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

Telegram机器人报错TypeError: Updater.__init__()意外获取参数'token'的解决咨询

解决Telegram机器人TypeError: Updater.__init__() got an unexpected keyword argument 'token'错误

错误原因

这个报错是因为你使用的python-telegram-bot库版本为v20及以上,而你的代码是基于v13.x及更早版本编写的。v20+版本彻底重构了API,移除了Updater类初始化时的token和use_context参数,改用全新的Application架构。

两种解决方式

方式一:降级到兼容旧代码的库版本

如果你不想修改代码,可以直接把python-telegram-bot降级到v13.x版本(推荐13.7,是旧架构的最后一个稳定版本):

pip install python-telegram-bot==13.7

降级后你的原有代码可以直接正常运行。

方式二:升级代码适配v20+版本

如果你想使用最新版库的功能,需要修改代码适配新架构,修改后的完整代码如下:

from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes

# 替换为你的机器人Token
TOKEN = "YOUR_BOT_TOKEN"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Welcome to your Telegram bot!")

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("You requested help. Here are some available commands:\n"
                                  "/help - Show this help message\n"
                                  "/start - Start the bot")

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text = update.message.text
    if text == '/start':
        await start(update, context)
    elif text == '/help':
        await help_command(update, context)

def main():
    # 使用ApplicationBuilder初始化机器人
    application = ApplicationBuilder().token(TOKEN).build()
    
    # 添加命令处理器
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help_command))
    # 添加普通消息处理器
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    
    # 启动机器人
    application.run_polling()

if __name__ == '__main__':
    main()

主要改动点:

  • 用ApplicationBuilder().token(TOKEN).build()替代原有的Updater初始化逻辑
  • 所有消息处理函数改为异步函数(添加async关键字),发送消息时需加await关键字
  • 导入ContextTypes替代旧版的CallbackContext
  • 过滤器模块从Filters改为小写的filters(v20+版本的模块结构调整)
  • 启动机器人改用application.run_polling(),不再需要updater.idle()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:23:26