Answer the question
In order to leave comments, you need to log in
How to stop the loop on the next AIOGRAM command (Python)?
Hello, I want the loop execution to stop after I enter the stop command, how can I implement this? help me please
@dp.message_handler()
async def echo(message: types.Message):
if message.text == 'test':
sec = 0
while message.text == 'stop':
print(sec)
await asyncio.sleep(1)
sec += 1
Answer the question
In order to leave comments, you need to log in
No need to use a while loop in asynchronous code, and in general if the bot is designed for more than one user
Use storage
from aiogram.contrib.fsm_storage.memory import MemoryStorage
storage = MemoryStorage()
from aiogram.dispatcher import FSMContext
@dp.message_handler(commands=['start'])
async def start(message: types.Message, state=FSMContext):
await message.answer('Вы ввели команду /start, введите команду /stop или /cancel чтобы выйти из меню')
await state.set_state(YourState.name_state)
@dp.message_handler(commands=['stop'], state=YourState.name_state)
async def stop(message: types.Message, state=FSMContext):
await message.answer('Вы ввели команду /stop')
await state.finish()
@dp.message_handler(commands=['cancel'], state='*')
async def cancel(message: types.Message, state=FSMContext):
current_state = await state.get_state()
if current_state is None:
return
await state.finish()
await message.answer('Вы ввели команду /cancel')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question