skip to Main Content

I am struggling on how to get the text of a message to my C#-console tool with a telegram bot. 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. 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.

Thanks a lot for help on that issue.

3

Answers


  1. Chosen as BEST ANSWER

    oh, I just figured it out. for the offset you have to set the ID returned in the update.

    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. In 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().

    From Here you can also get channel post via:

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

    I hope it will Help!!

    Login or Signup to reply.
  3. According documentation, you can use offset -1 to get the last update.
    Just put in mind all previous updates will forgotten.

    getUpdates Docs

    https://api.telegram.org/bot{TOKEN}/getUpdates?offset=-1
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search