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

如何在点击InlineButton时触发Telegram Bot的指定命令?

解决Telegram Bot点击InlineButton触发指定命令的问题

核心问题分析

你的代码存在两个关键问题导致按钮点击无法触发/home逻辑:

  1. query_func中调用异步函数home_func时未使用await,异步函数必须通过await才能执行。
  2. 回调查询的update对象与命令触发的update结构不同:命令触发时update.message有效,但回调触发时,消息对象位于update.callback_query.message,直接调用home_func会导致update.message为None,无法发送消息。

修改后的完整代码

from telegram import (
    ReplyKeyboardMarkup, ReplyKeyboardRemove, Update,
    InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton
)

from telegram.ext import (
    Application,
    CommandHandler,
    ContextTypes,
    ConversationHandler,
    CallbackQueryHandler,
    MessageHandler,
    filters,
)

token = 'abc'

async def start_func(update, context):
    home_btn = [
        [
            InlineKeyboardButton('home', callback_data='home'),  # 去掉斜杠,简化判断
            InlineKeyboardButton('profile', callback_data='executive_menu'),
        ]
    ]

    reply_markup = InlineKeyboardMarkup(home_btn)

    await update.message.reply_text('start_message', reply_markup=reply_markup)


async def thanks_func(update, context):
    await update.message.reply_text('thanks_message')


async def home_func(update, context):
    # 兼容命令触发和回调触发两种场景,获取正确的消息对象
    if update.message:
        msg_obj = update.message
    elif update.callback_query:
        msg_obj = update.callback_query.message
    else:
        return
    
    await msg_obj.reply_text('testing home 0')
    await msg_obj.reply_text('testing home 1')


async def query_func(update, context):
    query = update.callback_query
    # 根据回调数据匹配对应的逻辑
    if query.data == 'home':
        await home_func(update, context)  # 必须用await调用异步函数
    elif query.data == 'executive_menu':
        # 可添加profile菜单的逻辑
        await query.message.reply_text('进入profile菜单')
    await query.answer()


def main() -> None:
    application = Application.builder().token(token).build()
    # handlers
    start_handler = CommandHandler('start', start_func)
    thanks_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), thanks_func)
    home_handler = CommandHandler('home', home_func)
    query_handler = CallbackQueryHandler(query_func)
    
    application.add_handler(start_handler)
    application.add_handler(thanks_handler)
    application.add_handler(home_handler)
    application.add_handler(query_handler)
    
    application.run_polling()


if __name__ == "__main__":
    main()

关键修改说明

  • 兼容两种触发场景:修改home_func,通过判断update的属性,分别获取命令触发时的update.message和回调触发时的update.callback_query.message,确保消息发送逻辑正常。
  • 异步函数调用规范:在query_func中调用home_func时添加await,保证异步函数能正确执行。
  • 简化回调数据:将callback_data从/home改为home,让判断逻辑更简洁,避免不必要的字符串处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:00:05