Wait for user input before a send_message

Viewed 1148

I'm having a problem with handling incoming messages. I have a main menu in my bot with one InlineKeyboardMarkup. When the button is pressed, the bot should wait for user input and then send a message. But in my case, it sends the message, then it waits for user input and then it sends again the message. And that's a big problem, because after the message it sends, it should go back to main menu.

I'm using pythonTelegramBotAPI (telebot)

That's the code:

  @bot.callback_query_handler(func = lambda call: True)
    def query_handler(call):
        bot.answer_callback_query(callback_query_id = call.id, text = '')
    
        cid = call.message.chat.id
        mid = call.message.message_id
        msg = call.message
    
     
        if call.data == 'request':
            bot.edit_message_text('Test - Answer to request', cid, mid, reply_markup = markup)
            request_handler(msg)
    
    ################# Keyboard sections #################
    
    @bot.message_handler()
    def request_handler(msg):
    
        if msg.content_type == 'text':
           bot.send_message(msg.chat.id, 'Request accepted')

# and here the code to go back, that I didn't do yet
2 Answers

Correct answer

The decorator @bot.messge_handler() is used to tell to the function that it must be handle incoming messages. So, when there's a new message, the function will do the code inside it automatically. This means that the function must not be called manually as is not required. Calling the function will, in fact, run the code inside it, instead of initializing it and waiting for an input.

And here's a tip: if the user send a message, the function is automatically called. But what happens when the bot send a message? The function is also called, because it doesn't make difference about who sent the message. So, to avoid using the function also for bot messages, just put an if in like this:

if msg.from_user.is_bot == False:
   # Here put what the function should do

The if, as you can see, check if the message is coming from the bot.

Related