Axcent
Axcent

Reputation: 43

how to detect the Inline python button during the state aiogram

there is a code:


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)

in short, in this code the /start command launches state.set() and + inline keyboard is attached to the message. after entering the start command, the bot will wait for the text from the user, and then display it. but if at the stage when the bot is waiting for the text the user presses the inline button, the bot will display a message that it has stopped waiting for the text and will stop waiting for it

That would be fine, but the handler calback does not see the inline button pressed during state

in this code the /start command launches state.set() and + inline keyboard is attached to the message. after entering the start command, the bot will wait for the text from the user, and then display it. but if at the stage when the bot is waiting for the text the user presses the inline button, the bot will display a message that it has stopped waiting for the text and will stop waiting for it

Upvotes: 1

Views: 1306

Answers (1)

progerg
progerg

Reputation: 81

@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')

try like this

Upvotes: 1

Related Questions