python-3.x - 我希望我的 Telegram Bot 等到用户使用远程机器人和回调处理程序应答

标签 python-3.x telegram telegram-bot

我正在用远程机器人编写一个 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/

相关文章:

list - 将 Python 3 列表写入 .csv

python - 将 tkinter 中的表格居中

linux - 由于 poppler,在 CentOS 上的 Python 3.6 中安装 pdftotext 时出现问题

nginx - 无法在 Telegram bot webhook 中使用 Let's Encrypt 证书(自签名证书工作正常)

javascript - 2 Java 脚本中的比较 - Telegram Bot

Telegram Bot : How to mention user by its id (not its username)

python - 获取 dateutil.parse 中的格式

telegram - AuthKeyDuplicatedError 电视节目

java - UnsatisfiedLinkError:在 Telegram 项目中出现此错误

telegram-bot - 在 Bot Framework 中使用 Slack 中的斜杠命令?