telegram.ext.filters Module

This module contains filters for use with telegram.ext.MessageHandler, telegram.ext.CommandHandler, or telegram.ext.PrefixHandler.

Changed in version 20.0:

  1. 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).

  2. Removed the Filters class. The filters are now directly attributes/classes of the filters module.

  3. The names of all filters has been updated:

    • Filter classes which are ready for use, e.g Filters.all are now capitalized, e.g filters.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 version filters.TEXT and class version filters.Text(...).

telegram.ext.filters.ALL = filters.ALL[source]

All Messages.

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().

New in version 13.6.

telegram.ext.filters.AUDIO = filters.AUDIO[source]

Messages that contain telegram.Message.audio.

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 and not. This means that for example:

filters.Regex(r'(a?x)') | filters.Regex(r'(b?x)')

With message.text == 'x', will only ever return the matches for the first filter, since the second one is never evaluated.

If you want to create your own filters create a class inheriting from either MessageFilter or UpdateFilter 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.

New in version 20.0: Added the arguments name and data_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 with telegram.ext.CallbackContext’s internal dict in most cases (depends on the handler).

name[source]

Name for this filter.

Type

str

data_filter[source]

Whether this filter is a data filter.

Type

bool

check_update(update)[source]

Checks if the specified update is a message.

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.

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.

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)

Parameters

strings (List[str] | Tuple[str], optional) – Which captions to allow. Only exact matches are allowed. If not specified, will allow any message with a caption.

class 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 their type 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 in telegram.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 as frozenset. This is to ensure thread safety. To add/remove a chat, you should use add_chat_ids(), and remove_chat_ids(). Only update the entire set by filter.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 in chat_ids and usernames. Defaults to False.

chat_ids[source]

Which chat ID(s) to allow through.

Type

set(int)

allow_empty[source]

Whether updates should be processed, if no chat is specified in chat_ids and usernames.

Type

bool

Raises

RuntimeError – If chat_id and username are both present.

add_chat_ids(chat_id)[source]

Add one or more chats to the allowed chat ids.

Parameters

chat_id (int | Collection[int]) – Which chat ID(s) to allow through.

remove_chat_ids(chat_id)[source]

Remove one or more chats from allowed chat ids.

Parameters

chat_id (int | Collection[int]) – Which chat ID(s) to disallow through.

add_usernames(username)[source]

Add one or more chats to the allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to allow through. Leading '@' s in usernames will be discarded.

remove_usernames(username)[source]

Remove one or more chats from allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to disallow through. Leading '@' s in usernames will be discarded.

property usernames[source]

Which username(s) to allow through.

Warning

usernames will give a copy of the saved usernames as frozenset. This is to ensure thread safety. To add/remove a user, you should use add_usernames(), and remove_usernames(). Only update the entire set by filter.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 or filters.ChatType.SUPERGROUP etc.

Caution

filters.ChatType itself is not a filter, but just a convenience namespace.

CHANNEL = filters.ChatType.CHANNEL[source]

Updates from channel.

GROUP = filters.ChatType.GROUP[source]

Updates from group.

GROUPS = filters.ChatType.GROUPS[source]

Update from group or supergroup.

PRIVATE = filters.ChatType.PRIVATE[source]

Update from private chats.

SUPERGROUP = filters.ChatType.SUPERGROUP[source]

Updates from supergroup.

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. Pass False to also allow messages that contain a bot command anywhere in the text.

Examples

MessageHandler(filters.Command(False), command_anywhere_callback)

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 to True.

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.

New 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.

ALL = filters.Dice.ALL[source]

Dice messages with any value and any emoji.

class Basketball(values)[source]

Bases: telegram.ext.filters.MessageFilter

Dice messages with the emoji 🏀. Supports passing a list of integers.

Parameters

values (int | Collection[int]) – Which values to allow.

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.

Parameters

values (int | Collection[int]) – Which values to allow.

BOWLING = filters.Dice.BOWLING[source]

Dice messages with the emoji 🎳. Matches any dice value.

class Darts(values)[source]

Bases: telegram.ext.filters.MessageFilter

Dice messages with the emoji 🎯. Supports passing a list of integers.

Parameters

values (int | Collection[int]) – Which values to allow.

DARTS = filters.Dice.DARTS[source]

Dice messages with the emoji 🎯. Matches any dice value.

class Dice(values)[source]

Bases: telegram.ext.filters.MessageFilter

Dice messages with the emoji 🎲. Supports passing a list of integers.

Parameters

values (int | Collection[int]) – Which values to allow.

DICE = filters.Dice.DICE[source]

Dice messages with the emoji 🎲. Matches any dice value.

class Football(values)[source]

Bases: telegram.ext.filters.MessageFilter

Dice messages with the emoji ⚽. Supports passing a list of integers.

Parameters

values (int | Collection[int]) – Which values to allow.

FOOTBALL = filters.Dice.FOOTBALL[source]

Dice messages with the emoji ⚽. Matches any dice value.

class SlotMachine(values)[source]

Bases: telegram.ext.filters.MessageFilter

Dice messages with the emoji 🎰. Supports passing a list of integers.

Parameters

values (int | Collection[int]) – Which values to allow.

SLOT_MACHINE = filters.Dice.SLOT_MACHINE[source]

Dice messages with the emoji 🎰. Matches any dice value.

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 use filters.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.

Parameters

category (str) – Category of the media you want to filter.

Example

filters.Document.Category('audio/') returns True 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.

AUDIO = filters.Document.Category('audio/')[source]

Use as filters.Document.AUDIO.

IMAGE = filters.Document.Category('image/')[source]

Use as filters.Document.IMAGE.

VIDEO = filters.Document.Category('video/')[source]

Use as filters.Document.VIDEO.

TEXT = filters.Document.Category('text/')[source]

Use as filters.Document.TEXT.

class FileExtension(file_extension, case_sensitive=False)[source]

Bases: telegram.ext.filters.MessageFilter

This filter filters documents by their file ending/extension.

Parameters

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.

Parameters

mimetype (str) – The mimetype to filter.

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.

DOC = filters.Document.MimeType('application/msword')[source]

Use as filters.Document.DOC.

DOCX = filters.Document.MimeType('application/vnd.openxmlformats-officedocument.wordprocessingml.document')[source]

Use as filters.Document.DOCX.

EXE = filters.Document.MimeType('application/octet-stream')[source]

Use as filters.Document.EXE.

MP4 = filters.Document.MimeType('video/mp4')[source]

Use as filters.Document.MP4.

GIF = filters.Document.MimeType('image/gif')[source]

Use as filters.Document.GIF.

JPG = filters.Document.MimeType('image/jpeg')[source]

Use as filters.Document.JPG.

MP3 = filters.Document.MimeType('audio/mpeg')[source]

Use as filters.Document.MP3.

PDF = filters.Document.MimeType('application/pdf')[source]

Use as filters.Document.PDF.

PY = filters.Document.MimeType('text/x-python')[source]

Use as filters.Document.PY.

SVG = filters.Document.MimeType('image/svg+xml')[source]

Use as filters.Document.SVG.

TXT = filters.Document.MimeType('text/plain')[source]

Use as filters.Document.TXT.

TARGZ = filters.Document.MimeType('application/x-compressed-tar')[source]

Use as filters.Document.TARGZ.

WAV = filters.Document.MimeType('audio/x-wav')[source]

Use as filters.Document.WAV.

XML = filters.Document.MimeType('text/xml')[source]

Use as filters.Document.XML.

ZIP = filters.Document.MimeType('application/zip')[source]

Use as filters.Document.ZIP.

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 their type 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 in telegram.MessageEntity.

telegram.ext.filters.FORWARDED = filters.FORWARDED[source]

Messages that contain telegram.Message.forward_date.

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_from and telegram.Message.forward_from_chat.

New in version 13.5.

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 both telegram.Message.forward_from and telegram.Message.forward_from_chat are None. However, this behaviour is undocumented and might be changed by Telegram.

Warning

chat_ids will give a copy of the saved chat ids as frozenset. This is to ensure thread safety. To add/remove a chat, you should use add_chat_ids(), and remove_chat_ids(). Only update the entire set by filter.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 in chat_ids and usernames. Defaults to False.

chat_ids[source]

Which chat/user ID(s) to allow through.

Type

set(int)

allow_empty[source]

Whether updates should be processed, if no chat is specified in chat_ids and usernames.

Type

bool

Raises

RuntimeError – If both chat_id and username are present.

add_chat_ids(chat_id)[source]

Add one or more chats to the allowed chat ids.

Parameters

chat_id (int | Collection[int]) – Which chat/user ID(s) to allow through.

remove_chat_ids(chat_id)[source]

Remove one or more chats from allowed chat ids.

Parameters

chat_id (int | Collection[int]) – Which chat/user ID(s) to disallow through.

add_usernames(username)[source]

Add one or more chats to the allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to allow through. Leading '@' s in usernames will be discarded.

remove_usernames(username)[source]

Remove one or more chats from allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to disallow through. Leading '@' s in usernames will be discarded.

property usernames[source]

Which username(s) to allow through.

Warning

usernames will give a copy of the saved usernames as frozenset. This is to ensure thread safety. To add/remove a user, you should use add_usernames(), and remove_usernames(). Only update the entire set by filter.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)

telegram.ext.filters.GAME = filters.GAME[source]

Messages that contain telegram.Message.game.

telegram.ext.filters.HAS_PROTECTED_CONTENT = filters.HAS_PROTECTED_CONTENT[source]

Messages that contain telegram.Message.has_protected_content.

New 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.

New in version 13.9.

telegram.ext.filters.LOCATION = filters.LOCATION[source]

Messages that contain telegram.Message.location.

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 using str.startswith meaning that ‘en’ will match both ‘en_US’ and ‘en_GB’.

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 to filter() is telegram.Update.effective_message.

Please see BaseFilter for details on how to create custom filters.

name[source]

Name for this filter. Defaults to the type of filter.

Type

str

data_filter[source]

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

check_update(update)[source]

Checks if the specified update is a message.

abstract filter(message)[source]

This method must be overwritten.

Parameters

message (telegram.Message) – The message that is tested.

Returns

dict or bool

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.REPLY = filters.REPLY[source]

Messages that contain telegram.Message.reply_to_message.

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. The re.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 use MessageHandler(filters.Regex(re.compile(r'help', re.IGNORECASE)), callback) if you want your pattern to be case insensitive. This approach is recommended if you need to specify flags on your pattern.

Note

Filters use the same short circuiting logic as python’s and, or and not. This means that for example:

>>> filters.Regex(r'(a?x)') | filters.Regex(r'(b?x)')

With a telegram.Message.text of x, will only ever return the matches for the first filter, since the second one is never evaluated.

Parameters

pattern (str | re.Pattern) – The regex pattern.

class telegram.ext.filters.Sticker[source]

Bases: object

Filters messages which contain a sticker.

Examples

Use this filter like: filters.Sticker.VIDEO. Or, just use filters.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 and is animated.

New in version 20.0.

STATIC = filters.Sticker.STATIC[source]

Messages that contain telegram.Message.sticker and is a static sticker, i.e. does not contain telegram.Sticker.is_animated or telegram.Sticker.is_video.

New in version 20.0.

VIDEO = filters.Sticker.VIDEO[source]

Messages that contain telegram.Message.sticker and is a video sticker.

New in version 20.0.

telegram.ext.filters.SUCCESSFUL_PAYMENT = filters.SUCCESSFUL_PAYMENT[source]

Messages that contain telegram.Message.successful_payment.

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, use MessageHandler(filters.SenderChat(-1234), callback_method).

  • To filter for messages of anonymous admins in a super group with username @anonymous, use MessageHandler(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 field telegram.Message.is_automatic_forward will be True for the discussion group message.

Warning

chat_ids will return a copy of the saved chat ids as frozenset. This is to ensure thread safety. To add/remove a chat, you should use add_chat_ids(), and remove_chat_ids(). Only update the entire set by filter.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 in chat_ids and usernames. Defaults to False.

chat_ids[source]

Which sender chat chat ID(s) to allow through.

Type

set(int)

allow_empty[source]

Whether updates should be processed, if no sender chat is specified in chat_ids and usernames.

Type

bool

Raises

RuntimeError – If both chat_id and username are present.

ALL = filters.SenderChat.ALL[source]

All messages with a telegram.Message.sender_chat.

SUPER_GROUP = filters.SenderChat.SUPER_GROUP[source]

Messages whose sender chat is a super group.

CHANNEL = filters.SenderChat.CHANNEL[source]

Messages whose sender chat is a channel.

add_chat_ids(chat_id)[source]

Add one or more sender chats to the allowed chat ids.

Parameters

chat_id (int | Collection[int]) – Which sender chat ID(s) to allow through.

remove_chat_ids(chat_id)[source]

Remove one or more sender chats from allowed chat ids.

Parameters

chat_id (int | Collection[int]) – Which sender chat ID(s) to disallow through.

add_usernames(username)[source]

Add one or more chats to the allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to allow through. Leading '@' s in usernames will be discarded.

remove_usernames(username)[source]

Remove one or more chats from allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to disallow through. Leading '@' s in usernames will be discarded.

property usernames[source]

Which username(s) to allow through.

Warning

usernames will give a copy of the saved usernames as frozenset. This is to ensure thread safety. To add/remove a user, you should use add_usernames(), and remove_usernames(). Only update the entire set by filter.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 just filters.StatusUpdate.ALL for all status update messages.

Caution

filters.StatusUpdate itself is not a filter, but just a convenience namespace.

ALL = filters.StatusUpdate.ALL[source]

Messages that contain any of the below.

CHAT_CREATED = filters.StatusUpdate.CHAT_CREATED[source]

Messages that contain telegram.Message.group_chat_created, telegram.Message.supergroup_chat_created or telegram.Message.channel_chat_created.

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.

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

New in version 13.4.

MIGRATE = filters.StatusUpdate.MIGRATE[source]

Messages that contain telegram.Message.migrate_from_chat_id or telegram.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.

VIDEO_CHAT_ENDED = filters.StatusUpdate.VIDEO_CHAT_ENDED[source]

Messages that contain telegram.Message.video_chat_ended.

New 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.

New 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.

New 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.

New 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.

New in version 20.0.

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).

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)

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.

Parameters

strings (List[str] | Tuple[str], optional) – Which messages to allow. Only exact matches are allowed. If not specified, will allow any text message.

telegram.ext.filters.USER = filters.USER[source]

This filter filters any message that has a telegram.Message.from_user.

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 to filter() is an instance of telegram.Update, which allows to create filters like telegram.ext.filters.UpdateType.EDITED_MESSAGE.

Please see telegram.ext.filters.BaseFilter for details on how to create custom filters.

name[source]

Name for this filter. Defaults to the type of filter.

Type

str

data_filter[source]

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

check_update(update)[source]

Checks if the specified update is a message.

abstract filter(update)[source]

This method must be overwritten.

Parameters

update (telegram.Update) – The update that is tested.

Returns

dict or bool.

class telegram.ext.filters.UpdateType[source]

Bases: object

Subset for filtering the type of update.

Examples

Use these filters like: filters.UpdateType.MESSAGE or filters.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 or telegram.Update.edited_channel_post.

EDITED = filters.UpdateType.EDITED[source]

Updates with either telegram.Update.edited_message or telegram.Update.edited_channel_post.

New in version 20.0.

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 or telegram.Update.edited_message.

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 in user_ids and usernames. Defaults to False.

Raises

RuntimeError – If user_id and username are both present.

allow_empty[source]

Whether updates should be processed, if no user is specified in user_ids and usernames.

Type

bool

add_usernames(username)[source]

Add one or more chats to the allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to allow through. Leading '@' s in usernames will be discarded.

remove_usernames(username)[source]

Remove one or more chats from allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to disallow through. Leading '@' s in usernames will be discarded.

property usernames[source]

Which username(s) to allow through.

Warning

usernames will give a copy of the saved usernames as frozenset. This is to ensure thread safety. To add/remove a user, you should use add_usernames(), and remove_usernames(). Only update the entire set by filter.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 as frozenset. This is to ensure thread safety. To add/remove a user, you should use add_user_ids(), and remove_user_ids(). Only update the entire set by filter.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)

add_user_ids(user_id)[source]

Add one or more users to the allowed user ids.

Parameters

user_id (int | Collection[int]) – Which user ID(s) to allow through.

remove_user_ids(user_id)[source]

Remove one or more users from allowed user ids.

Parameters

user_id (int | Collection[int]) – Which user ID(s) to disallow through.

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.

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.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)

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 in bot_ids and usernames. Defaults to False.

Raises

RuntimeError – If bot_id and username are both present.

allow_empty[source]

Whether updates should be processed, if no bot is specified in bot_ids and usernames.

Type

bool

add_usernames(username)[source]

Add one or more chats to the allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to allow through. Leading '@' s in usernames will be discarded.

remove_usernames(username)[source]

Remove one or more chats from allowed usernames.

Parameters

username (str | Collection[str]) – Which username(s) to disallow through. Leading '@' s in usernames will be discarded.

property usernames[source]

Which username(s) to allow through.

Warning

usernames will give a copy of the saved usernames as frozenset. This is to ensure thread safety. To add/remove a user, you should use add_usernames(), and remove_usernames(). Only update the entire set by filter.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 as frozenset. This is to ensure thread safety. To add/remove a bot, you should use add_bot_ids(), and remove_bot_ids(). Only update the entire set by filter.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)

add_bot_ids(bot_id)[source]

Add one or more bots to the allowed bot ids.

Parameters

bot_id (int | Collection[int]) – Which bot ID(s) to allow through.

remove_bot_ids(bot_id)[source]

Remove one or more bots from allowed bot ids.

Parameters

bot_id (int | Collection[int], optional) – Which bot ID(s) to disallow through.