So, I’m interested to know: is there any more practical way to organize chains of states than the one I suggested below?
Some commands in my bot, such as unlock and about, imply performing the same function at the beginning: getting the user Id, but the first command requires going to the next step, but the second one does not require anything else and just sends a message to the administrator.
I thought about how the get_id
function would not be duplicated for different chains and it turned out what I suggest below (I can write telegram bots and what I’m asking here is just a research experiment)
handlers.py
from .chains import AdminStates
from .objects import User, Chain
class AdminHandlers:
router = Router()
states = AdminStates()
chain = None
@router.message(states.get_id)
async def get_id(message: Message, state: FSMContext) -> None:
text = message.text
await message.answer(text)
next_state = AdminHandlers.chain.next_state()
if next_state is None:
await state.clear()
await state.set_state(AdminHandlers.states.chat)
else:
await state.set_state(next_state)
@router.message(Command("about"))
async def command_about_handler(message: Message, state: FSMContext) -> None:
user = User(message)
await user.intitialize()
if user.is_admin:
AdminHandlers.chain = Chain([AdminHandlers.states.get_id])
await state.set_state(AdminHandlers.chain.next_state())
objects.py
from aiogram.fsm.state import State
class Chain:
def __init__(self, states: list[State]) -> State | None:
self.iterator = iter(states)
self.position = 0
self.len = len(states)
def next_state(self) -> None:
if self.position < self.len:
self.position += 1
return next(self.iterator)
return None
P.S.:
I would just like to know your opinion about this approach to the organization of handlers (in the form of classes) and chains of states in this form