如何解决python-telegram-bot中Updater类的‘__init__() got an unexpected keyword argument 'token'’错误?
python-telegram-bot报错:init() got an unexpected keyword argument 'token'
我用Python开发Telegram机器人有段时间了,之前一切正常。今天启动新项目时出了一堆错误,卸载重装python-telegram-bot后,运行下面的简单代码还是报错:
from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, filters, CallbackContext, ConversationHandler from telegram import KeyboardButton def main(): updater = Updater(token="5934903868:AAGckQGHTbYwpAwdqGh9o5Zs2Hfdcb1PyZs") dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', startCommand)) updater.start_polling() updater.idle() if __name__ == '__main__': main()
遇到的错误:
init() got an unexpected keyword argument 'token'
问题原因
你重装后默认安装了python-telegram-bot的v20+版本,这个版本对API做了彻底重构:
Updater类不再支持直接传入token参数,且该类已被标记为废弃- 所有命令/消息处理函数要求使用异步写法(
async/await)
解决方案
方案1:升级代码适配v20+版本
改用Application替代Updater,同时调整处理函数为异步:
from telegram import Update from telegram.ext import Application, CommandHandler, CallbackContext # 处理函数必须是异步的,用async/await async def startCommand(update: Update, context: CallbackContext): await update.message.reply_text("欢迎使用机器人!") def main(): # 通过Application.builder()配置token application = Application.builder().token("5934903868:AAGckQGHTbYwpAwdqGh9o5Zs2Hfdcb1PyZs").build() # 添加命令处理器 application.add_handler(CommandHandler('start', startCommand)) # 启动轮询 application.run_polling() if __name__ == '__main__': main()
方案2:回退到旧版本API
如果你不想修改代码,可以指定安装兼容旧写法的v13.x版本:
pip uninstall python-telegram-bot -y pip install python-telegram-bot==13.7
内容的提问来源于stack exchange,提问作者johnx
相关产品推荐
相关产品推荐

