Use Middlewares for event processing
mainMiddlewares allow you to execute logic before and after event handlers are called. They are executed for every event received.
Important: Middlewares are called in the order they are added. Avoid long-running tasks in middlewares as they can significantly impact performance.
Middleware signature:
async def my_middleware(client: Client, event: BaseObject, /, *, call_next: HandlerCallable):
You must call await call_next(client, event) to proceed to the next middleware or event handler.
from aiotdlib import Client, ClientSettings, HandlerCallable
from aiotdlib.api import BaseObject
async def my_middleware(client: Client, event: BaseObject, /, *, call_next: HandlerCallable):
# Pre-event logic
print(f"Before event {event.ID}")
try:
await call_next(client, event)
finally:
# Post-event logic
print(f"After event {event.ID}")
async def main():
client = Client(settings=ClientSettings(api_id=123, api_hash="", phone_number=""))
client.add_middleware(my_middleware)
async with client:
await client.idle()