Search code examples
pythontelebot

why register_next_step_handler doesn't call a function immediately and waits for another message


I'm creating a simple bot using Telebot. The start func offers two buttons to the user (Currency/Weather). I expect the bot to move to the func "where_to_go" when a button is pressed. It happens only when I press the button twice or send any other second message. Then "where_to_go" func reads the first message. So it works, but why do I have to send one more message to push it? How can I fix it?

Here is the code:

@bot.message_handler(commands = ['start','main'])
    def start(message):
        markup = types.ReplyKeyboardMarkup()  
        btn1 = types.KeyboardButton('Currency Calc')
        markup.row(btn1)
        btn2 = types.KeyboardButton('Weather Today')
        markup.row(btn2)
        file = open('./Start Photo.png', 'rb')
        bot.send_photo(message.chat.id, file, reply_markup=markup)
        bot.send_message(message.chat.id,
                             f"Good night, {message.from_user.first_name} {message.from_user.last_name} 💋. \n")
        bot.send_message(message.chat.id, f"I'm PogodiPogoda Bot. Choose a button or just talk to me.", reply_markup=markup)
        bot.register_next_step_handler(message, where_to_go)
    
   
def where_to_go(message):
        
        if message.text == 'Currency Calc':
            bot.register_next_step_handler(message, converter)
        elif message.text == 'Weather Today':
            bot.register_next_step_handler(message, city)

The bot works well when he make the following step (from "where_to_go" to the funcs "converter" or "city").


Solution

  • You can try this :

    @bot.message_handler(commands = ['start','main'])
    def start(message):
        markup = types.ReplyKeyboardMarkup()  
        btn1 = types.KeyboardButton('Currency Calc')
        markup.row(btn1)
        btn2 = types.KeyboardButton('Weather Today')
        markup.row(btn2)
        file = open('./Start Photo.png', 'rb')
        bot.send_photo(message.chat.id, file, reply_markup=markup)
        bot.send_message(message.chat.id, f"Good night, {message.from_user.first_name} {message.from_user.last_name} 💋. \n")
        bot.send_message(message.chat.id, f"I'm PogodiPogoda Bot. Choose a button or just talk to me.", reply_markup=markup)
        # Register next step handler directly within the start function
        bot.register_next_step_handler(message, where_to_go)
    
    def where_to_go(message):
        if message.text == 'Currency Calc':
            converter(message)  # Call the function directly instead of registering another next step handler
        elif message.text == 'Weather Today':
            city(message)  # Call the function directly instead of registering another next step handler
    

    @bot will move to the where_to_go function immediately after the user selects an option, without the need for an additional message