Filters¶
Basics¶
Filter factory greatly simplifies the reuse of filters when registering handlers.
Filters factory¶
-
class
aiogram.dispatcher.filters.factory.FiltersFactory(dispatcher)[source]¶ Bases:
objectFilters 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
AbstractFiltervalidator – custom validator.
event_handlers – list of instances of
Handlerexclude_event_handlers – list of excluded event handlers (
Handler)
-
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.FilterYou can handle commands by using this filter.
If filter is successful processed the
Command.CommandObjwill 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:
commandcommands_prefix(will be passed asprefixes)commands_ignore_mention(will be passed asignore_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:
objectInstance of this object is always has command and it prefix.
Can be passed as keyword argument
commandto 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, re.Pattern, None] = None)[source]¶ Bases:
aiogram.dispatcher.filters.builtin.CommandThis filter based on
Commandfilter but can handle only/startcommand.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(...)).
CommandHelp¶
-
class
aiogram.dispatcher.filters.builtin.CommandHelp[source]¶ Bases:
aiogram.dispatcher.filters.builtin.CommandThis filter based on
Commandfilter but can handle only/helpcommand.
CommandSettings¶
-
class
aiogram.dispatcher.filters.builtin.CommandSettings[source]¶ Bases:
aiogram.dispatcher.filters.builtin.CommandThis filter based on
Commandfilter but can handle only/settingscommand.
CommandPrivacy¶
-
class
aiogram.dispatcher.filters.builtin.CommandPrivacy[source]¶ Bases:
aiogram.dispatcher.filters.builtin.CommandThis filter based on
Commandfilter but can handle only/privacycommand.
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.FilterSimple 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
HashTag¶
-
class
aiogram.dispatcher.filters.builtin.HashTag(hashtags=None, cashtags=None)[source]¶ Bases:
aiogram.dispatcher.filters.filters.FilterFilter for hashtag’s and cashtag’s
Regexp¶
-
class
aiogram.dispatcher.filters.builtin.Regexp(regexp)[source]¶ Bases:
aiogram.dispatcher.filters.filters.FilterRegexp filter for messages and callback query
RegexpCommandsFilter¶
-
class
aiogram.dispatcher.filters.builtin.RegexpCommandsFilter(regexp_commands)[source]¶ Bases:
aiogram.dispatcher.filters.filters.BoundFilterCheck commands by regexp in message
ContentTypeFilter¶
-
class
aiogram.dispatcher.filters.builtin.ContentTypeFilter(content_types)[source]¶ Bases:
aiogram.dispatcher.filters.filters.BoundFilterCheck message content type
StateFilter¶
-
class
aiogram.dispatcher.filters.builtin.StateFilter(dispatcher, state)[source]¶ Bases:
aiogram.dispatcher.filters.filters.BoundFilterCheck user state
ExceptionsFilter¶
-
class
aiogram.dispatcher.filters.builtin.ExceptionsFilter(exception)[source]¶ Bases:
aiogram.dispatcher.filters.filters.BoundFilterFilter for exceptions
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
validateis 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
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.FilterChecks 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
validateis 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
-
classmethod
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,FilterorBoundFilter
AbstractFilter¶
-
class
aiogram.dispatcher.filters.filters.AbstractFilter[source]¶ Bases:
abc.ABCAbstract 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 classmethod
Filter¶
-
class
aiogram.dispatcher.filters.filters.Filter[source]¶ Bases:
aiogram.dispatcher.filters.filters.AbstractFilterYou can make subclasses of that class for custom filters.
Method
checkmust be overridden-
classmethod
validate(full_config: Dict[str, Any]) → Optional[Dict[str, Any]][source]¶ Here method
validateis 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
-
classmethod
BoundFilter¶
-
class
aiogram.dispatcher.filters.filters.BoundFilter[source]¶ Bases:
aiogram.dispatcher.filters.filters.FilterTo 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 andcheckmethod where you need to implement filter logic.-
key= None¶ Unique name of the filter argument. You need to override this attribute.
-
required= False¶ If
Truethis filter will be added to the all of the registered handlers
-
default= None¶ Default value for configure required filters
-
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])