简体   繁体   English

如何在 Telegram Bot API 中获取最新更新

[英]How to get most recent update in Telegram Bot API

I am struggling on how to get the text of a message to my C#-console tool with a telegram bot.我正在努力研究如何使用电报机器人将消息文本发送到我的 C#-console 工具。 Here is a piece of that is supposed to just print all messages in the telegram channel这是一块应该只打印电报频道中的所有消息

private async Task getTelegramMessage()
{
  var bot = new Telegram.Bot.TelegramBotClient("token")
  var updates = await bot.GetUpdatesAsync();
  foreach (var update in updates)
  {
    Console.WriteLine("Bot: " + update.Message.Text);
  }
}

the problem is that i always get all old updates.问题是我总是得到所有旧的更新。 The maximum length of the array updates is 100. So after I sent 100 messages in the telegram channel, I would only have access to the first 100 messages and no access to the newest.数组更新的最大长度是 100。所以在我在电报频道发送 100 条消息后,我只能访问前 100 条消息而无法访问最新的消息。 How can I get access to the most recent update?我如何才能访问最新的更新? Or can I somehow delete the message after my tool has processed it?或者我可以在我的工具处理完消息后以某种方式删除它吗?

I have seen that the bot provides the Event OnUpdate but I couldnt figure out how to use it.我已经看到机器人提供了 Event OnUpdate,但我不知道如何使用它。

Thanks a lot for help on that issue.非常感谢您在这个问题上的帮助。

oh, I just figured it out.哦,我刚刚想通了。 for the offset you have to set the ID returned in the update.对于偏移量,您必须设置更新中返回的 ID。

Notes 2. In order to avoid getting duplicate updates, recalculate offset after each server response.注意事项 2. 为了避免重复更新,每次服务器响应后重新计算偏移量。

Instead subscribe to the BotOnUpdateReceived event to handle the updates.而是订阅BotOnUpdateReceived事件来处理更新。 In main.cs:在 main.cs 中:

Bot.OnUpdate += BotOnUpdateReceived;
Bot.StartReceiving(Array.Empty<UpdateType>());
Console.WriteLine($"Start listening!!");
Console.ReadLine();
Bot.StopReceiving();

And handle the event:并处理事件:

private static async void BotOnUpdateReceived(object sender, UpdateEventArgs e)               
{               
    var message = e.Update.Message;
    if (message == null || message.Type != MessageType.Text) return;
    var text = message.Text;
    Console.WriteLine(text);
    await Bot.SendTextMessageAsync(message.Chat.Id, "_Received Update._", ParseMode.Markdown);
}

The Offset is internally working in it and it also internally call GetUpdatesAsync() . Offset 在内部工作,它也在内部调用GetUpdatesAsync()

From Here you can also get channel post via:从这里您还可以通过以下方式获取频道帖子:

var message = e.Update.ChannelPost.Text;  // For Text Messages

I hope it will Help!!我希望它会有所帮助!!

According documentation, you can use offset -1 to get the last update.根据文档,您可以使用 offset -1 来获取最后一次更新。 Just put in mind all previous updates will forgotten.请记住,所有以前的更新都会被遗忘。

getUpdates Docs获取更新文档

https://api.telegram.org/bot{TOKEN}/getUpdates?offset=-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM