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 filter argument of
telegram.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 an iterable of strings is passed, it filters messages to only allow those whose caption is appearing in the given iterable.
Examples
MessageHandler(Filters.caption, callback_method)Parameters: update (Iterable[ 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)¶ Bases:
telegram.ext.filters.BaseFilterFilters 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=None, username=None)¶ Bases:
telegram.ext.filters.BaseFilterFilters messages to allow only those which are from specified chat ID.
Examples
MessageHandler(Filters.chat(-1234), callback_method)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. If username start swith ‘@’ symbol, it will be ignored.
Raises: ValueError– If chat_id and username are both present, or neither is.- chat_id (
-
command= Filters.command¶ Messages starting with
/.
-
contact= Filters.contact¶ Messages that contain
telegram.Contact.
-
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¶ This Filter 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¶ This Filter 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)¶ Bases:
telegram.ext.filters.BaseFilterFilters 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)¶ Bases:
telegram.ext.filters.BaseFilterFilters 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)¶ Bases:
telegram.ext.filters.BaseFilterFilters updates by searching for an occurrence of
patternin the message text. There.searchfunction 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 that pythons 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 an iterable of strings is passed, it filters messages to only allow those whose text is appearing in the given iterable.
Examples
To allow any text message, simply use
MessageHandler(Filters.text, callback_method).A simple usecase for passing an iterable is to allow only messages that were send by a custom
telegram.ReplyKeyboardMarkup:buttons = ['Start', 'Settings', 'Back'] markup = ReplyKeyboardMarkup.from_column(buttons) ... MessageHandler(Filters.text(buttons), callback_method)
Parameters: update (Iterable[ str], optional) – Which messages to allow. Only exact matches are allowed. If not specified, will allow any text message.
-
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=None, username=None)¶ Bases:
telegram.ext.filters.BaseFilterFilters messages to allow only those which are from specified user ID.
Examples
MessageHandler(Filters.user(1234), callback_method)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. If username starts with ‘@’ symbol, it will be ignored.
Raises: ValueError– If chat_id and username are both present, or neither is.- user_id (
-
venue= Filters.venue¶ Messages that contain
telegram.Venue.
-
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:
objectBase class for all Message Filters.
Subclassing from this class filters to be 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 that pythons 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.
If you want to create your own filters create a class inheriting from this class and implement a filter method that returns a boolean: True if the message should be handled, False otherwise. 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 name class variable.
-
name¶ Name for this filter. Defaults to the type of filter.
Type: str
-
update_filter¶ Whether this filter should work on update. If
Falseit will run the filter onupdate.effective_message`. Default isFalse.Type: bool
-
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)¶ This method must be overwritten.
Note
If
update_filteris false then the first argument is message and of typetelegram.Message.Parameters: update ( telegram.Update) – The update that is tested.Returns: dictorbool
-
-
class
telegram.ext.filters.InvertedFilter(f)¶ Bases:
telegram.ext.filters.BaseFilterRepresents a filter that has been inverted.
Parameters: f – The filter to invert. -
filter(update)¶ This method must be overwritten.
Note
If
update_filteris false then the first argument is message and of typetelegram.Message.Parameters: update ( telegram.Update) – The update that is tested.Returns: dictorbool
-
-
class
telegram.ext.filters.MergedFilter(base_filter, and_filter=None, or_filter=None)¶ Bases:
telegram.ext.filters.BaseFilterRepresents 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)¶ This method must be overwritten.
Note
If
update_filteris false then the first argument is message and of typetelegram.Message.Parameters: update ( telegram.Update) – The update that is tested.Returns: dictorbool