Filters

Basics

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

Filters factory

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

Bases: object

Filters factory

bind(callback: Union[Callable, aiogram.dispatcher.filters.filters.AbstractFilter], validator: Optional[Callable] = None, event_handlers: Optional[List[aiogram.dispatcher.handler.Handler]] = None, exclude_event_handlers: Optional[Iterable[aiogram.dispatcher.handler.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, aiogram.dispatcher.filters.filters.AbstractFilter])[source]

Unregister callback

Parameters

callback – callable of subclass of AbstractFilter

resolve(event_handler, *custom_filters, **full_config) → List[Union[Callable, aiogram.dispatcher.filters.filters.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.builtin.Command(commands: Union[Iterable, str], prefixes: Union[Iterable, str] = '/', ignore_case: bool = True, ignore_mention: bool = False)[source]

Bases: aiogram.dispatcher.filters.filters.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)

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

Parameters

full_config

Returns

config or empty dict

async check(message: aiogram.types.message.Message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

class CommandObj(prefix: str = '/', command: str = '', mention: str = None, args: 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 = '/'

Command without prefix and mention

command = ''

Mention (if available)

mention = None

Command argument

property mentioned

This command has mention?

Returns

property text

Generate original text from object

Returns

CommandStart

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

Bases: aiogram.dispatcher.filters.builtin.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: aiogram.types.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.builtin.CommandHelp[source]

Bases: aiogram.dispatcher.filters.builtin.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)

CommandSettings

class aiogram.dispatcher.filters.builtin.CommandSettings[source]

Bases: aiogram.dispatcher.filters.builtin.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)

CommandPrivacy

class aiogram.dispatcher.filters.builtin.CommandPrivacy[source]

Bases: aiogram.dispatcher.filters.builtin.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)

Text

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

Bases: aiogram.dispatcher.filters.filters.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[aiogram.types.message.Message, aiogram.types.callback_query.CallbackQuery, aiogram.types.inline_query.InlineQuery, aiogram.types.poll.Poll])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

HashTag

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

Bases: aiogram.dispatcher.filters.filters.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: aiogram.types.message.Message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

Regexp

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

Bases: aiogram.dispatcher.filters.filters.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[aiogram.types.message.Message, aiogram.types.callback_query.CallbackQuery, aiogram.types.inline_query.InlineQuery, aiogram.types.poll.Poll])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

RegexpCommandsFilter

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

Bases: aiogram.dispatcher.filters.filters.BoundFilter

Check commands by regexp in message

async check(message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

ContentTypeFilter

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

Bases: aiogram.dispatcher.filters.filters.BoundFilter

Check message content type

async check(message)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

IsSenderContact

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

Bases: aiogram.dispatcher.filters.filters.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

async check(message: aiogram.types.message.Message) → bool[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

StateFilter

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

Bases: aiogram.dispatcher.filters.filters.BoundFilter

Check user state

async check(obj)[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

ExceptionsFilter

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

Bases: aiogram.dispatcher.filters.filters.BoundFilter

Filter for exceptions

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: Union[Iterable[Union[int, str]], str, int, None] = None, chat_id: Union[Iterable[Union[int, str]], str, int, None] = None)[source]

Bases: aiogram.dispatcher.filters.filters.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[aiogram.types.message.Message, aiogram.types.callback_query.CallbackQuery, aiogram.types.inline_query.InlineQuery])[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

AdminFilter

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

Bases: aiogram.dispatcher.filters.filters.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[aiogram.types.message.Message, aiogram.types.callback_query.CallbackQuery, aiogram.types.inline_query.InlineQuery]) → bool[source]

Will be called when filters checks.

This method must be overridden.

Parameters

args

Returns

IsReplyFilter

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.filters.AbstractFilter[source]

Bases: abc.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.filters.Filter[source]

Bases: aiogram.dispatcher.filters.filters.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.filters.BoundFilter[source]

Bases: aiogram.dispatcher.filters.filters.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])