Telegram-бот с потоком выдает исключение - PullRequest
0 голосов
/ 08 мая 2020

У меня два проекта и кусок кода. В одном из них все работает нормально, а в другом выдает эту ошибку. Как я могу решить эту проблему?

private void btnStart_Click(object sender, EventArgs e)
{

    botThread = new Thread(new ThreadStart(RunBot));
    botThread.Start();
}

private void RunBot()
{
    bot = new Telegram.Bot.TelegramBotClient(Token);

    this.Invoke(new Action(() =>
    {
        lblStatus.Text = "online";
        lblStatus.ForeColor = Color.Green;

        btnStart.BackColor = Color.Red;
        btnStart.Text = "stop";
    }));


    int offset = 0;

    botIsRun = true;
    while (botIsRun)
    {
        Telegram.Bot.Types.Update[] updates;
        try
        {
            updates =bot.GetUpdatesAsync(offset).Result;
        }
        catch (Exception ex)
        {

            MessageBox.Show("Erorr", "Error");
            botIsRun = false;
            this.Invoke(new Action(() =>
            {
                lblStatus.Text = "Offline";
                lblStatus.ForeColor = Color.Red;

                btnStart.BackColor = Color.LightGreen;
                btnStart.Text = "stop";
            }));
            continue;
        }



        foreach (var update in updates)
        {

            offset = update.Id + 1;

            if (update.Message == null)
            {
                continue;
            }

            string text = update.Message.Text.ToLower();
            var from = update.Message.From;
            var chatId = update.Message.Chat.Id;

            var a = update.Message.NewChatMembers;


            if (text.Contains("/start"))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("welcome " + from.Username)
                    .AppendLine("fromId: " + from.Id)
                    .AppendLine("From IsBot: " + from.IsBot)
                    .AppendLine("From LanguageCode: " + from.LanguageCode)
                    .AppendLine("From LastName: " + from.LastName)
                    .AppendLine("From SupportsInlineQueries: " + from.SupportsInlineQueries)
                    .AppendLine("From FirstName: " + from.FirstName)
                    .AppendLine("From CanJoinGroups: " + from.CanJoinGroups)
                    .AppendLine("From CanReadAllGroupMessages: " + from.CanReadAllGroupMessages);

                bot.SendTextMessageAsync(chatId, sb.ToString());
            }
        }
    }
}

в System.Threading.Tasks.Task.ThrowIfExceptional (Boolean includeTaskCanceledExceptions) в System.Threading.Tasks.Task 1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task 1.get_Result () в TelegramBot .FrmMain.RunBot () в C: \ Users \ MSP \ Desktop \ Telegram bot \ project \ TelegramBot \ TelegramBot \ FrmMain.cs: строка 59

1 Ответ

0 голосов
/ 08 мая 2020

Проблема в том, что вы смешиваете Syn c с кодом Asyn c, вы должны преобразовать private void RunBot() в private async Task RunBotAsync(), иначе вы потеряете исключение в updates =bot.GetUpdatesAsync(offset).Result; (также я оставляю вам пару комментариев по поводу того, что необходимо учитывать):

private void btnStart_Click(object sender, EventArgs e)
{
    //Convert your old [Thread botThread] variable to [Task botTask]
    botTask = RunBotAsync;    //Don't worry, as RunBot() is now async, it will not block your ui
}

private async Task RunBotAsync()
{
    bot = new Telegram.Bot.TelegramBotClient(Token);

    this.Invoke(new Action(() =>
    {
        lblStatus.Text = "online";          //YOu shoul check this part, because accesing Form components here could be risky (becouse the method could be executed in other theread different to the UI thread, then you can get an error)
        lblStatus.ForeColor = Color.Green;

        btnStart.BackColor = Color.Red;
        btnStart.Text = "stop";
    }));


    int offset = 0;

    botIsRun = true;
    while (botIsRun)
    {
        Telegram.Bot.Types.Update[] updates;
        try
        {
            updates = await bot.GetUpdatesAsync(offset);
        }
        catch (Exception ex)
        {

            MessageBox.Show("Erorr", "Error");
            botIsRun = false;
            this.Invoke(new Action(() =>
            {
                lblStatus.Text = "Offline";
                lblStatus.ForeColor = Color.Red;

                btnStart.BackColor = Color.LightGreen;
                btnStart.Text = "stop";
            }));
            continue;
        }



        foreach (var update in updates)
        {

            offset = update.Id + 1;

            if (update.Message == null)
            {
                continue;
            }

            string text = update.Message.Text.ToLower();
            var from = update.Message.From;
            var chatId = update.Message.Chat.Id;

            var a = update.Message.NewChatMembers;


            if (text.Contains("/start"))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("welcome " + from.Username)
                    .AppendLine("fromId: " + from.Id)
                    .AppendLine("From IsBot: " + from.IsBot)
                    .AppendLine("From LanguageCode: " + from.LanguageCode)
                    .AppendLine("From LastName: " + from.LastName)
                    .AppendLine("From SupportsInlineQueries: " + from.SupportsInlineQueries)
                    .AppendLine("From FirstName: " + from.FirstName)
                    .AppendLine("From CanJoinGroups: " + from.CanJoinGroups)
                    .AppendLine("From CanReadAllGroupMessages: " + from.CanReadAllGroupMessages);

                await bot.SendTextMessageAsync(chatId, sb.ToString());
            }
        }
    }
}
...