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

初始化python-telegram-bot的Updater时触发TypeError错误求助

修复python-telegram-bot 20.x版本中Updater初始化错误

你遇到的TypeError: Updater.__init__() got an unexpected keyword argument 'token'错误,是因为python-telegram-bot 20.x版本彻底重构了核心API,Updater的初始化方式和旧版本完全不同。

错误信息

Traceback (most recent call last):
  File "C:\Users\Mustafa\Desktop\Telegram bot\my_telegram_bot.py", line 32, in <module>
    main()
  File "C:\Users\Mustafa\Desktop\Telegram bot\my_telegram_bot.py", line 21, in main
    updater = Updater(token='64xxxxxxxxxxxxxxxxxxxFmQM', use_context=True)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Updater.__init__() got an unexpected keyword argument 'token'

代码调整方案

20.x版本中,Updater不再直接接收token参数,需要通过ApplicationBuilder创建应用实例,同时还有几处API细节需要修改。以下是适配后的完整代码:

import os
from telegram import Update
from telegram.ext import (
    ApplicationBuilder,
    CommandHandler,
    MessageHandler,
    CallbackContext,
)
import telegram.ext.filters as filters
from pytube import YouTube

def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Send me a YouTube link with /download to get the video.')

def download_video(update: Update, context: CallbackContext) -> None:
    if not context.args:
        update.message.reply_text('请提供YouTube链接,格式:/download <视频链接>')
        return
    
    url = context.args[0]
    try:
        yt = YouTube(url)
        video = yt.streams.get_highest_resolution()
        # 直接指定下载文件名,避免重命名异常
        filename = f"{yt.title}.mp4"
        video.download(filename=filename)
        
        with open(filename, 'rb') as doc:
            update.message.reply_document(document=doc)
        
        os.remove(filename)
    except Exception as e:
        update.message.reply_text(f"下载失败:{str(e)}")

def main() -> None:
    # 用ApplicationBuilder创建应用实例,传入token
    application = ApplicationBuilder().token('646XXXXXXXXXXXXXXXXXXXXXXXXXmQM').build()
    
    # 获取调度器
    dispatcher = application.dispatch
    
    # 添加处理器,注意过滤器使用导入的filters而非旧版Filters
    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(CommandHandler('download', download_video))
    dispatcher.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, start))
    
    # 启动轮询
    application.run_polling()

if __name__ == '__main__':
    main()

关键变更点

  • 初始化方式替换:不再直接实例化Updater,改用ApplicationBuilder创建应用,token通过链式调用传入
  • 过滤器命名统一:原Filters改为filters(对应你代码中导入的telegram.ext.filters as filters)
  • 移除冗余参数:20.x版本默认启用上下文模式,无需use_context=True;CommandHandler默认传递参数,无需pass_args=True
  • 优化异常处理:增加参数校验和异常捕获,避免因非法输入导致机器人崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 15:53:43