I want my telegram bot wait until user answers with telebot and callback handler

Viewed 980

I am writing a telegram bot with telebot. I have following piece of code:

@bot.message_handler(commands=["play"])
def game(message):
    bot.send_message(message.chat.id, 'Start')
    process(message)
    process2(message)

def process(message):
    arr = ['Ans1', 'Ans2', 'Ans3', 'Ans4']
    ans = ['1', '2', '3', '4']
    keyboard = keyboard_gen(arr, ans)
    bot.send_message(message.chat.id, text = 'Question1', reply_markup=keyboard)

def process2(message):
    pass

@bot.callback_query_handler(func=lambda call: True) 
def callback_worker(call):
    if call.data == 1:
        bot.send_message(call.message.chat.id, 'True')
    if call.data in [2, 3, 4]:
        bot.send_message(call.message.chat.id, 'False')

keyboard_gen generates keyboards. I need process1 to let user pick right option in process before starting process2. Is there any way to do so? My code immediately starts process2, but I have to be sure user picks right option.

1 Answers

This way of dealing with telegram bots is not recommended. Because each update is a separate request.

You need to use a database to store user's state and reply based on that state.

But here you can move process2 inside callback_worker and call it after the if conditions.

@bot.callback_query_handler(func=lambda call: True) 
def callback_worker(call):
    if call.data == 1:
        bot.send_message(call.message.chat.id, 'True')
    if call.data in [2, 3, 4]:
        bot.send_message(call.message.chat.id, 'False')
    process2()

Also you should remove message parameter from it, if you'd mentioned what you were going to do with process2() the solution might have been different.

Check my answer here about storing user state in a database.

Related