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

python-telegram-bot v20.7中CallbackQuery为NoneType的问题排查

修复方案

你的代码核心问题大概率是以下几个点,按顺序排查修复:

  • 替换占位令牌:代码里的TOKEN是占位符,必须替换成你从BotFather获取的机器人有效令牌。如果令牌无效,机器人无法和Telegram服务器建立连接,自然收不到回调请求,button_pressed函数也就不会执行。

  • 确认依赖版本:确保你安装的python-telegram-bot版本是v20.x系列,你的代码使用的是该版本的API(比如ApplicationBuilder、ContextTypes.DEFAULT_TYPE),如果版本不匹配(比如用了v13旧版本),会导致回调处理逻辑失效。可以通过pip install python-telegram-bot==20.7安装指定版本。

  • 添加基础错误防护:在button_pressed函数里增加对query的非空判断,避免因意外情况抛出异常:

async def button_pressed(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    if query is None:
        return
    await query.answer()
    if query.data == 'hello':
        await query.edit_message_text("Hello!")
  • 检查运行日志:运行代码时查看控制台输出,如果有令牌无效、网络连接失败等报错,先解决这些基础问题。

修复后的完整代码示例:

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
from telegram.constants import ParseMode
from telegram.ext import ApplicationBuilder, CommandHandler
from telegram.ext import filters, MessageHandler, ContextTypes, ConversationHandler, CallbackQueryHandler

async def hello_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton("Press me", callback_data='hello')]
    ]

    reply_markup = InlineKeyboardMarkup(keyboard)

    await update.message.reply_text('Press:', reply_markup=reply_markup)

async def button_pressed(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    if query is None:
        return
    await query.answer()
    if query.data == 'hello':
        await query.edit_message_text("Hello!")

if __name__ == '__main__':
    # 替换成你的机器人令牌
    TOKEN = "你的机器人令牌"
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler('hello', hello_command))
    app.add_handler(CallbackQueryHandler(callback=button_pressed))
    app.run_polling()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:32:21