Answer the question
In order to leave comments, you need to log in
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("Жаль, что ты так и не ответил...")
Answer the question
In order to leave comments, you need to log in
@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}')
# Установите следующие состояние
# Если вы завершите состояние, то тогда бот ответит 'Жаль, что ты не ответил'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question