0
# aiogram
1
2
A modern and fully asynchronous framework for Telegram Bot API. aiogram provides a comprehensive Python toolkit for building Telegram bots with async/await support, type safety, powerful filtering system, finite state machines, middleware support, and complete coverage of the Telegram Bot API v9.2.
3
4
## Package Information
5
6
- **Package Name**: aiogram
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install aiogram`
10
- **API Version**: 9.2 (Telegram Bot API)
11
12
## Core Imports
13
14
```python
15
import aiogram
16
```
17
18
Common imports for bot development:
19
20
```python
21
from aiogram import Bot, Dispatcher, Router, F, html, md, flags
22
from aiogram.types import Message, CallbackQuery, Update
23
from aiogram.filters import Command, StateFilter
24
from aiogram.fsm.context import FSMContext
25
from aiogram.fsm.state import State, StatesGroup
26
```
27
28
## Basic Usage
29
30
```python
31
import asyncio
32
from aiogram import Bot, Dispatcher, Router, F
33
from aiogram.types import Message
34
from aiogram.filters import Command
35
36
# Initialize bot and dispatcher
37
bot = Bot(token="YOUR_BOT_TOKEN")
38
dp = Dispatcher()
39
router = Router()
40
41
# Register handlers using decorators
42
@router.message(Command("start"))
43
async def cmd_start(message: Message):
44
await message.answer("Hello! This is a bot built with aiogram.")
45
46
@router.message(F.text == "hello")
47
async def hello_handler(message: Message):
48
await message.answer("Hello there!")
49
50
# Include router in dispatcher
51
dp.include_router(router)
52
53
# Start polling
54
async def main():
55
await dp.start_polling(bot)
56
57
if __name__ == "__main__":
58
asyncio.run(main())
59
```
60
61
## Architecture
62
63
aiogram follows a modular, event-driven architecture built on asyncio:
64
65
- **Bot**: HTTP client for Telegram Bot API with automatic retries and session management
66
- **Dispatcher**: Root router managing update distribution, middleware stack, and FSM
67
- **Routers**: Nested event handlers for organizing bot logic into modules
68
- **Filters**: Composable conditions for matching updates (magic filters, commands, states)
69
- **Middleware**: Request/response processing pipeline for authentication, logging, rate limiting
70
- **FSM**: Finite state machine for complex conversational flows
71
- **Types**: Complete type system covering all Telegram objects with full type hints
72
73
This design enables scalable bot development with clean separation of concerns, type safety, and powerful abstraction layers.
74
75
## Capabilities
76
77
### Bot and Dispatcher
78
79
Core classes for bot instantiation, update processing, and event routing. The Bot class handles API communication while Dispatcher manages update distribution and middleware execution.
80
81
```python { .api }
82
class Bot:
83
def __init__(self, token: str, **kwargs): ...
84
async def get_me(self) -> User: ...
85
async def send_message(self, chat_id: int | str, text: str, **kwargs) -> Message: ...
86
87
class Dispatcher(Router):
88
def __init__(self, **kwargs): ...
89
async def start_polling(self, bot: Bot, **kwargs): ...
90
def include_router(self, router: Router): ...
91
```
92
93
[Bot and Dispatcher](./bot-and-dispatcher.md)
94
95
### Types and Objects
96
97
Complete type system covering all Telegram objects including messages, users, chats, keyboards, media, payments, and inline queries. Over 319 classes with full type safety.
98
99
```python { .api }
100
class Message(TelegramObject):
101
message_id: int
102
from_user: User | None
103
sender_chat: Chat | None
104
date: datetime.datetime
105
chat: Chat
106
text: str | None
107
entities: list[MessageEntity] | None
108
109
class User(TelegramObject):
110
id: int
111
is_bot: bool
112
first_name: str
113
last_name: str | None
114
username: str | None
115
```
116
117
[Types and Objects](./types-and-objects.md)
118
119
### API Methods
120
121
Complete coverage of all 162+ Telegram Bot API methods for sending messages, managing chats, handling payments, games, stickers, and webhooks. Type-safe method calls with automatic serialization.
122
123
```python { .api }
124
async def send_message(
125
chat_id: int | str,
126
text: str,
127
parse_mode: str | None = None,
128
reply_markup: InlineKeyboardMarkup | ReplyKeyboardMarkup | None = None
129
) -> Message: ...
130
131
async def edit_message_text(
132
text: str,
133
chat_id: int | str | None = None,
134
message_id: int | None = None,
135
parse_mode: str | None = None
136
) -> Message | bool: ...
137
```
138
139
[API Methods](./api-methods.md)
140
141
### Filters and Handlers
142
143
Powerful filtering system with magic filters, command matching, state filtering, and custom filters. Handler registration with decorators and functional approaches.
144
145
```python { .api }
146
class Filter:
147
async def __call__(self, obj: TelegramObject) -> bool | dict[str, Any]: ...
148
149
class Command(Filter):
150
def __init__(self, *commands: str): ...
151
152
F: MagicFilter # Magic filter instance for complex conditions
153
154
@router.message(Command("start"))
155
async def start_handler(message: Message): ...
156
157
@router.message(F.text.contains("hello"))
158
async def text_filter_handler(message: Message): ...
159
```
160
161
[Filters and Handlers](./filters-and-handlers.md)
162
163
### Finite State Machine
164
165
Built-in FSM support for complex conversational flows with multiple storage backends, state groups, and context management.
166
167
```python { .api }
168
class State:
169
def __init__(self, state: str, group_name: str | None = None): ...
170
171
class StatesGroup:
172
pass
173
174
class FSMContext:
175
async def set_state(self, state: State | str | None) -> None: ...
176
async def get_state(self) -> str | None: ...
177
async def set_data(self, data: dict[str, Any]) -> None: ...
178
async def get_data(self) -> dict[str, Any]: ...
179
```
180
181
[Finite State Machine](./state-management.md)
182
183
### Utilities and Enums
184
185
Comprehensive utility functions for deep linking, keyboard building, text formatting, and validation. Complete enumeration system for API constants.
186
187
```python { .api }
188
def create_start_link(bot_username: str, payload: str | None = None) -> str: ...
189
190
class InlineKeyboardBuilder:
191
def button(self, text: str, **kwargs) -> InlineKeyboardBuilder: ...
192
def adjust(self, *sizes: int) -> InlineKeyboardBuilder: ...
193
def as_markup(self) -> InlineKeyboardMarkup: ...
194
195
# Enums
196
class ChatType(str, Enum):
197
PRIVATE = "private"
198
GROUP = "group"
199
SUPERGROUP = "supergroup"
200
CHANNEL = "channel"
201
```
202
203
[Utilities and Enums](./utilities-and-enums.md)
204
205
## Types
206
207
### Core Type Hierarchy
208
209
```python { .api }
210
class TelegramObject:
211
"""Base class for all Telegram objects"""
212
pass
213
214
class Update(TelegramObject):
215
"""Represents an incoming update"""
216
update_id: int
217
message: Message | None
218
edited_message: Message | None
219
channel_post: Message | None
220
edited_channel_post: Message | None
221
business_connection: BusinessConnection | None
222
business_message: Message | None
223
edited_business_message: Message | None
224
deleted_business_messages: BusinessMessagesDeleted | None
225
message_reaction: MessageReactionUpdated | None
226
message_reaction_count: MessageReactionCountUpdated | None
227
inline_query: InlineQuery | None
228
chosen_inline_result: ChosenInlineResult | None
229
callback_query: CallbackQuery | None
230
shipping_query: ShippingQuery | None
231
pre_checkout_query: PreCheckoutQuery | None
232
purchased_paid_media: PaidMediaPurchased | None
233
poll: Poll | None
234
poll_answer: PollAnswer | None
235
my_chat_member: ChatMemberUpdated | None
236
chat_member: ChatMemberUpdated | None
237
chat_join_request: ChatJoinRequest | None
238
chat_boost: ChatBoostUpdated | None
239
removed_chat_boost: ChatBoostRemoved | None
240
241
class Bot:
242
"""Main bot class for API interactions"""
243
def __init__(
244
self,
245
token: str,
246
parse_mode: str | None = None,
247
disable_web_page_preview: bool | None = None,
248
protect_content: bool | None = None,
249
session: BaseSession | None = None,
250
**kwargs
251
): ...
252
```