Telegram Bot Utilities – examples: Receive updates

Receive bot’s Updates

The “getUpdates” method accepts three parameters:

  • The first parameter is the starting id (i.e. the minimum id of the first update being returned)
  • The second one is called limit: the number of updates being read in the current call (if it is set to less than 1 it will return all the avaiable updates)
  • The last parameter is the timeout for the request (if set to less than 1 it will not set a timeout)

Here you can see a small piece of code that shows how to receive incoming updates:

public static void main(String[] args) throws GettingUpdatesException, IOException {
    String yourToken = "YOUR TOKEN";
    // Instantiates bot
    TelegramBot b = new TelegramBot(yourToken);
    // Instantiates updates array
    Update[] updates;
    try {
        // Try to receive incoming updates from the bot
        updates = b.getUpdates(-1, -1, -1);
    } catch (EmptyUpdatesException e) {
        e.printStackTrace();
    }
    // Iterate over the updates
    for (int i = 0; i < updates.length; i++) {
        //An update could have no message (e.g. it is an inline query, or other)
        if(updates[i].getMessage() != null) {
            // If there is a Message into the current update, then print it
            System.out.println(updates[i].getMessage().getText());
        }
    }
}

Here you can see how you can use that method in order to create an echo bot:

Previous Entries Telegram Bot Utilities - examples: send a simple message Next Entries Telegram Bots Utilities - examples: send a photo

2 thoughts on “Telegram Bot Utilities – examples: Receive updates

  1. Hi!
    Is there a way to create an async version of getUpdates()? So that I can call it and make some other thing? I’ve read doc but I don’t understand, what are offset, limit and timeout parameters in getUpdates method. Can you explain me please?
    Thanks in advice and sorry for disturbe.

    • leocus on said:

      Hi!
      You could create a new Thread running getUpdates().
      For the other question offset is the offset from which you can read updates, limit is the number of updates to read and timeout is the timeout for the request. If you don’t know how to use them set them to -1.
      Thank you for using my library 😀

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.