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

python-telegram-bot中ConversationHandler无法正常运行的问题求助

python-telegram-bot v20.1 ConversationHandler问题修复方案

问题根源

  1. 429请求限流:轮询模式下请求频率过高,触发Telegram API限流,导致getUpdates接口返回异常。
  2. ConversationHandler配置错误:v20.x版本对入口处理器、状态流转的要求与旧版本不同,错误配置会导致按钮、命令无响应。

修复步骤

1. 调整轮询参数解决限流

启动机器人时给run_polling()添加间隔和超时参数,降低请求频率:

application.run_polling(
    interval=1,  # 每次请求间隔1秒
    timeout=30,
    read_timeout=30,
    allowed_updates=Update.ALL_TYPES
)

2. 修正ConversationHandler核心配置

v20.x版本需用CommandHandler作为entry_points,同时正确配置states和fallbacks:

from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import (
    ApplicationBuilder, CommandHandler, MessageHandler,
    filters, ConversationHandler, CallbackContext
)

# 定义会话状态
START, CHOOSING = range(2)

async def start(update: Update, context: CallbackContext) -> int:
    reply_keyboard = [["选项1", "选项2"]]
    await update.message.reply_text(
        "欢迎开始,请选择选项:",
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
    )
    return CHOOSING

async def handle_option1(update: Update, context: CallbackContext) -> int:
    await update.message.reply_text("你选择了选项1,发送/cancel可结束会话")
    return CHOOSING

async def cancel(update: Update, context: CallbackContext) -> int:
    await update.message.reply_text("会话已取消")
    return ConversationHandler.END

def main():
    application = ApplicationBuilder().token("你的机器人TOKEN").build()

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],  # 正确用CommandHandler作为入口
        states={
            CHOOSING: [
                MessageHandler(filters.Regex("^选项1$"), handle_option1),
                MessageHandler(filters.Regex("^选项2$"), handle_option2)  # 自行实现该函数
            ]
        },
        fallbacks=[CommandHandler("cancel", cancel)]  # 配置cancel命令的 fallback
    )

    application.add_handler(conv_handler)
    application.run_polling(interval=1, timeout=30)

if __name__ == "__main__":
    main()

3. 处理InlineButton点击事件

若使用InlineKeyboardButton,需搭配CallbackQueryHandler并加入states:

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

async def start(update: Update, context: CallbackContext) -> int:
    keyboard = [
        [InlineKeyboardButton("选项A", callback_data="a")],
        [InlineKeyboardButton("选项B", callback_data="b")]
    ]
    await update.message.reply_text(
        "请选择:",
        reply_markup=InlineKeyboardMarkup(keyboard)
    )
    return CHOOSING

async def button_callback(update: Update, context: CallbackContext) -> int:
    query = update.callback_query
    await query.answer()
    await query.edit_message_text(text=f"你选择了:{query.data}")
    return CHOOSING

# 在ConversationHandler的states中添加:
CHOOSING: [
    CallbackQueryHandler(button_callback),
    CommandHandler("cancel", cancel)
]

4. 基础检查

  • 确认机器人TOKEN无拼写错误
  • 确保机器人已加入目标对话,且具备发送消息权限

关键提示

  • v20.x为异步版本,所有处理器必须用async def定义
  • 会话状态流转需通过返回状态常量或ConversationHandler.END控制
  • 严格遵守Telegram API限流规则,避免高频请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:53:18