ユーザーがテレボットとコールバックハンドラーで応答するまでテレグラムボットを待機させたい

Nov 22 2020

私はtelebotでtelegramボットを書いています。私は次のコードを持っています:

@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はキーボードを生成します。process2を開始する前に、ユーザーがプロセス中の正しいオプションを選択できるようにするために、process1が必要です。そうする方法はありますか?私のコードはすぐにprocess2を開始しますが、ユーザーが正しいオプションを選択していることを確認する必要があります。

回答

2 AliPadida Nov 21 2020 at 23:18

テレグラムボットを処理するこの方法はお勧めしません。各更新は個別のリクエストであるためです。

データベースを使用してユーザーの状態を保存し、その状態に基づいて返信する必要があります。

しかし、ここでは、process2内部に移動してcallback_worker、if条件の後で呼び出すことができます。

@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()

また、ソリューションでmessage何をしようとしていprocess2()たかが異なっていた可能性があると述べた場合は、パラメーターを削除する必要があります。

データベースへのユーザーの保存については、ここで私の答えを確認してくださいstate