如何获取更新并回复电报机器人?

时间:2017-06-02 18:50:30

标签: c# bots telegram telegram-bot

这是我尝试连接电报机器人的代码

namespace telegramUpdate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        TelegramBotClient bot = new TelegramBotClient("xxxxxxxxx");
        int offset = 23;
        Update temp = null;
        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    var m = Task.Run(async()=> bot.GetUpdatesAsync(offset,50)).Result;
                    foreach (var x in m.Result)
                    {
                        switch (x.Type)
                        {
                            case UpdateType.MessageUpdate:
                                temp = x;
                                backgroundWorker1.ReportProgress(0);
                                bot.SendTextMessageAsync(x.Message.Chat.Id, ":)").ConfigureAwait(false);
                                break;
                        }
                        offset = x.Id+1;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);

                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label1.Text = temp.Message.From.FirstName;
        }
    }
}

在破坏消息框后显示"发生了一个或多个错误。"问题是什么?电报机器人应回复":)"但它不是。我无法确定是否收到任何更新。

2 个答案:

答案 0 :(得分:0)

试试这个:

 bot.SendTextMessageAsync(x.Message.Chat.Id, ":)").GetAwaiter().GetResult();

你没有执行任务。只是它

答案 1 :(得分:0)

对我来说,在使bot.SendTextMessageAsync我收到相同的异常时,最近也发生了同样的错误(代码在2020年2月起作用,但以后不再起作用)。经过一番研究,我发现了这个主题[Telegram Bot stops with An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll 真正解决了我的问题。

    using System.Net;

    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;