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

创建Telegram Bot遇Updater初始化错误:unexpected keyword argument 'use_context'

解决Telegram Bot Updater初始化的TypeError问题

问题原因

你遇到的错误是因为**use_context=True参数在python-telegram-bot v14及以后的版本中已被移除**——从v14开始,上下文(Context)模式成为默认行为,不再需要手动指定这个参数。另外代码里还有两个小问题:

  • 导入的是小写filters,但代码中用了大写Filters
  • 如果使用的是v20+版本,Updater和Dispatcher已经被完全移除,需要改用Application类

解决方案

根据你使用的python-telegram-bot版本,选择对应的修复方式:

情况1:使用v14-v19版本

直接移除use_context=True参数,同时修正filters的大小写:

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters  # 改为大写Filters

TOKEN = 'mine_BOT_TOKEN'

def start_command(update, context):
    update.message.reply_text('Hello! Let\'s find you a match')

def echo(update, context):
    update.message.reply_text(update.message.text)

def main():
    updater = Updater(token=TOKEN)  # 移除use_context=True
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler('start', start_command))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

情况2:使用v20+版本(推荐,最新稳定版)

v20+彻底弃用了Updater和Dispatcher,改用Application类重构代码:

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

TOKEN = 'mine_BOT_TOKEN'

async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Hello! Let\'s find you a match')

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(update.message.text)

def main():
    application = ApplicationBuilder().token(TOKEN).build()

    application.add_handler(CommandHandler('start', start_command))
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    application.run_polling()

if __name__ == '__main__':
    main()

注意:v20+要求所有处理函数必须是异步函数(用async/await)。

额外提示

  • 可以通过pip show python-telegram-bot命令查看当前安装的版本
  • 不推荐降级到旧版本,旧版本已停止维护,存在安全风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:06:08