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

python-telegram-bot点击内联键盘报错:TypeError缺失context参数

解决python-telegram-bot点击内联键盘出现的TypeError问题

你的代码存在三个关键问题,导致了TypeError: start2() missing 1 required positional argument: 'context'错误,以下是问题说明和修正方案:

问题分析

  • CallbackQueryHandler参数顺序错误:你把pattern和回调函数的位置写反了,正确的参数顺序是CallbackQueryHandler(回调函数, pattern=匹配规则),颠倒后框架无法正确传递参数。
  • 回调函数未使用异步定义:python-telegram-bot v20+版本要求所有回调函数必须是异步函数(用async def定义),且异步方法调用必须加await,你写的start2是同步函数,调用edit_message_text时也没加await。
  • 缺少回调查询应答:处理内联键盘回调时,必须先调用update.callback_query.answer(),否则用户端会一直显示加载状态,还可能引发异常。

修正后的代码

from telegram.ext import ApplicationBuilder, CommandHandler, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram import Update
from telegram.ext import ContextTypes

from TOKEN import TOKEN


keyboard = [
    [InlineKeyboardButton("Start", callback_data="start")],
]

start_query_keyboard = InlineKeyboardMarkup(keyboard)


async def start(update, context):
    await update.message.reply_text("Hello World!", reply_markup=start_query_keyboard)

async def start2(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    # 应答回调查询,消除用户端加载状态
    await update.callback_query.answer()
    # 异步编辑消息文本
    await update.callback_query.edit_message_text("START", reply_markup=start_query_keyboard)


if __name__ == "__main__":
    app = ApplicationBuilder().token(TOKEN).build()

    # 修正CallbackQueryHandler的参数顺序
    app.add_handlers([CommandHandler("start", start), CallbackQueryHandler(start2, pattern="start")])

    app.run_polling(stop_signals=None)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:31