filters Module¶
This module contains filters for use with telegram.ext.MessageHandler,
telegram.ext.CommandHandler, or telegram.ext.PrefixHandler.
Changed in version 20.0:
Filters are no longer callable, if you’re using a custom filter and are calling an existing filter, then switch to the new syntax:
filters.{filter}.check_update(update).Removed the
Filtersclass. The filters are now directly attributes/classes of thefiltersmodule.The names of all filters has been updated:
Filter classes which are ready for use, e.g
Filters.allare now capitalized, e.gfilters.ALL.Filters which need to be initialized are now in CamelCase. E.g.
filters.User(...).Filters which do both (like
Filters.text) are now split as ready-to-use versionfilters.TEXTand class versionfilters.Text(...).
Changed in version 22.0: Removed deprecated attribute CHAT.
- telegram.ext.filters.ANIMATION = filters.ANIMATION[source]¶
Messages that contain
telegram.Message.animation.
- telegram.ext.filters.ATTACHMENT = filters.ATTACHMENT[source]¶
Messages that contain
telegram.Message.effective_attachment().Added in version 13.6.
- telegram.ext.filters.AUDIO = filters.AUDIO[source]¶
Messages that contain
telegram.Message.audio.
- telegram.ext.filters.BOOST_ADDED = filters.BOOST_ADDED[source]¶
Messages that contain
telegram.Message.boost_added.
- telegram.ext.filters.CAPTION = filters.CAPTION[source]¶
Shortcut for
telegram.ext.filters.Caption().Examples
To allow any caption, simply use
MessageHandler(filters.CAPTION, callback_method).
- telegram.ext.filters.CHECKLIST = filters.CHECKLIST[source]¶
Messages that contain
telegram.Message.checklist.Added in version 22.3.
- telegram.ext.filters.COMMAND = filters.COMMAND[source]¶
Shortcut for
telegram.ext.filters.Command().Examples
To allow messages starting with a command use
MessageHandler(filters.COMMAND, command_at_start_callback).
- telegram.ext.filters.CONTACT = filters.CONTACT[source]¶
Messages that contain
telegram.Message.contact.
- telegram.ext.filters.DIRECT_MESSAGES = filters.DIRECT_MESSAGES[source]¶
Filter chats which are the direct messages for a channel.
See also
Added in version 22.4.
- telegram.ext.filters.EFFECT_ID = filters.EFFECT_ID[source]¶
Messages that contain
telegram.Message.effect_id.Added in version 21.3.
- telegram.ext.filters.FORUM = filters.FORUM[source]¶
Messages that are from a forum (topics enabled) chat.
Added in version 22.4.
- telegram.ext.filters.FORWARDED = filters.FORWARDED[source]¶
Messages that contain
telegram.Message.forward_origin.Changed in version 20.8: Now based on
telegram.Message.forward_origininstead oftelegram.Message.forward_date.
- telegram.ext.filters.GAME = filters.GAME[source]¶
Messages that contain
telegram.Message.game.
- telegram.ext.filters.GIVEAWAY = filters.GIVEAWAY[source]¶
Messages that contain
telegram.Message.giveaway.
- telegram.ext.filters.GIVEAWAY_WINNERS = filters.GIVEAWAY_WINNERS[source]¶
Messages that contain
telegram.Message.giveaway_winners.
- telegram.ext.filters.HAS_MEDIA_SPOILER = filters.HAS_MEDIA_SPOILER[source]¶
Messages that contain
telegram.Message.has_media_spoiler.Added in version 20.0.
- telegram.ext.filters.HAS_PROTECTED_CONTENT = filters.HAS_PROTECTED_CONTENT[source]¶
Messages that contain
telegram.Message.has_protected_content.Added in version 13.9.
- telegram.ext.filters.INVOICE = filters.INVOICE[source]¶
Messages that contain
telegram.Message.invoice.
- telegram.ext.filters.IS_AUTOMATIC_FORWARD = filters.IS_AUTOMATIC_FORWARD[source]¶
Messages that contain
telegram.Message.is_automatic_forward.Added in version 13.9.
- telegram.ext.filters.IS_FROM_OFFLINE = filters.IS_FROM_OFFLINE[source]¶
Messages that contain
telegram.Message.is_from_offline.Added in version 21.1.
- telegram.ext.filters.IS_TOPIC_MESSAGE = filters.IS_TOPIC_MESSAGE[source]¶
Messages that contain
telegram.Message.is_topic_message.Added in version 20.0.
- telegram.ext.filters.LOCATION = filters.LOCATION[source]¶
Messages that contain
telegram.Message.location.
- telegram.ext.filters.PAID_MEDIA = filters.PAID_MEDIA[source]¶
Messages that contain
telegram.Message.paid_media.Added in version 21.4.
- telegram.ext.filters.PASSPORT_DATA = filters.PASSPORT_DATA[source]¶
Messages that contain
telegram.Message.passport_data.
- telegram.ext.filters.PHOTO = filters.PHOTO[source]¶
Messages that contain
telegram.Message.photo.
- telegram.ext.filters.POLL = filters.POLL[source]¶
Messages that contain
telegram.Message.poll.
- telegram.ext.filters.PREMIUM_USER = filters.PREMIUM_USER[source]¶
This filter filters any message from a
Telegram Premium userastelegram.Update.effective_user.Added in version 20.0.
- telegram.ext.filters.REPLY = filters.REPLY[source]¶
Messages that contain
telegram.Message.reply_to_message.
- telegram.ext.filters.REPLY_TO_STORY = filters.REPLY_TO_STORY[source]¶
Messages that contain
telegram.Message.reply_to_story.
- telegram.ext.filters.SENDER_BOOST_COUNT = filters.SENDER_BOOST_COUNT[source]¶
Messages that contain
telegram.Message.sender_boost_count.
- telegram.ext.filters.STORY = filters.STORY[source]¶
Messages that contain
telegram.Message.story.Added in version 20.5.
- telegram.ext.filters.SUCCESSFUL_PAYMENT = filters.SUCCESSFUL_PAYMENT[source]¶
Messages that contain
telegram.Message.successful_payment.
- telegram.ext.filters.SUGGESTED_POST_INFO = filters.SUGGESTED_POST_INFO[source]¶
Messages that contain
telegram.Message.suggested_post_info.Added in version 22.4.
- telegram.ext.filters.TEXT = filters.TEXT[source]¶
Shortcut for
telegram.ext.filters.Text().Examples
To allow any text message, simply use
MessageHandler(filters.TEXT, callback_method).
- telegram.ext.filters.USER = filters.USER[source]¶
This filter filters any message that has a
telegram.Message.from_user.
- telegram.ext.filters.USER_ATTACHMENT = filters.USER_ATTACHMENT[source]¶
This filter filters any message that have a user who added the bot to their
attachment menuastelegram.Update.effective_user.Added in version 20.0.
- telegram.ext.filters.VENUE = filters.VENUE[source]¶
Messages that contain
telegram.Message.venue.
- telegram.ext.filters.VIA_BOT = filters.VIA_BOT[source]¶
This filter filters for message that were sent via any bot.
See also
- telegram.ext.filters.VIDEO = filters.VIDEO[source]¶
Messages that contain
telegram.Message.video.
- telegram.ext.filters.VIDEO_NOTE = filters.VIDEO_NOTE[source]¶
Messages that contain
telegram.Message.video_note.
- telegram.ext.filters.VOICE = filters.VOICE[source]¶
Messages that contain
telegram.Message.voice.
- class telegram.ext.filters.BaseFilter(name=None, data_filter=False)[source]¶
Bases:
objectBase 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
Exclusive Or:
filters.Regex('To Be') ^ filters.Regex('Not 2B')
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,orandnot. 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 afilter()method 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.Available In
Added in version 20.0: Added the arguments
nameanddata_filter.- Parameters:
name (
str) – Name for this filter. Defaults to the type of filter.data_filter (
bool) – Whether this filter is a data filter. A data filter should return a dict with lists. The dict will be merged withtelegram.ext.CallbackContext’s internal dict in most cases (depends on the handler).
- __and__(other)[source]¶
Defines AND bitwise operator for
BaseFilterobject. The combined filter accepts an update only if it is accepted by both filters. For example,filters.PHOTO & filters.CAPTIONwill only accept messages that contain both a photo and a caption.- Returns:
- __or__(other)[source]¶
Defines OR bitwise operator for
BaseFilterobject. The combined filter accepts an update only if it is accepted by any of the filters. For example,filters.PHOTO | filters.CAPTIONwill only accept messages that contain photo or caption or both.- Returns:
- __xor__(other)[source]¶
Defines XOR bitwise operator for
BaseFilterobject. The combined filter accepts an update only if it is accepted by any of the filters and not both of them. For example,filters.PHOTO ^ filters.CAPTIONwill only accept messages that contain photo or caption, not both of them.- Returns:
- __invert__()[source]¶
Defines NOT bitwise operator for
BaseFilterobject. The combined filter accepts an update only if it is accepted by any of the filters. For example,~ filters.PHOTOwill only accept messages that do not contain photo.- Returns:
- check_update(update)[source]¶
Checks if the specified update should be handled by this filter.
Changed in version 21.1: This filter now also returns
Trueif the update containsbusiness_messageoredited_business_message.- Parameters:
update (
telegram.Update) – The update to check.- Returns:
Trueif the update contains one ofchannel_post,message,edited_channel_post,edited_message,telegram.Update.business_message,telegram.Update.edited_business_message, orFalseotherwise.- Return type:
- class telegram.ext.filters.Caption(strings=None)[source]¶
Bases:
telegram.ext.filters.MessageFilterMessages 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(['PTB rocks!', 'PTB']), callback_method_2)See also
- class telegram.ext.filters.CaptionEntity(entity_type)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters media messages to only allow those which have a
telegram.MessageEntitywhere theirtypematches entity_type.Examples
MessageHandler(filters.CaptionEntity("hashtag"), callback_method)- Parameters:
entity_type (
str) – Caption Entity type to check for. All types can be found as constants intelegram.MessageEntity.
- class telegram.ext.filters.CaptionRegex(pattern)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters updates by searching for an occurrence of
patternin the message caption.This filter works similarly to
Regex, with the only exception being that it applies to the message caption instead of the text.Examples
Use
MessageHandler(filters.PHOTO & filters.CaptionRegex(r'help'), callback)to capture all photos with caption containing the word ‘help’.Note
This filter will not work on simple text messages, but only on media with caption.
- Parameters:
pattern (
str|re.Pattern) – The regex pattern.
- class telegram.ext.filters.Chat(chat_id=None, username=None, allow_empty=False)[source]¶
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_chat_ids(), andremove_chat_ids(). Only update the entire set byfilter.chat_ids = 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.- Parameters:
chat_id (
int| Collection[int], optional) – Which chat ID(s) to allow through.username (
str| Collection[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.
- allow_empty[source]¶
Whether updates should be processed, if no chat is specified in
chat_idsandusernames.- Type:
- Raises:
RuntimeError – If
chat_idandusernameare both present.
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernameswill give a copy of the saved usernames asfrozenset. This is to ensure thread safety. To add/remove a user, you should useadd_usernames(), andremove_usernames(). Only update the entire set byfilter.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.- Returns:
frozenset(
str)
- class telegram.ext.filters.ChatType[source]¶
Bases:
objectSubset for filtering the type of chat.
Examples
Use these filters like:
filters.ChatType.CHANNELorfilters.ChatType.SUPERGROUPetc.Caution
filters.ChatTypeitself is not a filter, but just a convenience namespace.
- class telegram.ext.filters.Command(only_start=True)[source]¶
Bases:
telegram.ext.filters.MessageFilterMessages 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(False), command_anywhere_callback)See also
Note
telegram.ext.filters.TEXTalso accepts messages containing a command.- Parameters:
only_start (
bool, optional) – Whether to only allow messages that start with a bot command. Defaults toTrue.
- class telegram.ext.filters.Dice(values=None, emoji=None)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice 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.
Added in version 13.4.
Examples
To allow any dice message, simply use
MessageHandler(filters.Dice.ALL, callback_method).To allow any dice message, but with value 3 or 4, use
MessageHandler(filters.Dice([3, 4]), callback_method)To allow only dice messages with the emoji 🎲, but any value, use
MessageHandler(filters.Dice.DICE, callback_method).To allow only dice messages with the emoji 🎯 and with value 6, use
MessageHandler(filters.Dice.Darts(6), callback_method).To allow only dice messages with the emoji ⚽ and with value 5 or 6, use
MessageHandler(filters.Dice.Football([5, 6]), callback_method).Note
Dice messages don’t have text. If you want to filter either text or dice messages, use
filters.TEXT | filters.Dice.ALL.- Parameters:
values (
int| Collection[int], optional) – Which values to allow. If not specified, will allow the specified dice message.
- class Basketball(values)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice messages with the emoji 🏀. Supports passing a list of integers.
- BASKETBALL = filters.Dice.BASKETBALL[source]¶
Dice messages with the emoji 🏀. Matches any dice value.
- class Bowling(values)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice messages with the emoji 🎳. Supports passing a list of integers.
- class Darts(values)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice messages with the emoji 🎯. Supports passing a list of integers.
- class Dice(values)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice messages with the emoji 🎲. Supports passing a list of integers.
- class Football(values)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice messages with the emoji ⚽. Supports passing a list of integers.
- class SlotMachine(values)[source]¶
Bases:
telegram.ext.filters.MessageFilterDice messages with the emoji 🎰. Supports passing a list of integers.
- class telegram.ext.filters.Document[source]¶
Bases:
objectSubset for messages containing a document/file.
Examples
Use these filters like:
filters.Document.MP3,filters.Document.MimeType("text/plain")etc. Or just usefilters.Document.ALLfor all document messages.Caution
filters.Documentitself is not a filter, but just a convenience namespace.- ALL = filters.Document.ALL[source]¶
Messages that contain a
telegram.Message.document.
- class Category(category)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters documents by their category in the mime-type attribute.
Example
filters.Document.Category('audio/')returnsTruefor all types of audio sent as a file, for example'audio/mpeg'or'audio/x-wav'.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.
- APPLICATION = filters.Document.Category('application/')[source]¶
Use as
filters.Document.APPLICATION.
- class FileExtension(file_extension, case_sensitive=False)[source]¶
Bases:
telegram.ext.filters.MessageFilterThis filter filters documents by their file ending/extension.
- Parameters:
file_extension (
str|None) – Media file extension you want to filter.case_sensitive (
bool, optional) – PassTrueto make the filter case sensitive. Default:False.
Example
filters.Document.FileExtension("jpg")filters files with extension".jpg".filters.Document.FileExtension(".jpg")filters files with extension"..jpg".filters.Document.FileExtension("Dockerfile", case_sensitive=True)filters files with extension".Dockerfile"minding the case.filters.Document.FileExtension(None)filters files without a dot in the filename.
Note
This Filter only filters by the file ending/extension of the document, it doesn’t check the validity of document.
The user can manipulate the file extension of a document and send media with wrong types that don’t fit to this handler.
Case insensitive by default, you may change this with the flag
case_sensitive=True.Extension should be passed without leading dot unless it’s a part of the extension.
Pass
Noneto filter files with no extension, i.e. without a dot in the filename.
- class MimeType(mimetype)[source]¶
Bases:
telegram.ext.filters.MessageFilterThis Filter filters documents by their mime-type attribute.
Example
filters.Document.MimeType('audio/mpeg')filters all audio in .mp3 format.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.
- APK = filters.Document.MimeType('application/vnd.android.package-archive')[source]¶
Use as
filters.Document.APK.
- DOCX = filters.Document.MimeType('application/vnd.openxmlformats-officedocument.wordprocessingml.document')[source]¶
Use as
filters.Document.DOCX.
- class telegram.ext.filters.Entity(entity_type)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters messages to only allow those which have a
telegram.MessageEntitywhere theirtypematches entity_type.Examples
MessageHandler(filters.Entity("hashtag"), callback_method)- Parameters:
entity_type (
str) – Entity type to check for. All types can be found as constants intelegram.MessageEntity.
- class telegram.ext.filters.ForwardedFrom(chat_id=None, username=None, allow_empty=False)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters messages to allow only those which are forwarded from the specified chat ID(s) or username(s) based on
telegram.Message.forward_originand in particularAdded in version 13.5.
Changed in version 20.8: Was previously based on
telegram.Message.forward_fromandtelegram.Message.forward_from_chat.Examples
MessageHandler(filters.ForwardedFrom(chat_id=1234), callback_method)Note
When a user has disallowed adding a link to their account while forwarding their messages, this filter will not work since
telegram.Message.forward_originwill be of typetelegram.MessageOriginHiddenUser. However, this behaviour is undocumented and might be changed by Telegram.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_chat_ids(), andremove_chat_ids(). Only update the entire set byfilter.chat_ids = 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.- Parameters:
chat_id (
int| Collection[int], optional) – Which chat/user ID(s) to allow through.username (
str| Collection[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.
- allow_empty[source]¶
Whether updates should be processed, if no chat is specified in
chat_idsandusernames.- Type:
- Raises:
RuntimeError – If both
chat_idandusernameare present.
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernameswill give a copy of the saved usernames asfrozenset. This is to ensure thread safety. To add/remove a user, you should useadd_usernames(), andremove_usernames(). Only update the entire set byfilter.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.- Returns:
frozenset(
str)
- class telegram.ext.filters.Language(lang)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters messages to only allow those which are from users with a certain language code.
Note
According to official Telegram Bot 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| Collection[str]) – Which language code(s) to allow through. This will be matched usingstr.startswithmeaning that ‘en’ will match both ‘en_US’ and ‘en_GB’.
- class telegram.ext.filters.Mention(mentions)[source]¶
Bases:
telegram.ext.filters.MessageFilterMessages containing mentions of specified users or chats.
Examples
MessageHandler(filters.Mention("username"), callback) MessageHandler(filters.Mention(["@username", 123456]), callback)
Added in version 20.7.
- Parameters:
mentions (
int|str|telegram.User| Collection[int|str|telegram.User]) – Specifies the users and chats to filter for. Messages that do not mention at least one of the specified users or chats will not be handled. Leading'@'s in usernames will be discarded.
- class telegram.ext.filters.MessageFilter(name=None, data_filter=False)[source]¶
Bases:
telegram.ext.filters.BaseFilterBase class for all Message Filters. In contrast to
UpdateFilter, the object passed tofilter()istelegram.Update.effective_message.Please see
BaseFilterfor details on how to create custom filters.See also
Available In
- check_update(update)[source]¶
Checks if the specified update should be handled by this filter by passing
effective_messagetofilter().
- class telegram.ext.filters.Regex(pattern)[source]¶
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,orandnot. This means that for example:>>> filters.Regex(r'(a?x)') | filters.Regex(r'(b?x)')
With a
telegram.Message.textof x, will only ever return the matches for the first filter, since the second one is never evaluated.See also
- Parameters:
pattern (
str|re.Pattern) – The regex pattern.
- class telegram.ext.filters.SenderChat(chat_id=None, username=None, allow_empty=False)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters messages to allow only those which are from a specified sender chat’s chat ID or username.
Examples
To filter for messages sent to a group by a channel with ID
-1234, useMessageHandler(filters.SenderChat(-1234), callback_method).To filter for messages of anonymous admins in a super group with username
@anonymous, useMessageHandler(filters.SenderChat(username='anonymous'), callback_method).To filter for messages sent to a group by any channel, use
MessageHandler(filters.SenderChat.CHANNEL, callback_method).To filter for messages of anonymous admins in any super group, use
MessageHandler(filters.SenderChat.SUPERGROUP, callback_method).To filter for messages forwarded to a discussion group from any channel or of anonymous admins in any super group, use
MessageHandler(filters.SenderChat.ALL, callback)
Note
Remember,
sender_chatis also set for messages in a channel as the channel itself, so when your bot is an admin in a channel and the linked discussion group, you would receive the message twice (once from inside the channel, once inside the discussion group). Since v13.9, the fieldtelegram.Message.is_automatic_forwardwill beTruefor the discussion group message.Warning
chat_idswill return a copy of the saved chat ids asfrozenset. This is to ensure thread safety. To add/remove a chat, you should useadd_chat_ids(), andremove_chat_ids(). Only update the entire set byfilter.chat_ids = 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.- Parameters:
chat_id (
int| Collection[int], optional) – Which sender chat chat ID(s) to allow through.username (
str| Collection[str], optional) – Which sender chat username(s) to allow through. Leading'@'s in usernames will be discarded.allow_empty (
bool, optional) – Whether updates should be processed, if no sender chat is specified inchat_idsandusernames. Defaults toFalse.
- allow_empty[source]¶
Whether updates should be processed, if no sender chat is specified in
chat_idsandusernames.- Type:
- Raises:
RuntimeError – If both
chat_idandusernameare present.
- ALL = filters.SenderChat.ALL[source]¶
All messages with a
telegram.Message.sender_chat.
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernameswill give a copy of the saved usernames asfrozenset. This is to ensure thread safety. To add/remove a user, you should useadd_usernames(), andremove_usernames(). Only update the entire set byfilter.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.- Returns:
frozenset(
str)
- class telegram.ext.filters.StatusUpdate[source]¶
Bases:
objectSubset for messages containing a status update.
Examples
Use these filters like:
filters.StatusUpdate.NEW_CHAT_MEMBERSetc. Or use justfilters.StatusUpdate.ALLfor all status update messages.Caution
filters.StatusUpdateitself is not a filter, but just a convenience namespace.Changed in version 22.0: Removed deprecated attribute USER_SHARED.
- CHAT_BACKGROUND_SET = filters.StatusUpdate.CHAT_BACKGROUND_SET[source]¶
Messages that contain
telegram.Message.chat_background_set.
- CHAT_CREATED = filters.StatusUpdate.CHAT_CREATED[source]¶
Messages that contain
telegram.Message.group_chat_created,telegram.Message.supergroup_chat_createdortelegram.Message.channel_chat_created.
- CHAT_SHARED = filters.StatusUpdate.CHAT_SHARED[source]¶
Messages that contain
telegram.Message.chat_shared.Added in version 20.1.
- CHECKLIST_TASKS_ADDED = filters.StatusUpdate.CHECKLIST_TASKS_ADDED[source]¶
Messages that contain
telegram.Message.checklist_tasks_added.Added in version 22.3.
- CHECKLIST_TASKS_DONE = filters.StatusUpdate.CHECKLIST_TASKS_DONE[source]¶
Messages that contain
telegram.Message.checklist_tasks_done.Added in version 22.3.
- CONNECTED_WEBSITE = filters.StatusUpdate.CONNECTED_WEBSITE[source]¶
Messages that contain
telegram.Message.connected_website.
- DIRECT_MESSAGE_PRICE_CHANGED = filters.StatusUpdate.DIRECT_MESSAGE_PRICE_CHANGED[source]¶
Messages that contain
telegram.Message.direct_message_price_changed.Added in version 22.3.
- DELETE_CHAT_PHOTO = filters.StatusUpdate.DELETE_CHAT_PHOTO[source]¶
Messages that contain
telegram.Message.delete_chat_photo.
- FORUM_TOPIC_CLOSED = filters.StatusUpdate.FORUM_TOPIC_CLOSED[source]¶
Messages that contain
telegram.Message.forum_topic_closed.Added in version 20.0.
- FORUM_TOPIC_CREATED = filters.StatusUpdate.FORUM_TOPIC_CREATED[source]¶
Messages that contain
telegram.Message.forum_topic_created.Added in version 20.0.
- FORUM_TOPIC_EDITED = filters.StatusUpdate.FORUM_TOPIC_EDITED[source]¶
Messages that contain
telegram.Message.forum_topic_edited.Added in version 20.0.
- FORUM_TOPIC_REOPENED = filters.StatusUpdate.FORUM_TOPIC_REOPENED[source]¶
Messages that contain
telegram.Message.forum_topic_reopened.Added in version 20.0.
- GENERAL_FORUM_TOPIC_HIDDEN = filters.StatusUpdate.GENERAL_FORUM_TOPIC_HIDDEN[source]¶
Messages that contain
telegram.Message.general_forum_topic_hidden.Added in version 20.0.
- GENERAL_FORUM_TOPIC_UNHIDDEN = filters.StatusUpdate.GENERAL_FORUM_TOPIC_UNHIDDEN[source]¶
Messages that contain
telegram.Message.general_forum_topic_unhidden.Added in version 20.0.
- GIFT = filters.StatusUpdate.GIFT[source]¶
Messages that contain
telegram.Message.gift.Added in version 22.1.
- GIVEAWAY_CREATED = filters.StatusUpdate.GIVEAWAY_CREATED[source]¶
Messages that contain
telegram.Message.giveaway_created.Added in version 20.8.
- GIVEAWAY_COMPLETED = filters.StatusUpdate.GIVEAWAY_COMPLETED[source]¶
Messages that contain
telegram.Message.giveaway_completed. .. versionadded:: 20.8
- LEFT_CHAT_MEMBER = filters.StatusUpdate.LEFT_CHAT_MEMBER[source]¶
Messages that contain
telegram.Message.left_chat_member.
- MESSAGE_AUTO_DELETE_TIMER_CHANGED = filters.StatusUpdate.MESSAGE_AUTO_DELETE_TIMER_CHANGED[source]¶
Messages that contain
telegram.Message.message_auto_delete_timer_changedAdded in version 13.4.
- MIGRATE = filters.StatusUpdate.MIGRATE[source]¶
Messages that contain
telegram.Message.migrate_from_chat_idortelegram.Message.migrate_to_chat_id.
- NEW_CHAT_MEMBERS = filters.StatusUpdate.NEW_CHAT_MEMBERS[source]¶
Messages that contain
telegram.Message.new_chat_members.
- NEW_CHAT_PHOTO = filters.StatusUpdate.NEW_CHAT_PHOTO[source]¶
Messages that contain
telegram.Message.new_chat_photo.
- NEW_CHAT_TITLE = filters.StatusUpdate.NEW_CHAT_TITLE[source]¶
Messages that contain
telegram.Message.new_chat_title.
- PAID_MESSAGE_PRICE_CHANGED = filters.StatusUpdate.PAID_MESSAGE_PRICE_CHANGED[source]¶
Messages that contain
telegram.Message.paid_message_price_changed.Added in version 22.1.
- PINNED_MESSAGE = filters.StatusUpdate.PINNED_MESSAGE[source]¶
Messages that contain
telegram.Message.pinned_message.
- PROXIMITY_ALERT_TRIGGERED = filters.StatusUpdate.PROXIMITY_ALERT_TRIGGERED[source]¶
Messages that contain
telegram.Message.proximity_alert_triggered.
- REFUNDED_PAYMENT = filters.StatusUpdate.REFUNDED_PAYMENT[source]¶
Messages that contain
telegram.Message.refunded_payment. .. versionadded:: 21.4
- SUGGESTED_POST_APPROVAL_FAILED = filters.StatusUpdate.SUGGESTED_POST_APPROVAL_FAILED[source]¶
Messages that contain
telegram.Message.suggested_post_approval_failed. .. versionadded:: 22.4
- SUGGESTED_POST_APPROVED = filters.StatusUpdate.SUGGESTED_POST_APPROVED[source]¶
Messages that contain
telegram.Message.suggested_post_approved. .. versionadded:: 22.4
- SUGGESTED_POST_DECLINED = filters.StatusUpdate.SUGGESTED_POST_DECLINED[source]¶
Messages that contain
telegram.Message.suggested_post_declined. .. versionadded:: 22.4
- SUGGESTED_POST_PAID = filters.StatusUpdate.SUGGESTED_POST_PAID[source]¶
Messages that contain
telegram.Message.suggested_post_paid. .. versionadded:: 22.4
- SUGGESTED_POST_REFUNDED = filters.StatusUpdate.SUGGESTED_POST_REFUNDED[source]¶
Messages that contain
telegram.Message.suggested_post_refunded. .. versionadded:: 22.4
- UNIQUE_GIFT = filters.StatusUpdate.UNIQUE_GIFT[source]¶
Messages that contain
telegram.Message.unique_gift.Added in version 22.1.
- USERS_SHARED = filters.StatusUpdate.USERS_SHARED[source]¶
Messages that contain
telegram.Message.users_shared.Added in version 20.8.
- VIDEO_CHAT_ENDED = filters.StatusUpdate.VIDEO_CHAT_ENDED[source]¶
Messages that contain
telegram.Message.video_chat_ended.Added in version 13.4.
Changed in version 20.0: This filter was formerly named
VOICE_CHAT_ENDED
- VIDEO_CHAT_SCHEDULED = filters.StatusUpdate.VIDEO_CHAT_SCHEDULED[source]¶
Messages that contain
telegram.Message.video_chat_scheduled.Added in version 13.5.
Changed in version 20.0: This filter was formerly named
VOICE_CHAT_SCHEDULED
- VIDEO_CHAT_STARTED = filters.StatusUpdate.VIDEO_CHAT_STARTED[source]¶
Messages that contain
telegram.Message.video_chat_started.Added in version 13.4.
Changed in version 20.0: This filter was formerly named
VOICE_CHAT_STARTED
- VIDEO_CHAT_PARTICIPANTS_INVITED = filters.StatusUpdate.VIDEO_CHAT_PARTICIPANTS_INVITED[source]¶
Messages that contain
telegram.Message.video_chat_participants_invited.Added in version 13.4.
Changed in version 20.0: This filter was formerly named
VOICE_CHAT_PARTICIPANTS_INVITED
- WEB_APP_DATA = filters.StatusUpdate.WEB_APP_DATA[source]¶
Messages that contain
telegram.Message.web_app_data.Added in version 20.0.
- WRITE_ACCESS_ALLOWED = filters.StatusUpdate.WRITE_ACCESS_ALLOWED[source]¶
Messages that contain
telegram.Message.write_access_allowed.Added in version 20.0.
- class telegram.ext.filters.Sticker[source]¶
Bases:
objectFilters messages which contain a sticker.
Examples
Use this filter like:
filters.Sticker.VIDEO. Or, just usefilters.Sticker.ALLfor any type of sticker.Caution
filters.Stickeritself is not a filter, but just a convenience namespace.- ALL = filters.Sticker.ALL[source]¶
Messages that contain
telegram.Message.sticker.
- ANIMATED = filters.Sticker.ANIMATED[source]¶
Messages that contain
telegram.Message.stickerandis animated.Added in version 20.0.
- STATIC = filters.Sticker.STATIC[source]¶
Messages that contain
telegram.Message.stickerand is a static sticker, i.e. does not containtelegram.Sticker.is_animatedortelegram.Sticker.is_video.Added in version 20.0.
- VIDEO = filters.Sticker.VIDEO[source]¶
Messages that contain
telegram.Message.stickerand is avideo sticker.Added in version 20.0.
- PREMIUM = filters.Sticker.PREMIUM[source]¶
Messages that contain
telegram.Message.stickerand have apremium animation.Added in version 20.0.
- class telegram.ext.filters.SuccessfulPayment(invoice_payloads=None)[source]¶
Bases:
telegram.ext.filters.MessageFilterSuccessful Payment Messages. If a list of invoice payloads is passed, it filters messages to only allow those whose invoice_payload is appearing in the given list.
Examples
MessageHandler(filters.SuccessfulPayment([‘Custom-Payload’]), callback_method)
- Parameters:
invoice_payloads (list[
str] | tuple[str], optional) – Which invoice payloads to allow. Only exact matches are allowed. If not specified, will allow any invoice payload.
Added in version 20.8.
- class telegram.ext.filters.Text(strings=None)[source]¶
Bases:
telegram.ext.filters.MessageFilterText Messages. If a list of strings is passed, it filters messages to only allow those whose text is appearing in the given list.
Examples
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)
See also
Note
Dice messages don’t have text. If you want to filter either text or dice messages, use
filters.TEXT | filters.Dice.ALL.Messages containing a command are accepted by this filter. Use
filters.TEXT & (~filters.COMMAND), if you want to filter only text messages without commands.
- class telegram.ext.filters.UpdateFilter(name=None, data_filter=False)[source]¶
Bases:
telegram.ext.filters.BaseFilterBase class for all Update Filters. In contrast to
MessageFilter, the object passed tofilter()is an instance oftelegram.Update, which allows to create filters liketelegram.ext.filters.UpdateType.EDITED_MESSAGE.Please see
telegram.ext.filters.BaseFilterfor details on how to create custom filters.Available In
- class telegram.ext.filters.UpdateType[source]¶
Bases:
objectSubset for filtering the type of update.
Examples
Use these filters like:
filters.UpdateType.MESSAGEorfilters.UpdateType.CHANNEL_POSTSetc.Caution
filters.UpdateTypeitself is not a filter, but just a convenience namespace.- CHANNEL_POST = filters.UpdateType.CHANNEL_POST[source]¶
Updates with
telegram.Update.channel_post.
- CHANNEL_POSTS = filters.UpdateType.CHANNEL_POSTS[source]¶
Updates with either
telegram.Update.channel_postortelegram.Update.edited_channel_post.
- EDITED = filters.UpdateType.EDITED[source]¶
Updates with
telegram.Update.edited_message,telegram.Update.edited_channel_post, ortelegram.Update.edited_business_message.Added in version 20.0.
Changed in version 21.1: Added
telegram.Update.edited_business_messageto the filter.
- EDITED_CHANNEL_POST = filters.UpdateType.EDITED_CHANNEL_POST[source]¶
Updates with
telegram.Update.edited_channel_post.
- EDITED_MESSAGE = filters.UpdateType.EDITED_MESSAGE[source]¶
Updates with
telegram.Update.edited_message.
- MESSAGE = filters.UpdateType.MESSAGE[source]¶
Updates with
telegram.Update.message.
- MESSAGES = filters.UpdateType.MESSAGES[source]¶
Updates with either
telegram.Update.messageortelegram.Update.edited_message.
- BUSINESS_MESSAGE = filters.UpdateType.BUSINESS_MESSAGE[source]¶
Updates with
telegram.Update.business_message.Added in version 21.1.
- EDITED_BUSINESS_MESSAGE = filters.UpdateType.EDITED_BUSINESS_MESSAGE[source]¶
Updates with
telegram.Update.edited_business_message.Added in version 21.1.
- BUSINESS_MESSAGES = filters.UpdateType.BUSINESS_MESSAGES[source]¶
Updates with either
telegram.Update.business_messageortelegram.Update.edited_business_message.Added in version 21.1.
- class telegram.ext.filters.User(user_id=None, username=None, allow_empty=False)[source]¶
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)- Parameters:
user_id (
int| Collection[int], optional) – Which user ID(s) to allow through.username (
str| Collection[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_idandusernameare both present.
- allow_empty[source]¶
Whether updates should be processed, if no user is specified in
user_idsandusernames.- Type:
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernameswill give a copy of the saved usernames asfrozenset. This is to ensure thread safety. To add/remove a user, you should useadd_usernames(), andremove_usernames(). Only update the entire set byfilter.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.- Returns:
frozenset(
str)
- property user_ids[source]¶
Which user ID(s) to allow through.
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_user_ids(), andremove_user_ids(). Only update the entire set byfilter.user_ids = 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.- Returns:
frozenset(
int)
- class telegram.ext.filters.ViaBot(bot_id=None, username=None, allow_empty=False)[source]¶
Bases:
telegram.ext.filters.MessageFilterFilters messages to allow only those which are from specified via_bot ID(s) or username(s).
Examples
MessageHandler(filters.ViaBot(1234), callback_method)See also
- Parameters:
bot_id (
int| Collection[int], optional) – Which bot ID(s) to allow through.username (
str| Collection[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_idandusernameare both present.
- allow_empty[source]¶
Whether updates should be processed, if no bot is specified in
bot_idsandusernames.- Type:
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernameswill give a copy of the saved usernames asfrozenset. This is to ensure thread safety. To add/remove a user, you should useadd_usernames(), andremove_usernames(). Only update the entire set byfilter.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.- Returns:
frozenset(
str)
- property bot_ids[source]¶
Which bot ID(s) to allow through.
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_bot_ids(), andremove_bot_ids(). Only update the entire set byfilter.bot_ids = 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.- Returns:
frozenset(
int)