mirror of
https://github.com/aiogram/aiogram.git
synced 2026-04-08 16:37:47 +00:00
Added full support for the Bot API 9.6 (#1792)
* Added full support for the Bot API 9.6 * Add support for `managed_bot` updates * Set `description_parse_mode` default to `"parse_mode"` and use `DateTime` for `addition_date` in `PollOption` * Update changelog with features and changes from Bot API 9.6 * Add changelog fragment generator and update poll parameter descriptions
This commit is contained in:
parent
00c1130938
commit
9f49c0413f
107 changed files with 3077 additions and 328 deletions
42
.serena/memories/code_style.md
Normal file
42
.serena/memories/code_style.md
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# Code Style & Conventions
|
||||
|
||||
## General
|
||||
- `from __future__ import annotations` at the top of every Python file
|
||||
- Full type hints on all function signatures and class fields
|
||||
- Max line length: **99** characters (ruff enforced)
|
||||
- snake_case for Python names; camelCase used only in `__api_method__` strings
|
||||
|
||||
## Pydantic models
|
||||
- All Telegram types extend `TelegramObject(BotContextController, BaseModel)` from `aiogram/types/base.py`
|
||||
- `TelegramObject` is frozen; use `MutableTelegramObject` when mutation is needed
|
||||
- Fields default to `None` for optional API parameters; use `Field(None, json_schema_extra={"deprecated": True})` for deprecated fields
|
||||
- Use `Default("key")` sentinel (from `aiogram.client.default`) for user-configurable defaults like `parse_mode`, `protect_content`
|
||||
- `TYPE_CHECKING` guards for circular imports — keep runtime imports lean
|
||||
|
||||
## API Methods
|
||||
- Each method is a class inheriting `TelegramMethod[ReturnType]` from `aiogram/methods/base.py`
|
||||
- Required class attrs: `__returning__` (return type), `__api_method__` (camelCase string)
|
||||
- Fields with `None` default = optional param
|
||||
- Method docstring format: short description + `Source: https://core.telegram.org/bots/api#methodname`
|
||||
- File name: snake_case of method name (e.g., `SendMessage` → `send_message.py`)
|
||||
|
||||
## Imports order (ruff/isort enforced)
|
||||
1. stdlib
|
||||
2. third-party
|
||||
3. `aiogram` (first-party)
|
||||
4. relative imports
|
||||
|
||||
## Ruff rules enforced
|
||||
- A (annotations), B (bugbear), C4 (comprehensions), DTZ (datetimez), E, F, I (isort), PERF, PL (pylint), Q (quotes), RET, SIM, T10, T20, UP (pyupgrade)
|
||||
- Several PLR rules disabled (Telegram API naturally has many params/methods)
|
||||
- `F401` disabled (re-exports in `__init__.py` intentional)
|
||||
|
||||
## Code generation convention
|
||||
- **Never hand-edit generated files** (`.butcher/**/entity.json`, auto-generated `aiogram/types/*.py`, `aiogram/methods/*.py`, `aiogram/enums/*.py`)
|
||||
- Add features via `.butcher` YAML config/aliases + templates, then regenerate
|
||||
- After codegen: always run lint + mypy
|
||||
|
||||
## Naming patterns
|
||||
- Enums: PascalCase class, UPPER_SNAKE members (e.g., `ContentType.TEXT`)
|
||||
- Test files: `test_<module_name>.py`
|
||||
- Test classes: `Test<ClassName>` with `async def test_<scenario>(self, bot: MockedBot)`
|
||||
84
.serena/memories/codebase_structure.md
Normal file
84
.serena/memories/codebase_structure.md
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
# Codebase Structure
|
||||
|
||||
## Top-level layout
|
||||
```
|
||||
aiogram/ # Main package
|
||||
.butcher/ # Code generation inputs (DO NOT edit entity.json files)
|
||||
tests/ # Test suite
|
||||
docs/ # Sphinx documentation (RST)
|
||||
examples/ # Example bot scripts
|
||||
scripts/ # Version bump scripts
|
||||
CHANGES/ # Towncrier changelog fragments (CHANGES/<issue>.<category>.rst)
|
||||
```
|
||||
|
||||
## aiogram/ package
|
||||
```
|
||||
aiogram/
|
||||
├── __init__.py # Public API re-exports
|
||||
├── __meta__.py # Version (hatch reads this)
|
||||
├── exceptions.py # Framework exceptions
|
||||
├── loggers.py # Named loggers
|
||||
├── client/
|
||||
│ ├── bot.py # Bot class — all API methods as async shortcuts
|
||||
│ ├── session/ # HTTP session backends (aiohttp, base)
|
||||
│ ├── default.py # Default() sentinel for configurable defaults
|
||||
│ └── context_controller.py # Bot context injection into models
|
||||
├── types/
|
||||
│ ├── base.py # TelegramObject (Pydantic BaseModel), MutableTelegramObject
|
||||
│ ├── *.py # One file per Telegram type
|
||||
│ └── __init__.py # Exports all types
|
||||
├── methods/
|
||||
│ ├── base.py # TelegramMethod[T] base class
|
||||
│ ├── *.py # One file per API method (e.g., send_message.py → SendMessage)
|
||||
│ └── __init__.py
|
||||
├── enums/
|
||||
│ ├── content_type.py # ContentType enum
|
||||
│ ├── update_type.py # UpdateType enum
|
||||
│ └── *.py
|
||||
├── dispatcher/
|
||||
│ ├── dispatcher.py # Dispatcher (main update processor)
|
||||
│ ├── router.py # Router (Blueprint-style routing)
|
||||
│ ├── middlewares/ # Middleware system
|
||||
│ ├── event/ # Event observer, typed decorators
|
||||
│ └── flags/ # Handler flags
|
||||
├── filters/ # Built-in filters (Command, StateFilter, etc.)
|
||||
├── fsm/
|
||||
│ ├── context.py # FSMContext
|
||||
│ ├── state.py # State, StatesGroup
|
||||
│ └── storage/ # Memory, Redis, MongoDB storage backends
|
||||
├── handlers/ # Base handler types
|
||||
├── utils/
|
||||
│ ├── keyboard.py # Keyboard builder utilities
|
||||
│ ├── text_decorations.py # HTML/Markdown formatting
|
||||
│ └── i18n/ # Internationalization support
|
||||
└── webhook/ # Webhook integrations (aiohttp, SimpleRequestHandler, etc.)
|
||||
```
|
||||
|
||||
## .butcher/ (Code generation)
|
||||
```
|
||||
.butcher/
|
||||
├── schema/schema.json # Full Bot API schema (source of truth)
|
||||
├── types/ # Per-type entity.json + optional alias YAML overrides
|
||||
├── methods/ # Per-method entity.json + optional alias YAML overrides
|
||||
├── enums/ # Per-enum entity.json + optional YAML overrides
|
||||
└── templates/ # Jinja2 templates for generated Python files
|
||||
```
|
||||
|
||||
**Rule**: Edit `.yml` alias files or templates in `.butcher/`, never `.entity.json` files directly. Regenerate after changes.
|
||||
|
||||
## tests/ layout
|
||||
```
|
||||
tests/
|
||||
├── conftest.py # Shared fixtures (bot, dispatcher, etc.)
|
||||
├── mocked_bot.py # MockedBot for testing without real HTTP
|
||||
├── test_api/
|
||||
│ ├── test_types/ # Tests for Telegram types
|
||||
│ ├── test_methods/ # Tests for API method classes
|
||||
│ └── test_client/ # HTTP client tests
|
||||
├── test_dispatcher/ # Dispatcher/Router/Middleware tests
|
||||
├── test_filters/ # Filter tests
|
||||
├── test_fsm/ # FSM and storage tests
|
||||
├── test_handler/ # Handler tests
|
||||
├── test_utils/ # Utility tests
|
||||
└── test_webhook/ # Webhook integration tests
|
||||
```
|
||||
44
.serena/memories/codegen_workflow.md
Normal file
44
.serena/memories/codegen_workflow.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# Bot API Codegen Workflow
|
||||
|
||||
## How code generation works
|
||||
aiogram uses `butcher` (via `aiogram-cli`) to auto-generate Python files from the Telegram Bot API schema.
|
||||
|
||||
### Source of truth
|
||||
- `.butcher/schema/schema.json` — full parsed Bot API schema
|
||||
- `.butcher/types/<TypeName>/entity.json` — parsed entity metadata (DO NOT edit)
|
||||
- `.butcher/methods/<MethodName>/entity.json` — parsed method metadata (DO NOT edit)
|
||||
- `.butcher/enums/<EnumName>/entity.json` — parsed enum metadata (DO NOT edit)
|
||||
- `.butcher/templates/` — Jinja2 templates that produce Python code
|
||||
- YAML alias/override files in `.butcher/types/`, `.butcher/methods/` — edit these for customizations
|
||||
|
||||
### Generated files (DO NOT hand-edit)
|
||||
- `aiogram/types/*.py` (except `base.py`, `custom.py`, `_union.py` — framework internals)
|
||||
- `aiogram/methods/*.py` (except `base.py`)
|
||||
- `aiogram/enums/*.py`
|
||||
- `aiogram/client/bot.py` (the `Bot` class shortcuts)
|
||||
- `aiogram/types/__init__.py`, `aiogram/methods/__init__.py`
|
||||
|
||||
### Regeneration commands
|
||||
```bash
|
||||
uv run --extra cli butcher parse # re-parse from API schema
|
||||
uv run --extra cli butcher refresh # refresh entity JSON from parsed schema
|
||||
uv run --extra cli butcher apply all # apply templates → generate Python files
|
||||
```
|
||||
|
||||
### Adding a new type/method/shortcut
|
||||
1. Update the `.butcher` YAML alias/config file for the entity
|
||||
2. Run regeneration (parse → refresh → apply)
|
||||
3. Run lint + mypy + tests
|
||||
4. Commit both the `.butcher` config changes AND the generated Python files
|
||||
|
||||
### API version bumps (maintainers)
|
||||
```bash
|
||||
make update-api args=patch # or minor/major
|
||||
```
|
||||
This runs butcher parse/refresh/apply + version bump scripts that update:
|
||||
- `aiogram/__meta__.py`
|
||||
- `README.rst`
|
||||
- `docs/index.rst`
|
||||
|
||||
## Key constraint
|
||||
The maintainers enforce: **never add types/methods/shortcuts by hand-editing generated files**. All changes must go through `.butcher` config so future regenerations preserve them.
|
||||
43
.serena/memories/dispatcher/adding_new_event_types.md
Normal file
43
.serena/memories/dispatcher/adding_new_event_types.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# Adding a New Update/Event Type to aiogram Dispatcher
|
||||
|
||||
When Telegram Bot API adds a new update type (e.g. `managed_bot`, `purchased_paid_media`), the following files must be touched. Types, enums, and butcher configs are generated — the dispatcher integration is manual.
|
||||
|
||||
## Checklist (in order)
|
||||
|
||||
### Generated / butcher layer (run `butcher parse && butcher refresh && butcher apply all`)
|
||||
- `.butcher/types/<TypeName>/entity.json` — type definition
|
||||
- `.butcher/types/Update/entity.json` — add field to Update entity
|
||||
- `aiogram/types/<type_name>.py` — generated type class
|
||||
- `aiogram/types/__init__.py` — export
|
||||
- `aiogram/enums/update_type.py` — `NEW_TYPE = "new_type"` enum member
|
||||
- `aiogram/types/update.py` — `new_type: NewType | None = None` field + TYPE_CHECKING import + `__init__` signature
|
||||
|
||||
### Manual dispatcher integration (NOT generated)
|
||||
|
||||
1. **`aiogram/types/update.py`** — `event_type` property (lines ~161-215): add `if self.new_type: return "new_type"` before the `raise UpdateTypeLookupError` line
|
||||
|
||||
2. **`aiogram/dispatcher/router.py`** — two places in `Router.__init__`:
|
||||
- Add `self.new_type = TelegramEventObserver(router=self, event_name="new_type")` after the last observer attribute (before `self.errors`)
|
||||
- Add `"new_type": self.new_type,` to the `self.observers` dict (before `"error"`)
|
||||
|
||||
3. **`aiogram/dispatcher/middlewares/user_context.py`** — `resolve_event_context()` method: add `if event.new_type: return EventContext(user=..., chat=...)` before `return EventContext()`. Use `user` field for user-scoped events, `chat` for chat-scoped. No `business_connection_id` unless the event has one.
|
||||
|
||||
### Tests (manual)
|
||||
|
||||
4. **`tests/test_dispatcher/test_dispatcher.py`** — add `pytest.param("new_type", Update(update_id=42, new_type=NewType(...)), has_chat, has_user)` to `test_listen_update` parametrize list. Import `NewType` in the imports block.
|
||||
|
||||
5. **`tests/test_dispatcher/test_router.py`** — add `assert router.observers["new_type"] == router.new_type` to `test_observers_config`
|
||||
|
||||
### Docs (generated or manual stub)
|
||||
- `docs/api/types/<type_name>.rst` — RST stub
|
||||
- `docs/api/types/index.rst` — add to index
|
||||
|
||||
## Key invariants
|
||||
- The snake_case name must be identical across: `UpdateType` enum value, `Update` field name, `event_type` return string, Router attribute name, observers dict key, and `TelegramEventObserver(event_name=...)`.
|
||||
- `Update.event_type` uses `@lru_cache()` — never mutate Update fields after construction.
|
||||
- The routing machinery (`propagate_event`, middleware chains, sub-router propagation) requires **zero changes** — it operates on observer names looked up dynamically.
|
||||
|
||||
## Example: `managed_bot` (API 9.6)
|
||||
- Type: `ManagedBotUpdated` with fields `user: User` (creator) and `bot_user: User` (the managed bot)
|
||||
- user_context: `EventContext(user=event.managed_bot.user)` — user only, no chat
|
||||
- `has_chat=False, has_user=True` in test parametrization
|
||||
43
.serena/memories/project_overview.md
Normal file
43
.serena/memories/project_overview.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# Project Overview: aiogram
|
||||
|
||||
## Purpose
|
||||
**aiogram** is a modern, fully asynchronous Python framework for the Telegram Bot API (currently supports Bot API 9.5+). It provides a high-level interface for building Telegram bots using asyncio.
|
||||
|
||||
## Tech Stack
|
||||
- **Python**: 3.10–3.14 (also supports PyPy)
|
||||
- **Async runtime**: asyncio + aiohttp (HTTP client)
|
||||
- **Data validation**: Pydantic v2
|
||||
- **Package manager**: `uv`
|
||||
- **Linter/formatter**: `ruff` (check + format)
|
||||
- **Type checker**: `mypy`
|
||||
- **Testing**: `pytest` with `pytest-asyncio`, `aresponses`
|
||||
- **Docs**: Sphinx (reStructuredText), `sphinx-autobuild`
|
||||
- **Changelog**: `towncrier`
|
||||
- **Code generation**: `butcher` (aiogram-cli) — generates types, methods, enums from Bot API schema
|
||||
|
||||
## Key Links
|
||||
- Docs (English): https://docs.aiogram.dev/en/dev-3.x/
|
||||
- GitHub: https://github.com/aiogram/aiogram/
|
||||
- Bot API schema: `.butcher/schema/schema.json`
|
||||
|
||||
## Architecture Summary
|
||||
The framework is layered:
|
||||
1. **`aiogram/client/`** — `Bot` class (all API methods as shortcuts), session management, context controller
|
||||
2. **`aiogram/types/`** — Pydantic models for all Telegram types (`TelegramObject` base)
|
||||
3. **`aiogram/methods/`** — `TelegramMethod[ReturnType]` subclasses, one per Bot API method
|
||||
4. **`aiogram/dispatcher/`** — Dispatcher, Router (blueprints), middleware, event observers
|
||||
5. **`aiogram/filters/`** — Filter classes for routing
|
||||
6. **`aiogram/fsm/`** — Finite State Machine (states, storage backends)
|
||||
7. **`aiogram/enums/`** — Enumerations (ContentType, UpdateType, etc.)
|
||||
8. **`aiogram/utils/`** — Text decoration, keyboards, i18n, etc.
|
||||
9. **`aiogram/webhook/`** — Webhook server integrations (aiohttp, FastAPI, etc.)
|
||||
10. **`.butcher/`** — Code generation inputs: YAML/JSON configs for types/methods/enums + Jinja2 templates
|
||||
|
||||
## Optional extras
|
||||
- `fast` — uvloop + aiodns
|
||||
- `redis` — Redis FSM storage
|
||||
- `mongo` — MongoDB FSM storage
|
||||
- `proxy` — SOCKS proxy support
|
||||
- `i18n` — Babel-based i18n
|
||||
- `cli` — `butcher` codegen CLI
|
||||
- `signature` — cryptographic signature verification
|
||||
66
.serena/memories/suggested_commands.md
Normal file
66
.serena/memories/suggested_commands.md
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
# Suggested Commands
|
||||
|
||||
## Setup
|
||||
```bash
|
||||
uv sync --all-extras --group dev --group test
|
||||
uv run pre-commit install
|
||||
```
|
||||
|
||||
## Lint & Format (quick loop — use before every commit)
|
||||
```bash
|
||||
uv run ruff check --show-fixes --preview aiogram examples
|
||||
uv run ruff format --check --diff aiogram tests scripts examples
|
||||
uv run mypy aiogram
|
||||
```
|
||||
|
||||
## Auto-fix formatting
|
||||
```bash
|
||||
uv run ruff format aiogram tests scripts examples
|
||||
uv run ruff check --fix aiogram tests scripts examples
|
||||
```
|
||||
|
||||
## Run tests
|
||||
```bash
|
||||
uv run pytest tests # basic
|
||||
uv run pytest tests --redis redis://localhost:6379/0 # with Redis
|
||||
uv run pytest tests --mongo mongodb://mongo:mongo@localhost:27017 # with MongoDB
|
||||
```
|
||||
|
||||
## Build docs
|
||||
```bash
|
||||
# Live-reload dev server
|
||||
uv run --extra docs sphinx-autobuild --watch aiogram/ --watch CHANGES.rst --watch README.rst docs/ docs/_build/
|
||||
# One-shot build
|
||||
uv run --extra docs bash -c 'cd docs && make html'
|
||||
```
|
||||
|
||||
## Code generation (Bot API codegen)
|
||||
```bash
|
||||
# After editing .butcher/*.yml or templates:
|
||||
uv run --extra cli butcher parse
|
||||
uv run --extra cli butcher refresh
|
||||
uv run --extra cli butcher apply all
|
||||
```
|
||||
|
||||
## API version bump (maintainers only)
|
||||
```bash
|
||||
make update-api args=patch # runs butcher parse/refresh/apply + version bump
|
||||
```
|
||||
|
||||
## Changelog
|
||||
```bash
|
||||
# Preview draft
|
||||
uv run --extra docs towncrier build --draft
|
||||
# Build final
|
||||
uv run --extra docs towncrier build --yes
|
||||
```
|
||||
|
||||
## Clean build artifacts
|
||||
```bash
|
||||
make clean
|
||||
```
|
||||
|
||||
## Build package
|
||||
```bash
|
||||
uv build
|
||||
```
|
||||
43
.serena/memories/task_completion.md
Normal file
43
.serena/memories/task_completion.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# Task Completion Checklist
|
||||
|
||||
Run these before marking any task done or requesting review.
|
||||
|
||||
## Quick loop (every PR)
|
||||
```bash
|
||||
uv run ruff check --show-fixes --preview aiogram examples
|
||||
uv run ruff format --check --diff aiogram tests scripts examples
|
||||
uv run mypy aiogram
|
||||
uv run pytest tests
|
||||
```
|
||||
|
||||
## Codegen tasks (when touching .butcher/ or generated API files)
|
||||
```bash
|
||||
uv run --extra cli butcher parse
|
||||
uv run --extra cli butcher refresh
|
||||
uv run --extra cli butcher apply all
|
||||
# Then re-run quick loop
|
||||
```
|
||||
|
||||
## Integration tests (only if Redis/Mongo storage touched)
|
||||
```bash
|
||||
uv run pytest --redis redis://localhost:6379/0 tests
|
||||
uv run pytest --mongo mongodb://mongo:mongo@localhost:27017 tests
|
||||
```
|
||||
|
||||
## Docs (only if docs/ or public API changed)
|
||||
```bash
|
||||
uv run --extra docs bash -c 'cd docs && make html'
|
||||
```
|
||||
|
||||
## Changelog fragment (required unless PR has `skip news` label)
|
||||
- Create `CHANGES/<issue-or-pr-number>.<category>.rst`
|
||||
- Valid categories: `feature`, `bugfix`, `doc`, `removal`, `misc`
|
||||
- Content: user-visible behavior description (not internal/process details)
|
||||
- Do NOT edit `CHANGES.rst` directly
|
||||
|
||||
## PR quality checklist
|
||||
1. Tests added/updated for all behavior changes
|
||||
2. Quick loop passes (ruff + mypy + pytest)
|
||||
3. Changelog fragment added (or justified `skip news`)
|
||||
4. If codegen-related: both `.butcher` source config AND generated files updated
|
||||
5. PR body has clear reproduction/validation steps
|
||||
45
.serena/memories/testing_patterns.md
Normal file
45
.serena/memories/testing_patterns.md
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# Testing Patterns
|
||||
|
||||
## Framework
|
||||
- pytest with async support
|
||||
- No `pytest-asyncio` explicit marks needed (configured globally in pyproject.toml)
|
||||
- `MockedBot` (tests/mocked_bot.py) — use for all bot method tests, no real HTTP
|
||||
|
||||
## MockedBot pattern
|
||||
```python
|
||||
from tests.mocked_bot import MockedBot
|
||||
from aiogram.methods import SendMessage
|
||||
from aiogram.types import Message, Chat
|
||||
import datetime
|
||||
|
||||
class TestSendMessage:
|
||||
async def test_bot_method(self, bot: MockedBot):
|
||||
prepare_result = bot.add_result_for(
|
||||
SendMessage,
|
||||
ok=True,
|
||||
result=Message(
|
||||
message_id=42,
|
||||
date=datetime.datetime.now(),
|
||||
text="test",
|
||||
chat=Chat(id=42, type="private"),
|
||||
),
|
||||
)
|
||||
response: Message = await bot.send_message(chat_id=42, text="test")
|
||||
bot.get_request()
|
||||
assert response == prepare_result.result
|
||||
```
|
||||
|
||||
## Test structure
|
||||
- Class per type/method: `class TestSendMessage:`
|
||||
- One test per scenario: `async def test_<scenario>(self, ...)`
|
||||
- `bot` fixture comes from `tests/conftest.py`
|
||||
|
||||
## Integration tests
|
||||
- Redis: `uv run pytest --redis redis://localhost:6379/0 tests`
|
||||
- MongoDB: `uv run pytest --mongo mongodb://mongo:mongo@localhost:27017 tests`
|
||||
- Only run these when Redis/Mongo storage code is affected
|
||||
|
||||
## What NOT to do
|
||||
- Do not mock the database/storage in FSM tests — use real backends or memory storage
|
||||
- Do not introduce new test dependencies for small tests
|
||||
- Keep test style consistent with existing suite
|
||||
Loading…
Add table
Add a link
Reference in a new issue