Add docs for class-based handlers

This commit is contained in:
Alex Root Junior 2019-12-03 00:37:53 +02:00
parent b82a1a6fb0
commit 62bce34b49
6 changed files with 61 additions and 4 deletions

View file

@ -0,0 +1,25 @@
# Overview
A handler is a async callable which takes a event with contextual data and returns a response.
In `aiogram` this can be more than just an async function, these allow you to use classes which can be used as Telegram event handlers to structure your event handlers and reuse code by harnessing inheritance and mixins.
There are some base class based handlers what you need to use in your own handlers:
- [BaseHandler](#basehandler)
- [MessageHandler](message.md)
## BaseHandler
Base handler is abstract class and should be used in all other class-based handlers.
Import: `#!python3 from aiogram.hanler import BaseHandler`
By default you will need to override only method `#!python3 async def handle(self) -> Any: ...`
The list of filters can be specified in attribute `#!python3 filters: Union[List["FilterType"], Tuple["FilterType"]]` or you can combine that attribute with filters specified in event registerer (via decorator or observer method)
This class is also have an default initializer and you don't need to change it.
Initializer accepts current event and all contextual data and which can be accessed from the handler through attributes: `event: TelegramEvent` and `data: Dict[Any, str]`
If instance of the bot is specified in context data or current context it can be accessed through `bot` class attribute.

View file

@ -0,0 +1,25 @@
# MessageHandler
There is base class for message handlers.
## Simple usage:
```pyhton3
from aiogram.handlers import MessageHandler
...
@router.message_handler()
class MyTestMessageHandler(MessageHandler):
filters = [Text(text="test")]
async def handle() -> Any:
return SendMessage(chat_id=self.chat.id, text="PASS")
```
## Extension
This base handler is subclass of [BaseHandler](basics.md#basehandler) with some extensions:
- `self.chat` is alias for `self.event.chat`
- `self.from_user` is alias for `self.event.from_user`