0

I have this code, from https://stackoverflow.com/a/58314239/15473592

def city(update,context):
  list_of_cities = ['Erode','Coimbatore','London', 'Thunder Bay', 'California']
  button_list = []
  for each in list_of_cities:
     button_list.append(InlineKeyboardButton(each, callback_data = each))
  reply_markup=InlineKeyboardMarkup(build_menu(button_list,n_cols=1)) #n_cols = 1 is for single column and mutliple rows
  bot.send_message(chat_id=update.message.chat_id, text='Choose from the following',reply_markup=reply_markup)


def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None):
  menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
  if header_buttons:
    menu.insert(0, header_buttons)
  if footer_buttons:
    menu.append(footer_buttons)
  return menu

How can I remove a item from list when pressing the button from the list on telegram chat?

  • Hi. I suggest to edit "Telebot" -> "python-telegram-bot" in the questions title, as telepot is a module provided by a different library ;) – CallMeStag Jun 01 '21 at 07:13

1 Answers1

0

In order to change the keyboard, you'll have to edit it with edit_message_reply_markup or edit_message_text (which also edits the keyboard on the fly). So you'll have to

  1. check which button the user clicked
  2. build a new keyboard without that particular button

For 1., you can use the callback_data that's delivered along with the CallbackQuery. E.g. in the snippet from your question, the callback_data equals the buttons text. So you could do something like

for each in list_of_cities:
    if each != update.callback_query.data:
        button_list.append(InlineKeyboardButton(each, callback_data = each))

This will exclude the pressed buttom from the newly generated keyboard.

Maybe check out the inlinekeyboard.py example of PTB for some intuition on how inline buttons work on python-telegram-bot.


Disclaimer: I'm currently the maintainer of python-telegram-bot.

CallMeStag
  • 5,467
  • 1
  • 7
  • 22
  • Oops, I was using telebot instead of python-telegram-bot. I'll change the code to use python-telegram-bot instead. Thank you! – BernardoCR Jun 01 '21 at 13:06
  • If my answer was helpful, please consider [accepting](https://stackoverflow.com/help/someone-answers) it :) – CallMeStag Jun 07 '21 at 08:53