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

python-telegram-bot的ConversationHandler忽略fallbacks,/stop命令不生效怎么办

问题原因
  • 过滤器匹配范围问题:状态1中配置的MessageHandler(Filters.text, first_handler)所用的Filters.text默认会匹配所有文本类型消息,包含/开头的命令消息。ConversationHandler的执行规则是优先匹配当前状态下的handler,所有当前状态handler都不匹配时才会触发fallbacks,因此你发送的/stop会先被first_handler捕获,返回「First handler」,不会走到fallback逻辑。
  • stop函数参数缺失:即便fallback被触发,你写的stop函数中调用send_message时没有传入必填的chat_id参数,会直接抛出参数错误,无法正常发送「Good Bye」消息。
  • 额外小问题:entry_points中配置的CommandHandler('Start', start)命令名是大写S,Telegram命令通常为小写格式,用户输入小写/start时也可能触发异常,建议统一改为小写。
修复方案

按以下两处修改代码即可:

  1. 修正stop函数的参数问题:
def stop(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='Good Bye')
    return ConversationHandler.END
  1. 调整ConversationHandler配置,限制状态内handler的匹配范围,同时修正start命令的大小写:
conv_handler = ConversationHandler(
    entry_points=[CommandHandler('start', start)],
    states={
        1: [MessageHandler(Filters.text & ~Filters.command, first_handler,
                           pass_user_data=True)],
    },
    fallbacks=[CommandHandler('stop', stop)]
)

修改后状态内的handler只会匹配非命令的普通文本,发送/stop时会绕过状态handler触发fallback的stop函数,返回预期的「Good Bye」并结束会话。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:24:03