Filtering events¶
Filters is needed for routing updates to the specific handler. Searching of handler is always stops on first match set of filters are pass. By default, all handlers has empty set of filters, so all updates will be passed to first handler that has empty set of filters.
aiogram has some builtin useful filters or you can write own filters.
Builtin filters¶
Here is list of builtin filters:
Writing own filters¶
Filters can be:
Asynchronous function (
async def my_filter(*args, **kwargs): pass)Synchronous function (
def my_filter(*args, **kwargs): pass)Anonymous function (
lambda event: True)Any awaitable object
Subclass of
aiogram.filters.base.FilterInstances of MagicFilter
and should return bool or dict. If the dictionary is passed as result of filter - resulted data will be propagated to the next filters and handler as keywords arguments.
A filter must either be declared with async def (or be an object with an
async def __call__, like aiogram.filters.base.Filter), or be synchronous and
return a bool or a dict. aiogram does not await the result of a synchronous callable: a filter
that returns a coroutine or any other awaitable, such as lambda event: check(event) where
check is async, raises TypeError. Write it as async def instead.
Note
The same applies to wrappers. functools.partial(async_fn) works, but a
functools.partial over an object with an async __call__ (for example a
Filter instance) and an async def wrapper around a synchronous function
built with functools.wraps (for example aiofiles.os.wrap) are called as
synchronous functions, so they also raise TypeError. Wrap such filters in a plain
async def function.
Base class for own filters¶
- class aiogram.filters.base.Filter[source]¶
If you want to register own filters like builtin filters you will need to write subclass of this class with overriding the
__call__method and adding filter attributes.
Own filter example¶
For example if you need to make simple text filter:
from aiogram import Router
from aiogram.filters import Filter
from aiogram.types import Message
router = Router()
class MyFilter(Filter):
def __init__(self, my_text: str) -> None:
self.my_text = my_text
async def __call__(self, message: Message) -> bool:
return message.text == self.my_text
@router.message(MyFilter("hello"))
async def my_handler(message: Message) -> None: ...
Combining Filters¶
In general, all filters can be combined in two ways
Recommended way¶
If you specify multiple filters in a row, it will be checked with an “and” condition:
@<router>.message(F.text.startswith("show"), F.text.endswith("example"))
Also, if you want to use two alternative ways to run the same handler (“or” condition) you can register the handler twice or more times as you like
@<router>.message(F.text == "hi")
@<router>.message(CommandStart())
Also sometimes you will need to invert the filter result, for example you have an IsAdmin filter and you want to check if the user is not an admin
@<router>.message(~IsAdmin())
Another possible way¶
An alternative way is to combine using special functions (and_f(), or_f(), invert_f() from aiogram.filters module):
and_f(F.text.startswith("show"), F.text.endswith("example"))
or_f(F.text(text="hi"), CommandStart())
invert_f(IsAdmin())
and_f(<A>, or_f(<B>, <C>))