Search code examples
javatelegramtelegram-bot

How can you get the message ID of currently sent message sent from telegram bot?


I have created a message and sent it using sendMessage with Telegram API.

How can I get the message ID of currently sent message?

import org.telegram.telegrambots.meta.api.methods.send.SendMessage;

...

SendMessage message = new SendMessage(); 
message.setChatId(chat_id)

try {
    execute(message);
} catch (TelegramApiException e) {
    e.printStackTrace();
}

// here is where I would like to get the id of the message I just sent above

Solution

  • From the docs:

    Send message

    All send requests (SendMessage, SendPhoto, SendLocation...) return SendResponse object that contains Message.

    So you'll need to capture the response of execute(message) to get the SendResponse.

    The message ID will be available on that object.


    Example code:

    public class App  {
        public static void main( String[] args ) {
    
            long chatId = 1234567;
    
            TelegramBot bot = new TelegramBot("ABCDEF......");
    
            SendResponse response = bot.execute(new SendMessage(chatId, "Hello!"));
            Message message = response.message();
            long messageId = message.messageId();
    
            System.out.println("Message id :");
            System.out.println(messageId);
    
            System.exit(0);
        }
    }
    

    Shows the following output:

    Message id :
    449