我正在用远程机器人编写一个 Telegram Bot 。我有以下代码:
@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 生成键盘。我需要 process1 让用户在启动 process2 之前在进程中选择正确的选项。有什么办法可以做到吗?我的代码立即启动 process2,但我必须确保用户选择正确的选项。
最佳答案
不推荐这种处理 Telegram Bot 的方式。因为每次更新都是一个单独的请求。
您需要使用数据库来存储用户的状态并根据该状态进行回复。
但在这里,您可以将 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()
执行的操作,解决方案可能会有所不同。
检查我的答案 here关于在数据库中存储用户状态
。
关于python-3.x - 我希望我的 Telegram Bot 等到用户使用远程机器人和回调处理程序应答,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64945147/