2.9 KiB
Overview
aiogram provides powerful mechanism for customizing event handlers via middlewares.
Middlewares in bot framework seems like Middlewares mechanism in web-frameworks (like aiohttp, fastapi, Django or etc.) with small difference - here is implemented many layers of processing (named as pipeline).
!!! info Middleware is function that triggered on every event received from Telegram Bot API in many points on processing pipeline.
Base theory
As many books and other literature in internet says:
Middleware is reusable software that leverages patterns and frameworks to bridge the gap between the functional requirements of applications and the underlying operating systems, network protocol stacks, and databases.
Middleware can modify, extend or reject processing event before-, on- or after- processing of that event.
(Click on image to zoom it)
Event pipeline
As described below middleware an interact with event in many stages of pipeline.
Simple workflow:
- Dispatcher receive an Update
- Call pre-process update middleware in all routers tree
- Filter Update over handlers
- Call process update middleware in all routers tree
- Router detects event type (Message, Callback query, etc.)
- Router triggers pre-process middleware of specific type
- Pass event over filters to detect specific handler
- Call process middleware for specific type (only when handler for this event exists)
- Do magick. Call handler (Read more Event observers)
- Call post-process middleware
- Call post-process update middleware in all routers tree
- Emit response into webhook (when it needed)
!!! warning
When filters does not match any handler with this event the #!python3 process
step will not be called.
!!! warning When exception will be caused in handlers pipeline will be stopped immediately and then start processing error via errors handler and it own middleware callbacks.
!!! warning Middlewares for updates will be called for all routers in tree but callbacks for events will be called only for specific branch of routers.
Pipeline in pictures:
Simple pipeline
(Click on image to zoom it)
Nested routers pipeline
(Click on image to zoom it)


