2
votes

I am using the Python Telegram BOT API for building a demo application. The task I am trying to achieve is to create a custom keyboard and then keep editing the keyboard keys upon each interaction with the user. I tried using "edit_message_reply_markup" but I get an error "Message Can't be edited". Is it not possible to edit a custom keyboard?

Here is the sample code that I have written for my task.

Initial Task:

FirstKeyboard = [[KeyboardButton(text = "FRUITS"), KeyboardButton(text = "VEGITABLES"), KeyboardButton(text = "DRINKS")],[KeyboardButton(text = "SNACKS"), KeyboardButton(text = "CHIPS"), KeyboardButton(text = "NOTHING")],[KeyboardButton(text = "DONE")]]
menu = ReplyKeyboardMarkup(FirstKeyboard)
KeyboardMessageID = context.bot.send_message(chat_id = chatID, text = "Select What you Like", reply_markup = menu)

Edit Task:

SecondKeyBoard = [[KeyboardButton(text = "APPLE"), KeyboardButton(text = "BANANA"), KeyboardButton(text = "PUMPKIN")],[KeyboardButton(text = "ORANGES"), KeyboardButton(text = "GRAPES"), KeyboardButton(text = "WINE")],[KeyboardButton(text = "DONE")]]
menu = ReplyKeyboardMarkup(SecondKeyBoard)
KeyboardMessageID = context.bot.edit_message_reply_markup(chat_id = chatID, message_id = KeyboardMessageID, reply_markup = menu)

I get an Error "Message can't be edited"

3
use context.message.reply_text("your text", reply_markup=your key board markups). and be sure that at least one of text or markup changed then you got error for same input. - mujad

3 Answers

1
votes

You can send a new message with new KeyboardButton instead of editing previous message. New ReplyKeyboardMarkup will be replaced with the old ReplyKeyboardMarkup automatically. using:

context.bot.send_message(chat_id = chatID, text = "Select What you 
Like", reply_markup = NEW_Menu)

or reply to your user with:

update.message.reply_text(text = "Select What you Like", reply_markup = NEW_Menu)

You can change your text in the new massage or put it as the previous one.

1
votes

https://core.telegram.org/bots/api#updating-messages

Looks like at the moment we can edit inline keyboards, and can't edit reply keyboards

0
votes

As a workaround I delete previous message and dublicate it except reply_markup parameter. In your case something like:

context.user_data['last_message'] = context.bot.send_message(chat_id = chatID, text = "Select What you Like", reply_markup = menu)

# changing reply markup
last_message = context.user_data['last_message']
context.bot.delete_message(chat_id=update.effective_chat.id, message_id=last_message.message_id)
# create similar message except new menu
context.user_data['last_message'] = context.bot.send_message(chat_id = last_message.chat_id, text = last_message.text, reply_markup = new_menu)