W
W
Willesp2021-07-19 22:28:33
Python
Willesp, 2021-07-19 22:28:33

How to timeout answer to an Aiogram question, using State?

For example: The bot asked your name and will wait for an answer to the question for 60 seconds, if there is no answer, it says goodbye, if there is an answer, it deletes the task.

Initially, I implemented this through Asyncio -> create_task, if a response is received, I complete the task.
My code:

async def cancel_wait(task_id):
    for task in asyncio.all_tasks():
        if task.get_name() == task_id:
            task.cancel()

# Ранее я запустил задачу так
@dp.message_handler(commands=['start'])
async def start_bot(message: types.Message, state: FSMContext):
    await User.name.set()
    asyncio.create_task(wait_message(message, state), name=message.from_user.id)
    await message.answer(text="Привет")
# callback
async def wait_message(message: types.Message, state: FSMContext):
    await asyncio.sleep(60)
    await state.finish()
    await message.answer("Жаль, что ты так и не ответил...")

But I'm not sure if this is the correct implementation, besides, if the bot is restarted, then all tasks will be reset...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Bl4ckm45k, 2021-07-20
@Willesp

@dp.message_handler(state=Add.test_state)
@dp.message_handler(commands=['start'])
async def start_bot(message: types.Message, state: FSMContext):
    if message.text == '/start':
        await message.answer(text="Отправь мне свое имя")
        await Add.test_state.set() # Ваш state
        await asyncio.sleep(5) # 5 сек спим
        try:
            data = await state.get_data()
            if data['get_name'] == 'true':
                pass
        except KeyError: 
            # Если пользователь не ответил или за это время state завершился, получаем KeyError
            await message.answer(f'Жаль, что ты не ответил')
            await state.finish()
    else:
        await state.update_data(get_name='true')
        await message.answer(f'Твое имя {message.text}')
        # Установите следующие состояние
        # Если вы завершите состояние, то тогда бот ответит  'Жаль, что ты не ответил'

How it worked
60f69e24ad752236650893.png

A
Abraham lary, 2021-07-19
@SimpleMakc

use asyncio.sleep(60) and then process

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question