如何获取电报机器人发送的当前已发送消息的消息 ID?

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

我创建了一条消息并使用 sendMessage 和 Telegram API 发送了它。

如何获取当前发送的消息的消息ID?

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

来自docs

Send message

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

因此您需要捕获 execute(message) 的响应以获得 SendResponse

消息 ID 将在该对象上可用。


示例代码:

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

显示以下输出:

Message id :
449