references/fsm.md
# Finite State Machine (FSM)
Core flow
- Define states with `StatesGroup`.
- Use `FSMContext` in handlers to set state, update data, and clear.
- Separate handlers by state to guide multi-step dialogs.
Storage options
- `MemoryStorage` for dev/test.
- `RedisStorage` and `MongoStorage` for production/persistence.
- Customize keys with `KeyBuilder` if needed.
Managing other users
- Use `dispatcher.fsm.get_context(bot=..., chat_id=..., user_id=...)` to access another user's state.
See:
- `docs/dispatcher/finite_state_machine/index.rst`
- `docs/dispatcher/finite_state_machine/storages.rst`
- `examples/finite_state_machine.py`
- `examples/scene.py`, `examples/quiz_scene.py`
references/handlers-filters.md
# Handlers, routers, and filters
Routers and observers
- Create `Router` instances and register handlers via observer decorators (e.g., `@router.message(...)`).
- `Dispatcher` is a root router; include feature routers with `include_router`/`include_routers`.
- Common observers: `message`, `edited_message`, `callback_query`, `inline_query`, `my_chat_member`, `chat_member`, `chat_join_request`, `poll`, `shipping_query`, `pre_checkout_query`, etc.
- Handlers must be `async def`.
Filtering behavior
- The dispatcher stops at the first handler whose filters pass.
- If no filters are provided, the handler matches everything for that observer type.
- Use `F` (MagicFilter) to check event attributes safely: `F.text`, `F.sticker`, etc.
Built-in filters
- Use built-in filters like `CommandStart`, `Command`, `CallbackData`, and magic filters.
- Custom filters can be sync, async, lambda, awaitable, or `Filter` subclasses.
Combining filters
- Multiple filters in a decorator are ANDed.
- For OR, register the handler multiple times or use `or_f`.
- Negate with `~` or `invert_f`.
Passing data from filters
- Filters can return `dict` to inject data into handler kwargs.
- Magic filter `.as_(...)` can also inject values into context.
See:
- `docs/dispatcher/router.rst`
- `docs/dispatcher/filters/index.rst`
- `examples/own_filter.py`
references/middleware-di-errors.md
# Middlewares, dependency injection, and errors
Middlewares
- Two layers: outer (before filters) and inner (after filters, before handler).
- Register with `<router>.<event>.outer_middleware(...)` or `<router>.<event>.middleware(...)`.
- Middleware must call `await handler(event, data)` to continue processing.
- Implement as `BaseMiddleware` subclass or async callable.
Dependency injection (context data)
- Handler/filter kwargs are resolved from context data.
- Inject custom context data via:
- `Dispatcher(..., foo=42)`
- `Dispatcher.start_polling(..., bar="Bazz")`
- `SimpleRequestHandler(..., bar="Bazz")` for webhooks
- `dp["eggs"] = Spam()`
- Returning a dict from a filter
- Type hints: extend `MiddlewareData` to document custom context keys.
Errors
- Prefer local try/except inside handlers for known failures.
- Use router or dispatcher error handlers for global handling:
- `@router.error(...)` for scoped handling
- `@dispatcher.error(...)` for global
- `ErrorEvent` exposes `exception` and update context.
See:
- `docs/dispatcher/middlewares.rst`
- `docs/dispatcher/dependency_injection.rst`
- `docs/dispatcher/errors.rst`
- `examples/error_handling.py`
references/quickstart.md
# Quickstart skeleton (v3)
Use this as the minimal structure for a bot that uses Router + Dispatcher:
- Create `Bot` with a token.
- Create `Dispatcher` as the root router.
- Create feature routers and `include_router` into the dispatcher.
- Register handlers via router observers (e.g., `@router.message(...)`).
- Start update delivery with `start_polling` or webhook controller.
Minimal long-polling shape:
```python
import asyncio
from aiogram import Bot, Dispatcher, Router, types
router = Router()
aio_token = "..."
@router.message()
async def handle_message(message: types.Message) -> None:
await message.answer(message.text or "")
async def main() -> None:
bot = Bot(aio_token)
dp = Dispatcher()
dp.include_router(router)
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
```
Notes:
- `Dispatcher` is the root `Router` and should be the top-level entry point for routing updates.
- Handlers must be `async def`.
- Prefer small, focused routers grouped by feature/domain.
Examples to consult in this repo:
- `examples/echo_bot.py`
- `examples/without_dispatcher.py` (direct Bot API usage)
- `examples/multi_file_bot/`
references/updates.md
# Update delivery (long polling vs webhook)
Long polling
- Use `Dispatcher.start_polling` or `Dispatcher.run_polling`.
- Only one polling process per bot token, or Telegram returns an error.
- If you need to scale or run multiple bots, prefer webhooks.
- See `docs/dispatcher/long_polling.rst` and `examples/echo_bot.py`.
Webhook
- Webhook and polling are mutually exclusive.
- Use `aiogram.webhook.aiohttp_server` controllers for aiohttp integration:
- `BaseRequestHandler`, `SimpleRequestHandler` (single bot), `TokenBasedRequestHandler` (multi-bot).
- Validate incoming requests with secret token or IP filtering middleware.
- For non-aiohttp frameworks, parse request JSON into `Update` and call `dispatcher.feed_update`.
- See `docs/dispatcher/webhook.rst`, `examples/echo_bot_webhook.py`, `examples/echo_bot_webhook_ssl.py`.
Manual update feeding
- `Dispatcher.feed_update` accepts `Update` objects.
- `Dispatcher.feed_raw_update` accepts raw dict updates.
references/utils.md
# Utilities: keyboards, formatting, i18n
Keyboard builder
- Use `InlineKeyboardBuilder` / `ReplyKeyboardBuilder` for dynamic layouts.
- Prefer explicit markup for static keyboards.
- Adjust grid with `builder.adjust(...)` and export with `builder.as_markup()`.
- See `docs/utils/keyboard.rst`.
Formatting helpers
- `aiogram.utils.formatting` builds message entities without manual HTML/Markdown.
- Use `Text`, `Bold`, `Italic`, `HashTag`, `as_list`, `as_section`, etc., then `as_kwargs()`.
- See `docs/utils/formatting.rst`.
I18n
- Uses gettext and Babel; install extras with `aiogram[i18n]`.
- Use `gettext` (`_`) for runtime strings, `lazy_gettext` (`__`) when language is not known.
- Use an I18n middleware (`SimpleI18nMiddleware`, `FSMI18nMiddleware`, etc.).
- See `docs/utils/i18n.rst`.
SKILL.md
---
name: aiogram-framework
description: Build, refactor, or troubleshoot Telegram bots using aiogram v3. Use when working with aiogram routers/handlers/filters, Dispatcher lifecycle, update delivery (long polling or webhook), FSM, middleware/DI, error handling, or aiogram utilities like keyboards, formatting, and i18n.
---
# Aiogram Framework
## Overview
Use this skill to design or modify aiogram-based bots in this repository with v3 patterns and the local docs/examples.
## Workflow
1. Choose update delivery (polling vs webhook) and note any scaling or multi-bot needs. See `references/updates.md`.
2. Define dispatcher/router layout and handler registration. See `references/quickstart.md` and `references/handlers-filters.md`.
3. Add filters and context injection (including custom filters) as needed. See `references/handlers-filters.md` and `references/middleware-di-errors.md`.
4. Add middleware and error handling for cross-cutting concerns. See `references/middleware-di-errors.md`.
5. Add FSM if the flow is multi-step or needs user state. See `references/fsm.md`.
6. Use utilities (keyboards, formatting, i18n) where they reduce boilerplate. See `references/utils.md`.
7. Cross-check with local examples under `examples/` before finalizing.
## Reference Map
- Quickstart and project shape: `references/quickstart.md`
- Update delivery details: `references/updates.md`
- Routers/handlers/filters: `references/handlers-filters.md`
- Middlewares, DI, errors: `references/middleware-di-errors.md`
- FSM and storage: `references/fsm.md`
- Utilities (keyboard/formatting/i18n): `references/utils.md`