Filters

Basics

Filter factory greatly simplifies the reuse of filters when registering handlers.

Filters factory

class aiogram.dispatcher.filters.FiltersFactory(dispatcher)[source]

Bases: object

Filters factory

bind(callback: Union[Callable, AbstractFilter], validator: Optional[Callable] = None, event_handlers: Optional[List[Handler]] = None, exclude_event_handlers: Optional[Iterable[Handler]] = None)[source]

Register filter

Parameters
  • callback – callable or subclass of AbstractFilter

  • validator – custom validator.

  • event_handlers – list of instances of Handler

  • exclude_event_handlers – list of excluded event handlers (Handler)

unbind(callback: Union[Callable, AbstractFilter])[source]

Unregister filter

Parameters

callback – callable of subclass of AbstractFilter

resolve(event_handler, *custom_filters, **full_config) List[Union[Callable, AbstractFilter]][source]

Resolve filters to filters-set

Parameters
  • event_handler

  • custom_filters

  • full_config

Returns

Builtin filters

aiogram has some builtin filters. Here you can see all of them:

Command

class aiogram.dispatcher.filters.Command(commands: Union[Iterable[Union[str, BotCommand]], str, BotCommand], prefixes: Union[Iterable, str] = '/', ignore_case: bool = True, ignore_mention: bool = False, ignore_caption: bool = True)[source]

Bases: Filter

You can handle commands by using this filter.

If filter is successful processed the Command.CommandObj will be passed to the handler arguments.

By default this filter is registered for messages and edited messages handlers.

Filter can be initialized from filters factory or by simply creating instance of this class.

Examples:

@dp.message_handler(commands=['myCommand'])
@dp.message_handler(Command(['myCommand']))
@dp.message_handler(commands=['myCommand'], commands_prefix='!/')
Parameters
  • commands – Command or list of commands always without leading slashes (prefix)

  • prefixes – Allowed commands prefix. By default is slash. If you change the default behavior pass the list of prefixes to this argument.

  • ignore_case – Ignore case of the command

  • ignore_mention – Ignore mention in command (By default this filter pass only the commands addressed to current bot)

  • ignore_caption

    Ignore caption from message (in message types like photo, video, audio, etc) By default is True. If you want check commands in captions, you also should set required content_types.

    Examples:

    @dp.message_handler(commands=['myCommand'], commands_ignore_caption=False, content_types=ContentType.ANY)
    @dp.message_handler(Command(['myCommand'], ignore_caption=False), content_types=[ContentType.TEXT, ContentType.DOCUMENT])
    

classmethod validate(full_config: Dict[str, Any]) Optional[Dict[str, Any]][source]

Validator for filters factory

From filters factory this filter can be registered with arguments:

  • command

  • commands_prefix (will be passed as prefixes)

  • commands_ignore_mention (will be passed as ignore_mention)

  • commands_ignore_caption (will be passed as ignore_caption)

Parameters

full_config

Returns

config or empty dict

async check(message: Message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

class CommandObj(prefix: str = '/', command: str = '', mention: Optional[str] = None, args: Optional[str] = None)[source]

Bases: object

Instance of this object is always has command and it prefix.

Can be passed as keyword argument command to the handler

prefix: str = '/'

Command without prefix and mention

command: str = ''

Mention (if available)

mention: str = None

Command argument

property mentioned: bool

This command has mention?

Returns

property text: str

Generate original text from object

Returns

CommandStart

class aiogram.dispatcher.filters.CommandStart(deep_link: Optional[Union[str, Pattern[str]]] = None, encoded: bool = False)[source]

Bases: Command

This filter based on Command filter but can handle only /start command.

Also this filter can handle deep-linking arguments.

Example:

@dp.message_handler(CommandStart(re.compile(r'ref-([\d]+)')))
Parameters
  • deep_link – string or compiled regular expression (by re.compile(...)).

  • encoded – set True if you’re waiting for encoded payload (default - False).

async check(message: Message)[source]

If deep-linking is passed to the filter result of the matching will be passed as deep_link to the handler

Parameters

message

Returns

CommandHelp

class aiogram.dispatcher.filters.CommandHelp[source]

Bases: Command

This filter based on Command filter but can handle only /help command.

Filter can be initialized from filters factory or by simply creating instance of this class.

Examples:

@dp.message_handler(commands=['myCommand'])
@dp.message_handler(Command(['myCommand']))
@dp.message_handler(commands=['myCommand'], commands_prefix='!/')
Parameters
  • commands – Command or list of commands always without leading slashes (prefix)

  • prefixes – Allowed commands prefix. By default is slash. If you change the default behavior pass the list of prefixes to this argument.

  • ignore_case – Ignore case of the command

  • ignore_mention – Ignore mention in command (By default this filter pass only the commands addressed to current bot)

  • ignore_caption

    Ignore caption from message (in message types like photo, video, audio, etc) By default is True. If you want check commands in captions, you also should set required content_types.

    Examples:

    @dp.message_handler(commands=['myCommand'], commands_ignore_caption=False, content_types=ContentType.ANY)
    @dp.message_handler(Command(['myCommand'], ignore_caption=False), content_types=[ContentType.TEXT, ContentType.DOCUMENT])
    

CommandSettings

class aiogram.dispatcher.filters.CommandSettings[source]

Bases: Command

This filter based on Command filter but can handle only /settings command.

Filter can be initialized from filters factory or by simply creating instance of this class.

Examples:

@dp.message_handler(commands=['myCommand'])
@dp.message_handler(Command(['myCommand']))
@dp.message_handler(commands=['myCommand'], commands_prefix='!/')
Parameters
  • commands – Command or list of commands always without leading slashes (prefix)

  • prefixes – Allowed commands prefix. By default is slash. If you change the default behavior pass the list of prefixes to this argument.

  • ignore_case – Ignore case of the command

  • ignore_mention – Ignore mention in command (By default this filter pass only the commands addressed to current bot)

  • ignore_caption

    Ignore caption from message (in message types like photo, video, audio, etc) By default is True. If you want check commands in captions, you also should set required content_types.

    Examples:

    @dp.message_handler(commands=['myCommand'], commands_ignore_caption=False, content_types=ContentType.ANY)
    @dp.message_handler(Command(['myCommand'], ignore_caption=False), content_types=[ContentType.TEXT, ContentType.DOCUMENT])
    

CommandPrivacy

class aiogram.dispatcher.filters.CommandPrivacy[source]

Bases: Command

This filter based on Command filter but can handle only /privacy command.

Filter can be initialized from filters factory or by simply creating instance of this class.

Examples:

@dp.message_handler(commands=['myCommand'])
@dp.message_handler(Command(['myCommand']))
@dp.message_handler(commands=['myCommand'], commands_prefix='!/')
Parameters
  • commands – Command or list of commands always without leading slashes (prefix)

  • prefixes – Allowed commands prefix. By default is slash. If you change the default behavior pass the list of prefixes to this argument.

  • ignore_case – Ignore case of the command

  • ignore_mention – Ignore mention in command (By default this filter pass only the commands addressed to current bot)

  • ignore_caption

    Ignore caption from message (in message types like photo, video, audio, etc) By default is True. If you want check commands in captions, you also should set required content_types.

    Examples:

    @dp.message_handler(commands=['myCommand'], commands_ignore_caption=False, content_types=ContentType.ANY)
    @dp.message_handler(Command(['myCommand'], ignore_caption=False), content_types=[ContentType.TEXT, ContentType.DOCUMENT])
    

Text

class aiogram.dispatcher.filters.Text(equals: Optional[Union[str, LazyProxy, Iterable[Union[str, LazyProxy]]]] = None, contains: Optional[Union[str, LazyProxy, Iterable[Union[str, LazyProxy]]]] = None, startswith: Optional[Union[str, LazyProxy, Iterable[Union[str, LazyProxy]]]] = None, endswith: Optional[Union[str, LazyProxy, Iterable[Union[str, LazyProxy]]]] = None, ignore_case=False)[source]

Bases: Filter

Simple text filter

Check text for one of pattern. Only one mode can be used in one filter. In every pattern, a single string is treated as a list with 1 element.

Parameters
  • equals – True if object’s text in the list

  • contains – True if object’s text contains all strings from the list

  • startswith – True if object’s text starts with any of strings from the list

  • endswith – True if object’s text ends with any of strings from the list

  • ignore_case – case insensitive

classmethod validate(full_config: Dict[str, Any])[source]

Here method validate is optional. If you need to use filter from filters factory you need to override this method.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

async check(obj: Union[Message, CallbackQuery, InlineQuery, Poll])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

HashTag

class aiogram.dispatcher.filters.HashTag(hashtags=None, cashtags=None)[source]

Bases: Filter

Filter for hashtag’s and cashtag’s

classmethod validate(full_config: Dict[str, Any])[source]

Here method validate is optional. If you need to use filter from filters factory you need to override this method.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

async check(message: Message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

Regexp

class aiogram.dispatcher.filters.Regexp(regexp)[source]

Bases: Filter

Regexp filter for messages and callback query

classmethod validate(full_config: Dict[str, Any])[source]

Here method validate is optional. If you need to use filter from filters factory you need to override this method.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

async check(obj: Union[Message, CallbackQuery, InlineQuery, Poll])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

RegexpCommandsFilter

class aiogram.dispatcher.filters.RegexpCommandsFilter(regexp_commands)[source]

Bases: BoundFilter

Check commands by regexp in message

key = 'regexp_commands'

Unique name of the filter argument. You need to override this attribute.

async check(message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

ContentTypeFilter

class aiogram.dispatcher.filters.ContentTypeFilter(content_types)[source]

Bases: BoundFilter

Check message content type

key = 'content_types'

Unique name of the filter argument. You need to override this attribute.

required = True

If True this filter will be added to the all of the registered handlers

default = ['text']

Default value for configure required filters

async check(message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

IsSenderContact

class aiogram.dispatcher.filters.IsSenderContact(is_sender_contact: bool)[source]

Bases: BoundFilter

Filter check that the contact matches the sender

is_sender_contact=True - contact matches the sender is_sender_contact=False - result will be inverted

key = 'is_sender_contact'

Unique name of the filter argument. You need to override this attribute.

async check(message: Message) bool[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

StateFilter

class aiogram.dispatcher.filters.StateFilter(dispatcher, state)[source]

Bases: BoundFilter

Check user state

key = 'state'

Unique name of the filter argument. You need to override this attribute.

required = True

If True this filter will be added to the all of the registered handlers

async check(obj)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

ExceptionsFilter

class aiogram.dispatcher.filters.ExceptionsFilter(exception)[source]

Bases: BoundFilter

Filter for exceptions

key = 'exception'

Unique name of the filter argument. You need to override this attribute.

async check(update, exception)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

IDFilter

class aiogram.dispatcher.filters.builtin.IDFilter(user_id: Optional[Union[Iterable[Union[int, str]], str, int]] = None, chat_id: Optional[Union[Iterable[Union[int, str]], str, int]] = None)[source]

Bases: Filter

Parameters
  • user_id

  • chat_id

classmethod validate(full_config: Dict[str, Any]) Optional[Dict[str, Any]][source]

Here method validate is optional. If you need to use filter from filters factory you need to override this method.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

async check(obj: Union[Message, CallbackQuery, InlineQuery, ChatMemberUpdated, ChatJoinRequest])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

AdminFilter

class aiogram.dispatcher.filters.AdminFilter(is_chat_admin: Optional[Union[Iterable[Union[int, str]], str, int, bool]] = None)[source]

Bases: Filter

Checks if user is admin in a chat. If is_chat_admin is not set, the filter will check in the current chat (correct only for messages). is_chat_admin is required for InlineQuery.

classmethod validate(full_config: Dict[str, Any]) Optional[Dict[str, Any]][source]

Here method validate is optional. If you need to use filter from filters factory you need to override this method.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

async check(obj: Union[Message, CallbackQuery, InlineQuery, ChatMemberUpdated]) bool[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

IsReplyFilter

class aiogram.dispatcher.filters.IsReplyFilter(is_reply)[source]

Bases: BoundFilter

Check if message is replied and send reply message to handler

key = 'is_reply'

Unique name of the filter argument. You need to override this attribute.

async check(msg: Message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

ForwardedMessageFilter

class aiogram.dispatcher.filters.ForwardedMessageFilter(is_forwarded: bool)[source]

Bases: BoundFilter

key = 'is_forwarded'

Unique name of the filter argument. You need to override this attribute.

async check(message: Message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

ChatTypeFilter

class aiogram.dispatcher.filters.ChatTypeFilter(chat_type: Container[ChatType])[source]

Bases: BoundFilter

key = 'chat_type'

Unique name of the filter argument. You need to override this attribute.

async check(obj: Union[Message, CallbackQuery, ChatMemberUpdated, InlineQuery])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

MediaGroupFilter

class aiogram.dispatcher.filters.MediaGroupFilter(is_media_group: bool)[source]

Bases: BoundFilter

Check if message is part of a media group.

is_media_group=True - the message is part of a media group is_media_group=False - the message is NOT part of a media group

key = 'is_media_group'

Unique name of the filter argument. You need to override this attribute.

async check(message: Message) bool[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

Making own filters (Custom filters)

Own filter can be:

  • any callable object

  • any async function

  • any anonymous function (Example: lambda msg: msg.text == 'spam')

  • Subclass of AbstractFilter, Filter or BoundFilter

AbstractFilter

class aiogram.dispatcher.filters.AbstractFilter[source]

Bases: ABC

Abstract class for custom filters.

abstract classmethod validate(full_config: Dict[str, Any]) Optional[Dict[str, Any]][source]

Validate and parse config.

This method will be called by the filters factory when you bind this filter. Must be overridden.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

abstract async check(*args) bool[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

Filter

class aiogram.dispatcher.filters.Filter[source]

Bases: AbstractFilter

You can make subclasses of that class for custom filters.

Method check must be overridden

classmethod validate(full_config: Dict[str, Any]) Optional[Dict[str, Any]][source]

Here method validate is optional. If you need to use filter from filters factory you need to override this method.

Parameters

full_config – dict with arguments passed to handler registrar

Returns

Current filter config

BoundFilter

class aiogram.dispatcher.filters.BoundFilter[source]

Bases: Filter

To easily create your own filters with one parameter, you can inherit from this filter.

You need to implement __init__ method with single argument related with key attribute and check method where you need to implement filter logic.

key = None

Unique name of the filter argument. You need to override this attribute.

required = False

If True this filter will be added to the all of the registered handlers

default = None

Default value for configure required filters

classmethod validate(full_config: Dict[str, Any]) Dict[str, Any][source]

If cls.key is not None and that is in config returns config with that argument.

Parameters

full_config

Returns

class ChatIdFilter(BoundFilter):
    key = 'chat_id'

    def __init__(self, chat_id: typing.Union[typing.Iterable, int]):
        if isinstance(chat_id, int):
            chat_id = [chat_id]
        self.chat_id = chat_id

    def check(self, message: types.Message) -> bool:
        return message.chat.id in self.chat_id


dp.filters_factory.bind(ChatIdFilter, event_handlers=[dp.message_handlers])