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
Filters
class. The filters are now directly attributes/classes of thefilters
module.The names of all filters has been updated:
Filter classes which are ready for use, e.g
Filters.all
are 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.TEXT
and class versionfilters.Text(...)
.
- 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.CHAT = filters.CHAT[source]¶
This filter filters any message that has a
telegram.Message.chat
.Deprecated since version 20.8: This filter has no effect since
telegram.Message.chat
is always present.
- 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.EFFECT_ID = filters.EFFECT_ID[source]¶
Messages that contain
telegram.Message.effect_id
.Added in version 21.3.
- 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_origin
instead 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 user
astelegram.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.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 menu
astelegram.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:
object
Base 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
,or
andnot
. 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
MessageFilter
orUpdateFilter
and implement afilter()
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.Available In
Added in version 20.0: Added the arguments
name
anddata_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
BaseFilter
object. The combined filter accepts an update only if it is accepted by both filters. For example,filters.PHOTO & filters.CAPTION
will only accept messages that contain both a photo and a caption.- Returns:
- __or__(other)[source]¶
Defines OR bitwise operator for
BaseFilter
object. The combined filter accepts an update only if it is accepted by any of the filters. For example,filters.PHOTO | filters.CAPTION
will only accept messages that contain photo or caption or both.- Returns:
- __xor__(other)[source]¶
Defines XOR bitwise operator for
BaseFilter
object. 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.CAPTION
will only accept messages that contain photo or caption, not both of them.- Returns:
- __invert__()[source]¶
Defines NOT bitwise operator for
BaseFilter
object. The combined filter accepts an update only if it is accepted by any of the filters. For example,~ filters.PHOTO
will 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
True
if the update containsbusiness_message
oredited_business_message
.- Parameters:
update (
telegram.Update
) – The update to check.- Returns:
True
if the update contains one ofchannel_post
,message
,edited_channel_post
,edited_message
,telegram.Update.business_message
,telegram.Update.edited_business_message
, orFalse
otherwise.- Return type:
- class telegram.ext.filters.Caption(strings=None)[source]¶
Bases:
telegram.ext.filters.MessageFilter
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(['PTB rocks!', 'PTB']), callback_method_2)
See also
- class telegram.ext.filters.CaptionEntity(entity_type)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Filters media messages to only allow those which have a
telegram.MessageEntity
where theirtype
matches 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.MessageFilter
Filters updates by searching for an occurrence of
pattern
in 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.MessageFilter
Filters messages to allow only those which are from a specified chat ID or username.
Examples
MessageHandler(filters.Chat(-1234), callback_method)
Warning
chat_ids
will 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_ids
andusernames
. Defaults toFalse
.
- allow_empty[source]¶
Whether updates should be processed, if no chat is specified in
chat_ids
andusernames
.- Type:
- Raises:
RuntimeError – If
chat_id
andusername
are both present.
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernames
will 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:
object
Subset for filtering the type of chat.
Examples
Use these filters like:
filters.ChatType.CHANNEL
orfilters.ChatType.SUPERGROUP
etc.Caution
filters.ChatType
itself is not a filter, but just a convenience namespace.
- class telegram.ext.filters.Command(only_start=True)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Messages with a
telegram.MessageEntity.BOT_COMMAND
. By default, only allows messages starting with a bot command. PassFalse
to 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.TEXT
also 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.MessageFilter
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.
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.MessageFilter
Dice 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.MessageFilter
Dice messages with the emoji 🎳. Supports passing a list of integers.
- class Darts(values)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Dice messages with the emoji 🎯. Supports passing a list of integers.
- class Dice(values)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Dice messages with the emoji 🎲. Supports passing a list of integers.
- class Football(values)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Dice messages with the emoji ⚽. Supports passing a list of integers.
- class SlotMachine(values)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Dice messages with the emoji 🎰. Supports passing a list of integers.
- class telegram.ext.filters.Document[source]¶
Bases:
object
Subset for messages containing a document/file.
Examples
Use these filters like:
filters.Document.MP3
,filters.Document.MimeType("text/plain")
etc. Or just usefilters.Document.ALL
for all document messages.Caution
filters.Document
itself 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.MessageFilter
Filters documents by their category in the mime-type attribute.
Example
filters.Document.Category('audio/')
returnsTrue
for 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.MessageFilter
This filter filters documents by their file ending/extension.
- Parameters:
file_extension (
str
|None
) – Media file extension you want to filter.case_sensitive (
bool
, optional) – PassTrue
to 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
None
to filter files with no extension, i.e. without a dot in the filename.
- class MimeType(mimetype)[source]¶
Bases:
telegram.ext.filters.MessageFilter
This 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.MessageFilter
Filters messages to only allow those which have a
telegram.MessageEntity
where theirtype
matches 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.MessageFilter
Filters messages to allow only those which are forwarded from the specified chat ID(s) or username(s) based on
telegram.Message.forward_origin
and in particularAdded in version 13.5.
Changed in version 20.8: Was previously based on
telegram.Message.forward_from
andtelegram.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_origin
will be of typetelegram.MessageOriginHiddenUser
. However, this behaviour is undocumented and might be changed by Telegram.Warning
chat_ids
will 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_ids
andusernames
. Defaults toFalse
.
- allow_empty[source]¶
Whether updates should be processed, if no chat is specified in
chat_ids
andusernames
.- Type:
- Raises:
RuntimeError – If both
chat_id
andusername
are present.
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernames
will 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.MessageFilter
Filters 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.startswith
meaning that ‘en’ will match both ‘en_US’ and ‘en_GB’.
- class telegram.ext.filters.Mention(mentions)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Messages 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.BaseFilter
Base class for all Message Filters. In contrast to
UpdateFilter
, the object passed tofilter()
istelegram.Update.effective_message
.Please see
BaseFilter
for details on how to create custom filters.Available In
See also
- check_update(update)[source]¶
Checks if the specified update should be handled by this filter by passing
effective_message
tofilter()
.
- class telegram.ext.filters.Regex(pattern)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Filters updates by searching for an occurrence of
pattern
in the message text. There.search()
function is used to determine whether an update should be filtered.Refer to the documentation of the
re
module 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
andnot
. This means that for example:>>> filters.Regex(r'(a?x)') | filters.Regex(r'(b?x)')
With a
telegram.Message.text
of 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.MessageFilter
Filters 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_chat
is 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_forward
will beTrue
for the discussion group message.Warning
chat_ids
will 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_ids
andusernames
. Defaults toFalse
.
- allow_empty[source]¶
Whether updates should be processed, if no sender chat is specified in
chat_ids
andusernames
.- Type:
- Raises:
RuntimeError – If both
chat_id
andusername
are present.
- ALL = filters.SenderChat.ALL[source]¶
All messages with a
telegram.Message.sender_chat
.
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernames
will 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:
object
Subset for messages containing a status update.
Examples
Use these filters like:
filters.StatusUpdate.NEW_CHAT_MEMBERS
etc. Or use justfilters.StatusUpdate.ALL
for all status update messages.Caution
filters.StatusUpdate
itself is not a filter, but just a convenience namespace.- 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_created
ortelegram.Message.channel_chat_created
.
- CHAT_SHARED = filters.StatusUpdate.CHAT_SHARED[source]¶
Messages that contain
telegram.Message.chat_shared
.Added in version 20.1.
- CONNECTED_WEBSITE = filters.StatusUpdate.CONNECTED_WEBSITE[source]¶
Messages that contain
telegram.Message.connected_website
.
- 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.
- 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_changed
Added in version 13.4.
- MIGRATE = filters.StatusUpdate.MIGRATE[source]¶
Messages that contain
telegram.Message.migrate_from_chat_id
ortelegram.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
.
- 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
- USER_SHARED = filters.StatusUpdate.USER_SHARED[source]¶
Messages that contain
"user_shared"
intelegram.TelegramObject.api_kwargs
.Warning
This will only catch the legacy
user_shared
field, not the newtelegram.Message.users_shared
attribute!Changed in version 21.0: Now relies on
telegram.TelegramObject.api_kwargs
as the native attributeMessage.user_shared
was removed.Added in version 20.1.
Deprecated since version 20.8: Use
USERS_SHARED
instead.
- 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:
object
Filters messages which contain a sticker.
Examples
Use this filter like:
filters.Sticker.VIDEO
. Or, just usefilters.Sticker.ALL
for any type of sticker.Caution
filters.Sticker
itself 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.sticker
andis animated
.Added in version 20.0.
- STATIC = filters.Sticker.STATIC[source]¶
Messages that contain
telegram.Message.sticker
and is a static sticker, i.e. does not containtelegram.Sticker.is_animated
ortelegram.Sticker.is_video
.Added in version 20.0.
- VIDEO = filters.Sticker.VIDEO[source]¶
Messages that contain
telegram.Message.sticker
and is avideo sticker
.Added in version 20.0.
- PREMIUM = filters.Sticker.PREMIUM[source]¶
Messages that contain
telegram.Message.sticker
and have apremium animation
.Added in version 20.0.
- class telegram.ext.filters.SuccessfulPayment(invoice_payloads=None)[source]¶
Bases:
telegram.ext.filters.MessageFilter
Successful 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.MessageFilter
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
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.BaseFilter
Base 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.BaseFilter
for details on how to create custom filters.Available In
- class telegram.ext.filters.UpdateType[source]¶
Bases:
object
Subset for filtering the type of update.
Examples
Use these filters like:
filters.UpdateType.MESSAGE
orfilters.UpdateType.CHANNEL_POSTS
etc.Caution
filters.UpdateType
itself 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_post
ortelegram.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_message
to 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.message
ortelegram.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_message
ortelegram.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.MessageFilter
Filters 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_ids
andusernames
. Defaults toFalse
.
- Raises:
RuntimeError – If
user_id
andusername
are both present.
- allow_empty[source]¶
Whether updates should be processed, if no user is specified in
user_ids
andusernames
.- Type:
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernames
will 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_ids
will 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.MessageFilter
Filters 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_ids
andusernames
. Defaults toFalse
.
- Raises:
RuntimeError – If
bot_id
andusername
are both present.
- allow_empty[source]¶
Whether updates should be processed, if no bot is specified in
bot_ids
andusernames
.- Type:
- property usernames[source]¶
Which username(s) to allow through.
Warning
usernames
will 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_ids
will 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
)