Skip to content

Filters

Maksym Zavalniuk edited this page Sep 7, 2023 · 1 revision

AIogram official documentation.

How to create filters?

  1. In the filters folder create the file and add your code:
from typing import Union

from aiogram.filters import BaseFilter
from aiogram.types import Message


class ChatTypeFilter(BaseFilter):
    def __init__(self, chat_type: Union[str, list]):
        self.chat_type = chat_type

    async def __call__(self, message: Message) -> bool:
        if isinstance(self.chat_type, str):
            return message.chat.type == self.chat_type
        else:
            return message.chat.type in self.chat_type
  1. Add filter to the router:
router.message.filter(IsAdminFilter(353057906))
  1. Add filter to the handlers:
@router.message(
    ChatTypeFilter(chat_type=["group", "supergroup"]),
    Command(commands=["dice"]),
)

How to get the data from the filter?

filters/find_usernames.py

from typing import Union, Dict, Any

from aiogram.filters import BaseFilter
from aiogram.types import Message


class HasUsernamesFilter(BaseFilter):
    async def __call__(self, message: Message) -> Union[bool, Dict[str, Any]]:
        entities = message.entities or []

        found_usernames = [
            item.extract_from(message.text) for item in entities
            if item.type == "mention"
        ]

        if len(found_usernames) > 0:
            return {"usernames": found_usernames}
        return False

handlers/usernames.py

from typing import List

from aiogram import Router, F
from aiogram.types import Message

from filters.find_usernames import HasUsernamesFilter

router = Router()


@router.message(
    F.text,
    HasUsernamesFilter()
)
async def message_with_usernames(
        message: Message,
        usernames: List[str]
):
    await message.reply(
        f'Thanks! Here are usernames '
        f'{", ".join(usernames)}'
    )

Magic filters

from aiogram import F

# Здесь F - это message
@router.message(F.photo)
async def photo_msg(message: Message):
    await message.answer("This is image!")

Some examples:

router.message.filter(F.chat.type.in_({"group", "supergroup"}))

F.content_type.in_({'text', 'sticker', 'photo'}) or F.photo | F.text | F.sticker

from aiogram.types import Message, PhotoSize

@router.message(F.photo[-1].as_("largest_photo"))
async def forward_from_channel_handler(message: Message, largest_photo: PhotoSize) -> None:
    print(largest_photo.width, largest_photo.height)

from aiogram import F
from aiogram.types import Message, Chat

@router.message(F.forward_from_chat[F.type == "channel"].as_("channel"))
async def forwarded_from_channel(message: Message, channel: Chat):
    await message.answer(f"This channel's ID is {channel.id}")
Clone this wiki locally