You can organize bot logic using Router objects and manage user flow using MemoryContext with StatesGroup.
- Routers: Use
Router() to create modular handlers that can be included in a main Dispatcher via dp.include_routers(router). - States: Define a class inheriting from
StatesGroup with State() members to represent different steps in a conversation. - Context: Use
MemoryContext to persist data (update_data, get_data) and manage the current state (set_state, get_state, clear). - Filtering: Use the
F magic filter to trigger handlers based on specific conditions, such as F.callback.payload == '...' or combining a message filter with a specific state (e.g., @dp.message_created(F.message.body.text, Form.name)).
from maxapi import Bot, Dispatcher, F
from maxapi.context import MemoryContext, State, StatesGroup
from maxapi.types import MessageCreated, CallbackButton
from maxapi.utils.inline_keyboard import InlineKeyboardBuilder
from maxapi import Router
# 1. Define States
class Form(StatesGroup):
name = State()
age = State()
router = Router()
# 2. Use Router and Context to manage state transitions
@router.message_callback(F.callback.payload == "btn_1")
async def handle_btn_1(event: MessageCallback, context: MemoryContext):
await context.set_state(Form.name)
await event.message.answer("Отправьте свое имя:")
# 3. Handle input within a specific state
@router.message_created(F.message.body.text, Form.name)
async def handle_name_input(event: MessageCreated, context: MemoryContext):
await context.update_data(name=event.message.body.text)
await event.message.answer(f"Hello, {event.message.body.text}!")