Telegram Bot开发报错:Updater.__init__缺失update_queue参数
问题解决:Telegram Bot Updater初始化错误及功能实现
错误原因
你遇到的TypeError是因为python-telegram-bot v20+版本彻底重构了核心API,旧版本中Updater(TOKEN)的初始化方式已被废弃,新版本要求使用ApplicationBuilder创建Bot应用,同时Handler函数的参数结构也发生了变化。
关键修改点
- 替换
Updater初始化逻辑:用ApplicationBuilder替代旧的Updater创建Bot实例 - 更新Handler函数参数:所有处理函数需要接收
Update和Context参数,而非旧版的bot和update - 适配消息交互API:调整消息发送、编辑的调用方式以兼容新版本
修改后的完整代码
import telegram from telegram import InlineKeyboardMarkup, InlineKeyboardButton, Update from telegram.ext import ApplicationBuilder, CommandHandler, CallbackQueryHandler, ContextTypes from google.oauth2 import service_account import gspread # Telegram bot token TOKEN = 'xxxxxyyyyyy' # Google Sheets credentials SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SERVICE_ACCOUNT_FILE = 'C:/Users/ASUS/Downloads/credentials.json' spreadsheet_id = 'yyyyxxxxxxx' # Authenticate with Google Sheets API creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) # Function to fetch data from Google Sheets def get_sheet_data(sheet_name): gc = gspread.authorize(creds) sheet = gc.open_by_key(spreadsheet_id) worksheet = sheet.worksheet(sheet_name) return worksheet.get_all_values() # Command handler for starting the bot async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): keyboard = [ [InlineKeyboardButton("Dashboard", callback_data='Dashboard')], [InlineKeyboardButton("KPI", callback_data='KPI')] ] reply_markup = InlineKeyboardMarkup(keyboard) await update.effective_message.reply_text('Please choose:', reply_markup=reply_markup) # Callback handler for button presses async def button(update: Update, context: ContextTypes.DEFAULT_TYPE): query = update.callback_query await query.answer() # 必须调用此方法确认回调,否则Telegram会重复发送请求 sheet_name = query.data data = get_sheet_data(sheet_name) # 格式化表格数据,用竖线分隔列提升可读性 message = '\n'.join([' | '.join(row) for row in data]) # 处理超长消息:拆分内容适配Telegram单条消息4096字符限制 if len(message) > 4096: for i in range(0, len(message), 4096): await query.edit_message_text(text=message[i:i+4096]) else: await query.edit_message_text(text=message) def main(): # 使用ApplicationBuilder创建并配置Bot应用 application = ApplicationBuilder().token(TOKEN).build() application.add_handler(CommandHandler("start", start)) application.add_handler(CallbackQueryHandler(button)) # 启动轮询模式运行Bot application.run_polling() if __name__ == '__main__': main()
额外优化说明
- 新增
await query.answer():Telegram要求回调查询必须调用此方法确认,否则会持续重试请求 - 数据格式优化:用
|分隔列,比原代码的\t更易读 - 长消息处理:避免因内容超长导致发送失败的问题
- 回调数据对齐:将按钮回调数据与工作表名称统一,避免匹配错误
内容的提问来源于stack exchange,提问作者f3m
相关产品推荐
相关产品推荐

