How to check if user press the reply keyboard button? telegram bot python

Viewed 164

Easy task, but I can't figure out how to do it.
I'd like to check if user press the button 'Add variants' to add next messages from user to list variants. I tried to do it using if message.text == 'Add variants', but it just adds to the list text 'Add variants' one time and that's it. Is there any way to check if user click the button and after that add next messages from user to list?

variants = []

@bot.message_handler(commands=['start', 'welcome'])
def start(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item_1 = types.KeyboardButton('Random')
    item_2 = types.KeyboardButton('TradingView')
    item_3 = types.KeyboardButton('Weather')
    item_4 = types.KeyboardButton('Other')
    item_5 = types.KeyboardButton('Back')
    markup.add(item_1, item_2, item_3, item_4, item_5)

    bot.send_message(message.chat.id, 'Choose', reply_markup = markup)

@bot.message_handler(content_types=['text'])
def bot_message(message):

    if message.chat.type == 'private':
        if message.text == 'Random':
            
            markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
            item_1 = types.KeyboardButton('Add variants')
            item_2 = types.KeyboardButton('Back')
            markup.add(item_1, item_2)

            bot.send_message(message.chat.id, 'Choose', reply_markup = markup)
1 Answers

In this part of code you dont add anything to 'variants'. But as I understood: after user clicks 'Add variants' button you want to handle new message from user and add this message to a 'variants'. If so you need to register next_step_handler after you handeled 'Add variants' message.

Like that:

variants = []


@bot.message_handler(content_types=['text'])
def bot_message(message):

    if message.chat.type == 'private':
        if message.text == 'Add variants':
            msg = bot.send_message(message.chat.id, "Send me variant")
            bot.register_next_step_handler(msg, handling_variant)


def handling_variant(message):
    variants.append(message.text)

here is example of using next_step_handler

Related