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

aiogram状态中Inline Python按钮检测问题:回调Handler未触发

问题:FSM状态下Inline按钮回调无法触发

问题场景

用户发送/start命令后,Bot启动hi.hello状态,发送附带Cancel内联按钮的消息。此时Bot等待用户输入文本回复,但点击Cancel按钮时,对应的回调处理器无法响应点击操作。

问题原因

Aiogram的Dispatcher处理更新时,会优先匹配与当前FSM状态绑定的处理器。原代码中的@dp.callback_query_handler(text='Cancel')未指定状态匹配条件,默认仅在无FSM状态时触发,因此当用户处于hi.hello状态时,该回调不会被执行。

解决方案

给回调查询处理器添加状态匹配条件,可选择两种方式:

  • 明确指定匹配hi.hello状态
  • 使用state='*'匹配所有状态(适合全局通用的取消按钮)

修改后的代码

from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.dispatcher.filters.state import State, StatesGroup

storage = MemoryStorage()
bot = Bot(token=config.bot_token)
dp = Dispatcher(bot, storage=storage)

class hi(StatesGroup):
    hello = State()

@dp.message_handler(commands='start')
async def start(message: types.Message):
    repl = InlineKeyboardMarkup(row_width=1).add(InlineKeyboardButton(text='Cancel', callback_data='Cancel'))
    await bot.send_message(message.from_user.id, 'how are you?', reply_markup=repl)
    await hi.hello.set()

@dp.message_handler(state=hi.hello)
async def efe(message: types.Message, state: FSMContext):
    await bot.send_message(message.from_user.id, f'me too {message.text}')
    await state.finish()

# 方式1:仅匹配hi.hello状态下的Cancel回调
@dp.callback_query_handler(text='Cancel', state=hi.hello)
# 方式2:匹配所有状态下的Cancel回调(取消注释下方,注释上方)
# @dp.callback_query_handler(text='Cancel', state='*')
async def ponn(callback_query: types.CallbackQuery, state: FSMContext):
    await state.finish()
    await bot.send_message(callback_query.from_user.id, 'Canceled')
    # 可选:回调查询需要确认,避免用户看到加载状态
    await callback_query.answer()

if __name__ == '__main__':
    print('bot work')
    executor.start_polling(dp, skip_updates=True)

额外说明

添加await callback_query.answer()是为了告诉Telegram服务器已处理该回调,避免用户端按钮长时间处于加载状态,提升交互体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:42:27