U
U
Umid Yakubbaev2021-05-17 14:14:58
Bots
Umid Yakubbaev, 2021-05-17 14:14:58

Why do telegram bots need states?

Why do telegram bots need states?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aztart, 2021-05-17
@Aztart

To differentiate the performance of certain functions. Functions for one state will not run in another and vice versa.
On the example of the Aiogram library

from aiogram import Bot, Dispatcher
from aiogram.utils.helper import Item, Helper

bot = Bot(token=BOT_TOKEN, parse_mode='HTML')
dp = Dispatcher(bot, storage=MemoryStorage())

#Создание двух состояний (Есть третье нулевое)
class ListOfStates(Help):
    STATE_0 = Item()
    STATE_1 = Item()

#Команда для нулевого состояния (Не присвоенного) для переключения бота в состояние STATE_0
@dp.message_handler(commands=['make_state'])
async def state_set(message: types.Message):
    state = dp.current_state()
    await state.set_state(ListOfStates.STATE_0)
    await message.answer('Бот в состоянии STATE_0')

#Команда для возвращения бота в нулевое состояние 
@dp.message_handler(commands=['comand'], state = ListOfStates.STATE_0())
async def state_answer(message: types.Message):
    state = dp.current_state()
    await state.reset_state()
    await message.answer('Бот в нулевом состоянии')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question