python-telegram-bot版本升级后Updater初始化报错求助
解决python-telegram-bot v12+版本的Updater初始化问题
错误原因分析
1. SyntaxError:using-context=True
Python参数名不能包含连字符,正确写法是using_context=True,但这个参数在python-telegram-bot v12及以上版本已被移除——v12开始默认启用上下文功能,无需手动指定该参数。
2. TypeError:缺少update_queue参数
v12+版本中,Updater的构造函数逻辑发生变化,不再直接接受API密钥作为第一个位置参数,必须传入update_queue和bot实例,或者使用官方推荐的快捷方法创建实例。
修复方案
方案1:适配v12~v19版本
修改main函数中的Updater初始化代码,使用Updater.from_token()快捷方法创建实例,无需手动处理队列和Bot对象:
def main(): # 替换原Updater初始化代码 updater = Updater.from_token(keys.API_KEY) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start_command)) dp.add_handler(CommandHandler("help", help_command)) dp.add_handler(MessageHandler(Filters.text, handle_message)) dp.add_error_handler(error) updater.start_polling() updater.idle()
同时修复代码中变量名大小写错误:
将Response = R.sample_responses(text)改为response = R.sample_responses(text),避免后续调用reply_text(response)时触发NameError。
方案2:适配v20+版本(推荐,v20起Updater已被标记为废弃)
v20+版本采用异步架构,需调整代码结构为异步写法:
import constants as keys from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes import responses as R print('Bot starting ... ') async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text('type something random so') async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text('this is my help command.') async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): text = str(update.message.text).lower() response = R.sample_responses(text) await update.message.reply_text(response) async def error(update: Update, context: ContextTypes.DEFAULT_TYPE): print(f'Update {update} caused error {context.error}') def main(): application = ApplicationBuilder().token(keys.API_KEY).build() application.add_handler(CommandHandler("start", start_command)) application.add_handler(CommandHandler("help", help_command)) # 过滤掉命令消息,只处理普通文本 application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) application.add_error_handler(error) application.run_polling() print("polling ... ") main()
内容的提问来源于stack exchange,提问作者C9_HP
相关产品推荐
相关产品推荐

