You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-telegram-bot如何实现单函数内机器人响应多轮消息

问题原因

你当前的代码逻辑是同步线性执行的,触发/reqhelp命令时,request_help_function里拿到的update.message.text是用户刚发送的/reqhelp指令内容,不是机器人发完提示后用户的后续回复,所以会直接走完判断逻辑返回结果,不会等待用户输入。同时你的代码还存在变量名拼写错误:user_esponse少了字母r。

解决方案

使用python-telegram-bot内置的ConversationHandler实现多轮会话逻辑即可,完整修改方案如下:

  1. 先导入所需依赖组件
from telegram.ext import CommandHandler, MessageHandler, Filters, ConversationHandler
  1. 定义会话状态和拆分业务逻辑
# 定义等待用户回复的会话状态,用数字标识即可
WAITING_FOR_RESPONSE = 1

# 触发/reqhelp命令时的处理函数,仅负责发送提示并进入等待回复状态
def request_help_function(update: Update, context: CallbackContext):
    update.message.reply_text(
        "You are sending a help request to an admin. Type 'Cancel' if you don't want to do it."
    )
    # 返回状态,告诉ConversationHandler接下来要等待用户回复
    return WAITING_FOR_RESPONSE

# 接收用户后续回复的处理函数
def handle_user_response(update: Update, context: CallbackContext):
    user_response = update.message.text.strip()
    if user_response == "Cancel":
        message = "Ok, I cancelled the message"
    else:
        message = "Ok, I sent the message to an admin"
    update.message.reply_text(message)
    # 结束当前会话
    return ConversationHandler.END

# 可选:用户主动输入/cancel命令时直接中断会话的处理函数
def cancel_operation(update: Update, context: CallbackContext):
    update.message.reply_text("操作已取消")
    return ConversationHandler.END
  1. 替换原有Handler注册逻辑
# 构建多轮会话处理器
conv_handler = ConversationHandler(
    # 会话触发入口
    entry_points=[CommandHandler("reqhelp", request_help_function)],
    # 不同状态对应的处理规则,这里仅处理非命令的普通文本回复
    states={
        WAITING_FOR_RESPONSE: [
            MessageHandler(Filters.text & ~Filters.command, handle_user_response)
        ]
    },
    # 会话中断的兜底处理
    fallbacks=[CommandHandler("cancel", cancel_operation)]
)

# 注册会话处理器,删除你原来的普通CommandHandler注册逻辑
dispatcher.add_handler(conv_handler)

如果你使用的是v20+版本的python-telegram-bot,整体逻辑不变,只需要把所有处理函数改成异步写法、调用API时加await即可。

内容的提问来源于stack exchange,提问作者Christian Cristini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:45:03