I’m working with the python-telegram-bot library to build a Telegram bot using Python 3. I need help with editing a message that my bot already sent instead of creating a new one.
Right now my bot sends one message, waits a bit, then sends another message like this:
def handle_message(bot, update):
update.message.reply_text("Hold on, I'm thinking about it...")
time.sleep(5)
update.message.reply_text("Actually, I can't help you with this.")
What I want is to modify the first message instead of sending a second one. I attempted using this approach:
bot.editMessageText("Actually, I can't help you with this.",
chat_id=update.message.chat_id,
message_id=update.message.message_id)
This method works fine when I see it used with inline keyboards in tutorials, but it fails when I try to edit my bot’s previous message. How can I properly update the text of the last message my bot sent?
The error occurs because update.message.message_id refers to the user’s message ID instead of your bot’s. The solution is to save the return value of reply_text(), which contains the bot’s message ID. Here’s an updated example:
def handle_message(bot, update):
bot_message = update.message.reply_text("Hold on, I'm thinking about it...")
time.sleep(5)
bot.editMessageText(
text="Actually, I can't help you with this.",
chat_id=bot_message.chat_id,
message_id=bot_message.message_id
)
Using the correct message ID ensures you can edit the appropriate message.
you’ve got the message id mixed up! update.message.message_id is for the users msg. you should store the one from reply_text() like my_msg = update.message.reply_text("thinking...") then use my_msg.message_id to edit it. it’s a common mistake!
The issue you are facing stems from using update.message.message_id, which references the user’s message instead of your bot’s. When you call reply_text(), it returns a Message object containing your bot’s message ID. You should store that return in a variable to edit it later. Here’s how you can do it: python def handle_message(bot, update): sent_message = update.message.reply_text("Hold on, I'm thinking about it...") time.sleep(5) bot.editMessageText("Actually, I can't help you with this.", chat_id=update.message.chat_id, message_id=sent_message.message_id) I have made that mistake in my own bot’s development before. Just remember, each message has a unique ID; ensure you use the correct one.