0
# Bot and Dispatcher
1
2
Core classes for bot instantiation, API communication, update processing, and event routing. These form the foundation of any aiogram bot application.
3
4
## Capabilities
5
6
### Bot Class
7
8
The Bot class serves as the primary interface to the Telegram Bot API, handling HTTP communication, automatic retries, session management, and method execution.
9
10
```python { .api }
11
class Bot:
12
def __init__(
13
self,
14
token: str,
15
parse_mode: str | None = None,
16
disable_web_page_preview: bool | None = None,
17
protect_content: bool | None = None,
18
session: BaseSession | None = None,
19
**kwargs
20
):
21
"""
22
Initialize a Bot instance.
23
24
Parameters:
25
- token: Bot token from @BotFather
26
- parse_mode: Default parse mode (HTML, Markdown, MarkdownV2)
27
- disable_web_page_preview: Disable link previews by default
28
- protect_content: Protect content from forwarding/saving by default
29
- session: Custom HTTP session (defaults to AiohttpSession)
30
"""
31
32
async def get_me(self) -> User:
33
"""Get basic info about the bot"""
34
35
async def close(self) -> bool:
36
"""Close the bot instance and clean up resources"""
37
38
async def get_updates(
39
self,
40
offset: int | None = None,
41
limit: int | None = None,
42
timeout: int | None = None,
43
allowed_updates: list[str] | None = None
44
) -> list[Update]:
45
"""Get updates using long polling"""
46
47
@property
48
def id(self) -> int | None:
49
"""Bot's unique identifier (available after first API call)"""
50
51
@property
52
def username(self) -> str | None:
53
"""Bot's username (available after first API call)"""
54
55
@property
56
def first_name(self) -> str | None:
57
"""Bot's first name (available after first API call)"""
58
```
59
60
### Dispatcher Class
61
62
The Dispatcher is the root router that manages the entire update processing pipeline, including middleware execution, handler resolution, and FSM state management.
63
64
```python { .api }
65
class Dispatcher(Router):
66
def __init__(
67
self,
68
*,
69
storage: BaseStorage | None = None,
70
fsm_strategy: FSMStrategy = FSMStrategy.CHAT,
71
events_isolation: BaseEventIsolation | None = None,
72
disable_fsm: bool = False,
73
**kwargs
74
):
75
"""
76
Initialize the Dispatcher.
77
78
Parameters:
79
- storage: FSM storage backend (defaults to MemoryStorage)
80
- fsm_strategy: FSM isolation strategy (CHAT, USER_IN_CHAT, GLOBAL_USER)
81
- events_isolation: Event isolation mechanism
82
- disable_fsm: Disable FSM functionality entirely
83
"""
84
85
async def start_polling(
86
self,
87
bot: Bot,
88
*,
89
polling_timeout: int = 10,
90
handle_as_tasks: bool = True,
91
backoff_config: BackoffConfig = BackoffConfig(),
92
**kwargs
93
) -> None:
94
"""
95
Start polling for updates from Telegram.
96
97
Parameters:
98
- bot: Bot instance to use for polling
99
- polling_timeout: Timeout for long polling requests
100
- handle_as_tasks: Handle updates as asyncio tasks
101
- backoff_config: Backoff configuration for retries
102
"""
103
104
async def feed_update(self, bot: Bot, update: Update, **kwargs) -> Any:
105
"""Process a single update through the middleware and handler pipeline"""
106
107
def include_router(self, router: Router) -> None:
108
"""Include a child router in the dispatcher"""
109
110
def include_routers(self, *routers: Router) -> None:
111
"""Include multiple child routers"""
112
113
@property
114
def storage(self) -> BaseStorage:
115
"""Get the configured FSM storage backend"""
116
```
117
118
### Router Class
119
120
Routers organize handlers and middleware into logical groups, supporting nested routing structures for modular bot development.
121
122
```python { .api }
123
class Router:
124
def __init__(self, *, name: str | None = None):
125
"""
126
Initialize a Router.
127
128
Parameters:
129
- name: Optional name for the router (useful for debugging)
130
"""
131
132
def include_router(self, router: Router) -> None:
133
"""Include a child router"""
134
135
def include_routers(self, *routers: Router) -> None:
136
"""Include multiple child routers"""
137
138
# Event observers for handler registration
139
@property
140
def message(self) -> HandlerObject[Message]:
141
"""Message update observer"""
142
143
@property
144
def edited_message(self) -> HandlerObject[Message]:
145
"""Edited message update observer"""
146
147
@property
148
def channel_post(self) -> HandlerObject[Message]:
149
"""Channel post update observer"""
150
151
@property
152
def edited_channel_post(self) -> HandlerObject[Message]:
153
"""Edited channel post update observer"""
154
155
@property
156
def inline_query(self) -> HandlerObject[InlineQuery]:
157
"""Inline query update observer"""
158
159
@property
160
def chosen_inline_result(self) -> HandlerObject[ChosenInlineResult]:
161
"""Chosen inline result update observer"""
162
163
@property
164
def callback_query(self) -> HandlerObject[CallbackQuery]:
165
"""Callback query update observer"""
166
167
@property
168
def shipping_query(self) -> HandlerObject[ShippingQuery]:
169
"""Shipping query update observer"""
170
171
@property
172
def pre_checkout_query(self) -> HandlerObject[PreCheckoutQuery]:
173
"""Pre-checkout query update observer"""
174
175
@property
176
def poll(self) -> HandlerObject[Poll]:
177
"""Poll update observer"""
178
179
@property
180
def poll_answer(self) -> HandlerObject[PollAnswer]:
181
"""Poll answer update observer"""
182
183
@property
184
def my_chat_member(self) -> HandlerObject[ChatMemberUpdated]:
185
"""My chat member update observer"""
186
187
@property
188
def chat_member(self) -> HandlerObject[ChatMemberUpdated]:
189
"""Chat member update observer"""
190
191
@property
192
def chat_join_request(self) -> HandlerObject[ChatJoinRequest]:
193
"""Chat join request update observer"""
194
195
@property
196
def message_reaction(self) -> HandlerObject[MessageReactionUpdated]:
197
"""Message reaction update observer"""
198
199
@property
200
def message_reaction_count(self) -> HandlerObject[MessageReactionCountUpdated]:
201
"""Message reaction count update observer"""
202
203
@property
204
def chat_boost(self) -> HandlerObject[ChatBoostUpdated]:
205
"""Chat boost update observer"""
206
207
@property
208
def removed_chat_boost(self) -> HandlerObject[ChatBoostRemoved]:
209
"""Removed chat boost update observer"""
210
211
@property
212
def deleted_business_messages(self) -> HandlerObject[BusinessMessagesDeleted]:
213
"""Deleted business messages update observer"""
214
215
@property
216
def business_connection(self) -> HandlerObject[BusinessConnection]:
217
"""Business connection update observer"""
218
219
@property
220
def edited_business_message(self) -> HandlerObject[Message]:
221
"""Edited business message update observer"""
222
223
@property
224
def business_message(self) -> HandlerObject[Message]:
225
"""Business message update observer"""
226
227
@property
228
def purchased_paid_media(self) -> HandlerObject[PaidMediaPurchased]:
229
"""Purchased paid media update observer"""
230
231
@property
232
def error(self) -> HandlerObject[ErrorEvent]:
233
"""Error event observer"""
234
235
@property
236
def startup(self) -> HandlerObject[StartupEvent]:
237
"""Startup event observer"""
238
239
@property
240
def shutdown(self) -> HandlerObject[ShutdownEvent]:
241
"""Shutdown event observer"""
242
```
243
244
### Middleware Support
245
246
Base middleware class for creating custom middleware components that process updates and API calls.
247
248
```python { .api }
249
class BaseMiddleware:
250
"""Base class for creating middleware"""
251
252
async def __call__(
253
self,
254
handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
255
event: TelegramObject,
256
data: dict[str, Any]
257
) -> Any:
258
"""
259
Middleware execution method.
260
261
Parameters:
262
- handler: Next handler in the chain
263
- event: Telegram event object
264
- data: Handler context data
265
266
Returns:
267
Result from handler execution
268
"""
269
```
270
271
## Usage Examples
272
273
### Basic Bot Setup
274
275
```python
276
import asyncio
277
from aiogram import Bot, Dispatcher, Router
278
from aiogram.types import Message
279
from aiogram.filters import Command
280
281
# Create bot and dispatcher
282
bot = Bot(token="YOUR_BOT_TOKEN")
283
dp = Dispatcher()
284
285
# Create router for organizing handlers
286
main_router = Router()
287
288
@main_router.message(Command("start"))
289
async def start_command(message: Message):
290
await message.answer("Welcome to the bot!")
291
292
# Include router in dispatcher
293
dp.include_router(main_router)
294
295
# Start the bot
296
async def main():
297
await dp.start_polling(bot)
298
299
if __name__ == "__main__":
300
asyncio.run(main())
301
```
302
303
### Advanced Setup with Custom Session
304
305
```python
306
from aiogram import Bot, Dispatcher
307
from aiogram.client.session.aiohttp import AiohttpSession
308
from aiogram.client.telegram import TelegramAPIServer
309
import aiohttp
310
311
# Create custom session with proxy
312
session = AiohttpSession(
313
connector=aiohttp.TCPConnector(limit=100),
314
timeout=aiohttp.ClientTimeout(total=30)
315
)
316
317
# Create bot with custom API server
318
bot = Bot(
319
token="YOUR_BOT_TOKEN",
320
session=session,
321
server=TelegramAPIServer.from_base("https://api.telegram.org")
322
)
323
324
dp = Dispatcher()
325
```
326
327
### Nested Router Structure
328
329
```python
330
from aiogram import Dispatcher, Router
331
332
# Main dispatcher
333
dp = Dispatcher()
334
335
# Feature-specific routers
336
admin_router = Router(name="admin")
337
user_router = Router(name="user")
338
callback_router = Router(name="callbacks")
339
340
# Include routers with hierarchy
341
dp.include_routers(admin_router, user_router, callback_router)
342
343
# Routers can also include other routers
344
feature_router = Router(name="feature")
345
feature_router.include_router(callback_router)
346
user_router.include_router(feature_router)
347
```
348
349
### Custom Middleware
350
351
```python
352
from aiogram import BaseMiddleware
353
from aiogram.types import TelegramObject
354
from typing import Callable, Dict, Any, Awaitable
355
356
class LoggingMiddleware(BaseMiddleware):
357
async def __call__(
358
self,
359
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
360
event: TelegramObject,
361
data: Dict[str, Any]
362
) -> Any:
363
print(f"Processing {type(event).__name__}")
364
result = await handler(event, data)
365
print(f"Finished processing {type(event).__name__}")
366
return result
367
368
# Register middleware
369
dp.message.middleware(LoggingMiddleware())
370
```
371
372
## Types
373
374
### HandlerObject
375
376
```python { .api }
377
class HandlerObject[T: TelegramObject]:
378
"""Handler registration interface for specific event types"""
379
380
def __call__(self, *filters: Filter) -> Callable:
381
"""Decorator for registering handlers with filters"""
382
383
def register(
384
self,
385
callback: Callable,
386
*filters: Filter,
387
flags: dict[str, Any] | None = None
388
) -> None:
389
"""Register a handler programmatically"""
390
391
def filter(self, custom_filter: Filter) -> HandlerObject[T]:
392
"""Add a filter to the handler object"""
393
394
def middleware(self, middleware: BaseMiddleware) -> None:
395
"""Register middleware for this handler type"""
396
```
397
398
### Event Types
399
400
```python { .api }
401
class ErrorEvent:
402
"""Error event for exception handling"""
403
exception: Exception
404
update: Update
405
406
class StartupEvent:
407
"""Startup event fired when dispatcher starts"""
408
pass
409
410
class ShutdownEvent:
411
"""Shutdown event fired when dispatcher stops"""
412
pass
413
```