如何获取 Telegram Bot API 的最新更新

问题描述 投票:0回答:4

我正在努力研究如何使用电报机器人将消息文本发送到我的 C# 控制台工具。这是其中的一部分,应该只是打印电报频道中的所有消息

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);
  }
}

问题是我总是收到所有旧的更新。数组更新的最大长度为 100。因此,当我在电报频道中发送 100 条消息后,我只能访问前 100 条消息,而无法访问最新的消息。我如何才能访问最新的更新?或者我可以在我的工具处理完该消息后以某种方式删除该消息吗?

我看到机器人提供了事件 OnUpdate,但我不知道如何使用它。

非常感谢您在这个问题上的帮助。

c# telegram
4个回答
5
投票

根据文档,您可以使用偏移量-1来获取最后的更新。 请记住,所有以前的更新都会被忘记。

获取更新文档

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

3
投票

而是订阅

BotOnUpdateReceived
事件来处理更新。在 main.cs 中:

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

并处理事件:

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);
}

Offset 在其内部工作,它也在内部调用

GetUpdatesAsync()

从这里您还可以通过以下方式获取频道帖子:

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

希望对您有帮助!!


2
投票

哦,我刚刚想通了。对于偏移量,您必须设置更新中返回的 ID。

注释 2. 为了避免重复更新,每次服务器响应后重新计算偏移量。


0
投票

我正在为企业技术支持团队开发 Telegtam 机器人,并遇到了同样的问题。

offset -1
方法中的
GetUpdatesAsync
参数帮助了我。我模拟了服务器上互联网关闭的情况,重新打开后我得到了最后一个更新。我使用临时窗口摆脱了它。这是更新处理程序的示例代码:

private static DateTime _lastUpdateTime = DateTime.UtcNow;


async static Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
bool isBotAlive = await botClient.TestApiAsync();

Update[] updates = await botClient.GetUpdatesAsync(-1, null, null, null, cancellationToken); //-1 to reject old updates


foreach (var updateItem in updates)
{
    try
      {
      DateTime updateTimestamp = updateItem.Message?.Date ?? DateTime.UtcNow;

      TimeSpan timeSinceLastUpdate = updateTimestamp - _lastUpdateTime;


      if ((timeSinceLastUpdate.TotalSeconds <= 15) && (DateTime.UtcNow - _lastUpdateTime < TimeSpan.FromSeconds(30)))
      {
          //My code for processing Update.Message and Update.callbackQuery
      }
      else
      {
          Console.WriteLine($"Old message. Received in {DateTime.Now.ToString("HH:mm:ss dd/MM/yyyy")}\n");
      }
      if (isBotAlive)
      {
          _lastUpdateTime = updateTimestamp;
      }
      }
      catch (Exception ex)
      {
          var error = $"Error update was caught {ex.Message}";
          Console.WriteLine(error);
          _logger.Error(error);
      }
}
}

启动机器人时,我还在 ReceiverOptions 中使用了

ThrowPendingUpdates = true
参数,但我不能确定该参数是否有效。

© www.soinside.com 2019 - 2024. All rights reserved.