如何在状态图中检测内联python按钮

v09wglhw  于 2023-03-24  发布在  Python
关注(0)|答案(1)|浏览(144)

有一个代码:

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()

@dp.callback_query_handler(text='Cancel')
async def ponn(message: types.CallbackQuery, state: FSMContext):
    await state.finish()
    await bot.send_message(message.from_user.id, f'Canceled')

if __name__ == '__main__':

    print('bot work')
    executor.start_polling(dp, skip_updates=True)

简而言之,在这段代码中,/start命令启动state.set。()和+ inline键盘附加到消息中。在输入开始命令后,bot将等待来自用户的文本,然后显示它。但是如果在bot等待文本的阶段用户按了inline按钮机器人将显示一条消息,表明它已停止等待文本,并将停止等待它
这很好,但是处理程序回调在状态期间看不到按下的内联按钮
在这段代码中/start命令启动state.set()和+ inline键盘被附加到消息.在输入start命令后,bot将等待来自用户的文本,然后显示它.但是如果在bot等待文本的阶段用户按下inline按钮,bot将显示一条消息,它已经停止等待文本,并将停止等待它

kgqe7b3p

kgqe7b3p1#

@dp.callback_query_handler(text='Cancel', state=hi.hello)
async def ponn(message: types.CallbackQuery, state: FSMContext):
    await state.finish()
    await bot.send_message(message.from_user.id, f'Canceled')

像这样尝试

相关问题