telegram.ext.filters Module¶
This module contains the Filters for use with the MessageHandler class.
-
class
telegram.ext.filters.Filters¶ Bases:
objectPredefined filters for use as the
filterargument oftelegram.ext.MessageHandler.Examples
Use
MessageHandler(Filters.video, callback_method)to filter all video messages. UseMessageHandler(Filters.contact, callback_method)for all contacts. etc.-
all= Filters.all¶ All Messages.
-
animation= Filters.animation¶ Messages that contain
telegram.Animation.
-
audio= Filters.audio¶ Messages that contain
telegram.Audio.
-
caption= Filters.caption¶ Messages with a caption. If a list of strings is passed, it filters messages to only allow those whose caption is appearing in the given list.
Examples
MessageHandler(Filters.caption, callback_method)Parameters: update (List[ str] | Tuple[str], optional) – Which captions to allow. Only exact matches are allowed. If not specified, will allow any message with a caption.
-
class
caption_entity(entity_type: str)¶ Bases:
telegram.ext.filters.MessageFilterFilters media messages to only allow those which have a
telegram.MessageEntitywhere their type matches entity_type.Examples
Example
MessageHandler(Filters.caption_entity("hashtag"), callback_method)Parameters: entity_type – Caption Entity type to check for. All types can be found as constants in telegram.MessageEntity.
-
class
chat(chat_id: Union[int, List[int]] = None, username: Union[str, List[str]] = None, allow_empty: bool = False)¶ Bases:
telegram.ext.filters.MessageFilterFilters messages to allow only those which are from a specified chat ID or username.
Examples
MessageHandler(Filters.chat(-1234), callback_method)Warning
chat_idswill give a copy of the saved chat ids asfrozenset. This is to ensure thread safety. To add/remove a chat, you should useadd_usernames(),add_chat_ids(),remove_usernames()andremove_chat_ids(). Only update the entire set byfilter.chat_ids/usernames = new_set, if you are entirely sure that it is not causing race conditions, as this will complete replace the current set of allowed chats.-
chat_ids¶ Which chat ID(s) to allow through.
Type: set( int), optional
-
usernames¶ Which username(s) (without leading ‘@’) to allow through.
Type: set( str), optional
-
allow_empty¶ Whether updates should be processed, if no chat is specified in
chat_idsandusernames.Type: bool, optional
Parameters: - chat_id (
int| List[int], optional) – Which chat ID(s) to allow through. - username (
str| List[str], optional) – Which username(s) to allow through. Leading ‘@’ s in usernames will be discarded. - allow_empty (
bool, optional) – Whether updates should be processed, if no chat is specified inchat_idsandusernames. Defaults toFalse
Raises: RuntimeError– If chat_id and username are both present.-
add_chat_ids(chat_id: Union[int, List[int]]) → None¶ Add one or more chats to the allowed chat ids.
Parameters: chat_id ( int| List[int], optional) – Which chat ID(s) to allow through.
-
add_usernames(username: Union[str, List[str]]) → None¶ Add one or more chats to the allowed usernames.
Parameters: username ( str| List[str], optional) – Which username(s) to allow through. Leading ‘@’ s in usernames will be discarded.
-
remove_chat_ids(chat_id: Union[int, List[int]]) → None¶ Remove one or more chats from allowed chat ids.
Parameters: chat_id ( int| List[int], optional) – Which chat ID(s) to disallow through.
-
-
command= Filters.command¶ Messages with a
telegram.MessageEntity.BOT_COMMAND. By default only allows messages starting with a bot command. PassFalseto also allow messages that contain a bot command anywhere in the text.Examples:
MessageHandler(Filters.command, command_at_start_callback) MessageHandler(Filters.command(False), command_anywhere_callback)
Note
Filters.textalso accepts messages containing a command.Parameters: update ( bool, optional) – Whether to only allow messages that start with a bot command. Defaults toTrue.
-
contact= Filters.contact¶ Messages that contain
telegram.Contact.
-
dice= Filters.dice¶ Dice Messages. If an integer or a list of integers is passed, it filters messages to only allow those whose dice value is appearing in the given list.
Examples
To allow any dice message, simply use
MessageHandler(Filters.dice, callback_method). To allow only dice with value 6, useMessageHandler(Filters.dice(6), callback_method). To allow only dice with value 5 or 6, useMessageHandler(Filters.dice([5, 6]), callback_method).Parameters: update ( int| List[int], optional) – Which values to allow. If not specified, will allow any dice message.Note
Dice messages don’t have text. If you want to filter either text or dice messages, use
Filters.text | Filters.dice.-
dice Dice messages with the emoji 🎲. Passing a list of integers is supported just as for
Filters.dice.
-
darts¶ Dice messages with the emoji 🎯. Passing a list of integers is supported just as for
Filters.dice.
-
basketball¶ Dice messages with the emoji 🏀. Passing a list of integers is supported just as for
Filters.dice.
-
-
document= Filters.document¶ Subset for messages containing a document/file.
Examples
Use these filters like:
Filters.document.mp3,Filters.document.mime_type("text/plain")etc. Or use justFilters.documentfor all document messages.-
category¶ Filters documents by their category in the mime-type attribute
Note
This Filter only filters by the mime_type of the document, it doesn’t check the validity of the document. The user can manipulate the mime-type of a message and send media with wrong types that don’t fit to this handler.
Example
Filters.documents.category('audio/')filters all types of audio sent as file, for example ‘audio/mpeg’ or ‘audio/x-wav’.
-
application¶ Same as
Filters.document.category("application").
-
audio Same as
Filters.document.category("audio").
-
image¶ Same as
Filters.document.category("image").
-
video¶ Same as
Filters.document.category("video").
-
text¶ Same as
Filters.document.category("text").
-
mime_type¶ Filters documents by their mime-type attribute
Note
This Filter only filters by the mime_type of the document, it doesn’t check the validity of document.
The user can manipulate the mime-type of a message and send media with wrong types that don’t fit to this handler.
Example
Filters.documents.mime_type('audio/mpeg')filters all audio in mp3 format.
-
apk¶ Same as
Filters.document.mime_type("application/vnd.android.package-archive")-
-
doc¶ Same as
Filters.document.mime_type("application/msword")-
-
docx¶ Same as
Filters.document.mime_type("application/vnd.openxmlformats-officedocument.wordprocessingml.document")-
-
exe¶ Same as
Filters.document.mime_type("application/x-ms-dos-executable")-
-
gif¶ Same as
Filters.document.mime_type("video/mp4")-
-
jpg¶ Same as
Filters.document.mime_type("image/jpeg")-
-
mp3¶ Same as
Filters.document.mime_type("audio/mpeg")-
-
pdf¶ Same as
Filters.document.mime_type("application/pdf")-
-
py¶ Same as
Filters.document.mime_type("text/x-python")-
-
svg¶ Same as
Filters.document.mime_type("image/svg+xml")-
-
txt¶ Same as
Filters.document.mime_type("text/plain")-
-
targz¶ Same as
Filters.document.mime_type("application/x-compressed-tar")-
-
wav¶ Same as
Filters.document.mime_type("audio/x-wav")-
-
xml¶ Same as
Filters.document.mime_type("application/xml")-
-
zip¶ Same as
Filters.document.mime_type("application/zip")-
-
-
class
entity(entity_type: str)¶ Bases:
telegram.ext.filters.MessageFilterFilters messages to only allow those which have a
telegram.MessageEntitywhere their type matches entity_type.Examples
Example
MessageHandler(Filters.entity("hashtag"), callback_method)Parameters: entity_type – Entity type to check for. All types can be found as constants in telegram.MessageEntity.
-
forwarded= Filters.forwarded¶ Messages that are forwarded.
-
game= Filters.game¶ Messages that contain
telegram.Game.
-
group= Filters.group¶ Messages sent in a group chat.
-
invoice= Filters.invoice¶ Messages that contain
telegram.Invoice.
-
class
language(lang: Union[str, List[str]])¶ Bases:
telegram.ext.filters.MessageFilterFilters messages to only allow those which are from users with a certain language code.
Note
According to official Telegram API documentation, not every single user has the language_code attribute. Do not count on this filter working on all users.
Examples
MessageHandler(Filters.language("en"), callback_method)Parameters: lang ( str| List[str]) – Which language code(s) to allow through. This will be matched using.startswithmeaning that ‘en’ will match both ‘en_US’ and ‘en_GB’.
-
location= Filters.location¶ Messages that contain
telegram.Location.
-
passport_data= Filters.passport_data¶ Messages that contain a
telegram.PassportData
-
photo= Filters.photo¶ Messages that contain
telegram.PhotoSize.
-
poll= Filters.poll¶ Messages that contain a
telegram.Poll.
-
private= Filters.private¶ Messages sent in a private chat.
-
class
regex(pattern: Union[str, Pattern[AnyStr]])¶ Bases:
telegram.ext.filters.MessageFilterFilters updates by searching for an occurrence of
patternin the message text. There.search()function is used to determine whether an update should be filtered.Refer to the documentation of the
remodule for more information.To get the groups and groupdict matched, see
telegram.ext.CallbackContext.matches.Examples
Use
MessageHandler(Filters.regex(r'help'), callback)to capture all messages that contain the word ‘help’. You can also useMessageHandler(Filters.regex(re.compile(r'help', re.IGNORECASE)), callback)if you want your pattern to be case insensitive. This approach is recommended if you need to specify flags on your pattern.Note
Filters use the same short circuiting logic as python’s and, or and not. This means that for example:
>>> Filters.regex(r'(a?x)') | Filters.regex(r'(b?x)')
With a message.text of x, will only ever return the matches for the first filter, since the second one is never evaluated.
Parameters: pattern ( str|Pattern) – The regex pattern.
-
reply= Filters.reply¶ Messages that are a reply to another message.
-
status_update= Filters.status_update¶ Subset for messages containing a status update.
Examples
Use these filters like:
Filters.status_update.new_chat_membersetc. Or use justFilters.status_updatefor all status update messages.-
chat_created¶ Messages that contain
telegram.Message.group_chat_created,telegram.Message.supergroup_chat_createdortelegram.Message.channel_chat_created.
-
delete_chat_photo¶ Messages that contain
telegram.Message.delete_chat_photo.
-
left_chat_member¶ Messages that contain
telegram.Message.left_chat_member.
-
migrate¶ Messages that contain
telegram.Message.migrate_from_chat_idor :attr: telegram.Message.migrate_from_chat_id.
-
new_chat_members¶ Messages that contain
telegram.Message.new_chat_members.
-
new_chat_photo¶ Messages that contain
telegram.Message.new_chat_photo.
-
new_chat_title¶ Messages that contain
telegram.Message.new_chat_title.
-
pinned_message¶ Messages that contain
telegram.Message.pinned_message.
-
-
sticker= Filters.sticker¶ Messages that contain
telegram.Sticker.
-
successful_payment= Filters.successful_payment¶ Messages that confirm a
telegram.SuccessfulPayment.
-
text= Filters.text Text Messages. If a list of strings is passed, it filters messages to only allow those whose text is appearing in the given list.
Examples
To allow any text message, simply use
MessageHandler(Filters.text, callback_method).A simple use case for passing a list is to allow only messages that were sent by a custom
telegram.ReplyKeyboardMarkup:buttons = ['Start', 'Settings', 'Back'] markup = ReplyKeyboardMarkup.from_column(buttons) ... MessageHandler(Filters.text(buttons), callback_method)
Note
- Dice messages don’t have text. If you want to filter either text or dice messages, use
Filters.text | Filters.dice. - Messages containing a command are accepted by this filter. Use
Filters.text & (~Filters.command), if you want to filter only text messages without commands.
Parameters: update (List[ str] | Tuple[str], optional) – Which messages to allow. Only exact matches are allowed. If not specified, will allow any text message.- Dice messages don’t have text. If you want to filter either text or dice messages, use
-
update= Filters.update¶ Subset for filtering the type of update.
Examples
Use these filters like:
Filters.update.messageorFilters.update.channel_postsetc. Or use justFilters.updatefor all types.-
message¶ Updates with
telegram.Update.message
-
edited_message¶ Updates with
telegram.Update.edited_message
-
messages¶ Updates with either
telegram.Update.messageortelegram.Update.edited_message
-
channel_post¶ Updates with
telegram.Update.channel_post
-
edited_channel_post¶ Updates with
telegram.Update.edited_channel_post
-
channel_posts¶ Updates with either
telegram.Update.channel_postortelegram.Update.edited_channel_post
-
-
class
user(user_id: Union[int, List[int]] = None, username: Union[str, List[str]] = None, allow_empty: bool = False)¶ Bases:
telegram.ext.filters.MessageFilterFilters messages to allow only those which are from specified user ID(s) or username(s).
Examples
MessageHandler(Filters.user(1234), callback_method)Warning
user_idswill give a copy of the saved user ids asfrozenset. This is to ensure thread safety. To add/remove a user, you should useadd_usernames(),add_user_ids(),remove_usernames()andremove_user_ids(). Only update the entire set byfilter.user_ids/usernames = new_set, if you are entirely sure that it is not causing race conditions, as this will complete replace the current set of allowed users.-
user_ids¶ Which user ID(s) to allow through.
Type: set( int), optional
-
usernames¶ Which username(s) (without leading ‘@’) to allow through.
Type: set( str), optional
-
allow_empty¶ Whether updates should be processed, if no user is specified in
user_idsandusernames.Type: bool, optional
Parameters: - user_id (
int| List[int], optional) – Which user ID(s) to allow through. - username (
str| List[str], optional) – Which username(s) to allow through. Leading ‘@’s in usernames will be discarded. - allow_empty (
bool, optional) – Whether updates should be processed, if no user is specified inuser_idsandusernames. Defaults toFalse
Raises: RuntimeError– If user_id and username are both present.-
add_user_ids(user_id: Union[int, List[int]]) → None¶ Add one or more users to the allowed user ids.
Parameters: user_id ( int| List[int], optional) – Which user ID(s) to allow through.
-
add_usernames(username: Union[str, List[str]]) → None¶ Add one or more users to the allowed usernames.
Parameters: username ( str| List[str], optional) – Which username(s) to allow through. Leading ‘@’s in usernames will be discarded.
-
remove_user_ids(user_id: Union[int, List[int]]) → None¶ Remove one or more users from allowed user ids.
Parameters: user_id ( int| List[int], optional) – Which user ID(s) to disallow through.
-
-
venue= Filters.venue¶ Messages that contain
telegram.Venue.
-
class
via_bot(bot_id: Union[int, List[int]] = None, username: Union[str, List[str]] = None, allow_empty: bool = False)¶ Bases:
telegram.ext.filters.MessageFilterFilters messages to allow only those which are from specified via_bot ID(s) or username(s).
Examples
MessageHandler(Filters.via_bot(1234), callback_method)Warning
bot_idswill give a copy of the saved bot ids asfrozenset. This is to ensure thread safety. To add/remove a bot, you should useadd_usernames(),add_bot_ids(),remove_usernames()andremove_bot_ids(). Only update the entire set byfilter.bot_ids/usernames = new_set, if you are entirely sure that it is not causing race conditions, as this will complete replace the current set of allowed bots.-
bot_ids¶ Which bot ID(s) to allow through.
Type: set( int), optional
-
usernames¶ Which username(s) (without leading ‘@’) to allow through.
Type: set( str), optional
-
allow_empty¶ Whether updates should be processed, if no bot is specified in
bot_idsandusernames.Type: bool, optional
Parameters: - bot_id (
int| List[int], optional) – Which bot ID(s) to allow through. - username (
str| List[str], optional) – Which username(s) to allow through. Leading ‘@’s in usernames will be discarded. - allow_empty (
bool, optional) – Whether updates should be processed, if no user is specified inbot_idsandusernames. Defaults toFalse
Raises: RuntimeError– If bot_id and username are both present.-
add_bot_ids(bot_id: Union[int, List[int]]) → None¶ Add one or more users to the allowed user ids.
Parameters: bot_id ( int| List[int], optional) – Which bot ID(s) to allow through.
-
add_usernames(username: Union[str, List[str]]) → None¶ Add one or more users to the allowed usernames.
Parameters: username ( str| List[str], optional) – Which username(s) to allow through. Leading ‘@’s in usernames will be discarded.
-
remove_bot_ids(bot_id: Union[int, List[int]]) → None¶ Remove one or more users from allowed user ids.
Parameters: bot_id ( int| List[int], optional) – Which bot ID(s) to disallow through.
-
-
video= Filters.video Messages that contain
telegram.Video.
-
video_note= Filters.video_note¶ Messages that contain
telegram.VideoNote.
-
voice= Filters.voice¶ Messages that contain
telegram.Voice.
-
-
class
telegram.ext.filters.BaseFilter¶ Bases:
abc.ABCBase class for all Filters.
Filters subclassing from this class can combined using bitwise operators:
And:
>>> (Filters.text & Filters.entity(MENTION))
Or:
>>> (Filters.audio | Filters.video)
Not:
>>> ~ Filters.command
Also works with more than two filters:
>>> (Filters.text & (Filters.entity(URL) | Filters.entity(TEXT_LINK))) >>> Filters.text & (~ Filters.forwarded)
Note
Filters use the same short circuiting logic as python’s and, or and not. This means that for example:
>>> Filters.regex(r'(a?x)') | Filters.regex(r'(b?x)')
With
message.text == x, will only ever return the matches for the first filter, since the second one is never evaluated.If you want to create your own filters create a class inheriting from either
MessageFilterorUpdateFilterand implement a :meth:filtermethod that returns a boolean:Trueif the message should be handled,Falseotherwise. Note that the filters work only as class instances, not actual class objects (so remember to initialize your filter classes).By default the filters name (what will get printed when converted to a string for display) will be the class name. If you want to overwrite this assign a better name to the
nameclass variable.-
name¶ Name for this filter. Defaults to the type of filter.
Type: str
-
data_filter¶ Whether this filter is a data filter. A data filter should return a dict with lists. The dict will be merged with
telegram.ext.CallbackContext’s internal dict in most cases (depends on the handler).Type: bool
-
-
class
telegram.ext.filters.MessageFilter¶ Bases:
telegram.ext.filters.BaseFilter,abc.ABCBase class for all Message Filters. In contrast to
UpdateFilter, the object passed tofilter()isupdate.effective_message.Please see
telegram.ext.BaseFilterfor details on how to create custom filters.-
name¶ Name for this filter. Defaults to the type of filter.
Type: str
-
data_filter¶ Whether this filter is a data filter. A data filter should return a dict with lists. The dict will be merged with
telegram.ext.CallbackContext’s internal dict in most cases (depends on the handler).Type: bool
-
filter(message: telegram.message.Message) → Union[bool, Dict[KT, VT], None]¶ This method must be overwritten.
Parameters: message ( telegram.Message) – The message that is tested.Returns: dictorbool
-
-
class
telegram.ext.filters.UpdateFilter¶ Bases:
telegram.ext.filters.BaseFilter,abc.ABCBase class for all Update Filters. In contrast to
UpdateFilter, the object passed tofilter()isupdate, which allows to create filters likeFilters.update.edited_message.Please see
telegram.ext.BaseFilterfor details on how to create custom filters.-
name¶ Name for this filter. Defaults to the type of filter.
Type: str
-
data_filter¶ Whether this filter is a data filter. A data filter should return a dict with lists. The dict will be merged with
telegram.ext.CallbackContext’s internal dict in most cases (depends on the handler).Type: bool
-
filter(update: telegram.update.Update) → Union[bool, Dict[KT, VT], None]¶ This method must be overwritten.
Parameters: update ( telegram.Update) – The update that is tested.Returns: dictorbool.
-
-
class
telegram.ext.filters.InvertedFilter(f: telegram.ext.filters.BaseFilter)¶ Bases:
telegram.ext.filters.UpdateFilterRepresents a filter that has been inverted.
Parameters: f – The filter to invert. -
filter(update: telegram.update.Update) → bool¶ This method must be overwritten.
Parameters: update ( telegram.Update) – The update that is tested.Returns: dictorbool.
-
-
class
telegram.ext.filters.MergedFilter(base_filter: telegram.ext.filters.BaseFilter, and_filter: telegram.ext.filters.BaseFilter = None, or_filter: telegram.ext.filters.BaseFilter = None)¶ Bases:
telegram.ext.filters.UpdateFilterRepresents a filter consisting of two other filters.
Parameters: - base_filter – Filter 1 of the merged filter.
- and_filter – Optional filter to “and” with base_filter. Mutually exclusive with or_filter.
- or_filter – Optional filter to “or” with base_filter. Mutually exclusive with and_filter.
-
filter(update: telegram.update.Update) → Union[bool, Dict[KT, VT]]¶ This method must be overwritten.
Parameters: update ( telegram.Update) – The update that is tested.Returns: dictorbool.