Hide navigation sidebar
Hide table of contents sidebar
Skip to content
Back to top
View this page
Toggle table of contents sidebar

# 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

  All Messages.

telegram.ext.filters.ANIMATION = filters.ANIMATION

  Messages that contain `telegram.Message.animation`.

telegram.ext.filters.ATTACHMENT = filters.ATTACHMENT

  Messages that contain `telegram.Message.effective_attachment()`.

  Added in version 13.6.

telegram.ext.filters.AUDIO = filters.AUDIO

  Messages that contain `telegram.Message.audio`.

telegram.ext.filters.BOOST_ADDED = filters.BOOST_ADDED

  Messages that contain `telegram.Message.boost_added`.

telegram.ext.filters.CAPTION = filters.CAPTION

  Shortcut for `telegram.ext.filters.Caption()`.

  Examples

  To allow any caption, simply use `MessageHandler(filters.CAPTION, callback_method)`.

telegram.ext.filters.CHAT = filters.CHAT

  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

  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

  Messages that contain `telegram.Message.contact`.

telegram.ext.filters.EFFECT_ID = filters.EFFECT_ID

  Messages that contain `telegram.Message.effect_id`.

  Added in version 21.3.

telegram.ext.filters.FORWARDED = filters.FORWARDED

  Messages that contain `telegram.Message.forward_origin`.

  Changed in version 20.8: Now based on `telegram.Message.forward_origin` instead of `telegram.Message.forward_date`.

telegram.ext.filters.GAME = filters.GAME

  Messages that contain `telegram.Message.game`.

telegram.ext.filters.GIVEAWAY = filters.GIVEAWAY

  Messages that contain `telegram.Message.giveaway`.

telegram.ext.filters.GIVEAWAY_WINNERS = filters.GIVEAWAY_WINNERS

  Messages that contain `telegram.Message.giveaway_winners`.

telegram.ext.filters.HAS_MEDIA_SPOILER = filters.HAS_MEDIA_SPOILER

  Messages that contain `telegram.Message.has_media_spoiler`.

  Added in version 20.0.

telegram.ext.filters.HAS_PROTECTED_CONTENT = filters.HAS_PROTECTED_CONTENT

  Messages that contain `telegram.Message.has_protected_content`.

  Added in version 13.9.

telegram.ext.filters.INVOICE = filters.INVOICE

  Messages that contain `telegram.Message.invoice`.

telegram.ext.filters.IS_AUTOMATIC_FORWARD = filters.IS_AUTOMATIC_FORWARD

  Messages that contain `telegram.Message.is_automatic_forward`.

  Added in version 13.9.

telegram.ext.filters.IS_FROM_OFFLINE = filters.IS_FROM_OFFLINE

  Messages that contain `telegram.Message.is_from_offline`.

  Added in version 21.1.

telegram.ext.filters.IS_TOPIC_MESSAGE = filters.IS_TOPIC_MESSAGE

  Messages that contain `telegram.Message.is_topic_message`.

  Added in version 20.0.

telegram.ext.filters.LOCATION = filters.LOCATION

  Messages that contain `telegram.Message.location`.

telegram.ext.filters.PAID_MEDIA = filters.PAID_MEDIA

  Messages that contain `telegram.Message.paid_media`.

  Added in version 21.4.

telegram.ext.filters.PASSPORT_DATA = filters.PASSPORT_DATA

  Messages that contain `telegram.Message.passport_data`.

telegram.ext.filters.PHOTO = filters.PHOTO

  Messages that contain `telegram.Message.photo`.

telegram.ext.filters.POLL = filters.POLL

  Messages that contain `telegram.Message.poll`.

telegram.ext.filters.PREMIUM_USER = filters.PREMIUM_USER

  This filter filters any message from a `Telegram Premium user` as `telegram.Update.effective_user`.

  Added in version 20.0.

telegram.ext.filters.REPLY = filters.REPLY

  Messages that contain `telegram.Message.reply_to_message`.

telegram.ext.filters.REPLY_TO_STORY = filters.REPLY_TO_STORY

  Messages that contain `telegram.Message.reply_to_story`.

telegram.ext.filters.SENDER_BOOST_COUNT = filters.SENDER_BOOST_COUNT

  Messages that contain `telegram.Message.sender_boost_count`.

telegram.ext.filters.STORY = filters.STORY

  Messages that contain `telegram.Message.story`.

  Added in version 20.5.

telegram.ext.filters.SUCCESSFUL_PAYMENT = filters.SUCCESSFUL_PAYMENT

  Messages that contain `telegram.Message.successful_payment`.

telegram.ext.filters.TEXT = filters.TEXT

  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

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

telegram.ext.filters.USER_ATTACHMENT = filters.USER_ATTACHMENT

  This filter filters any message that have a user who added the bot to their `attachment menu` as `telegram.Update.effective_user`.

  Added in version 20.0.

telegram.ext.filters.VENUE = filters.VENUE

  Messages that contain `telegram.Message.venue`.

telegram.ext.filters.VIA_BOT = filters.VIA_BOT

  This filter filters for message that were sent via any bot.

  See also

  `ViaBot`

telegram.ext.filters.VIDEO = filters.VIDEO

  Messages that contain `telegram.Message.video`.

telegram.ext.filters.VIDEO_NOTE = filters.VIDEO_NOTE

  Messages that contain `telegram.Message.video_note`.

telegram.ext.filters.VOICE = filters.VOICE

  Messages that contain `telegram.Message.voice`.

class telegram.ext.filters.BaseFilter(name=None, data_filter=False)

  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.

  Available In

  - `telegram.ext.CommandHandler.filters`

  - `telegram.ext.MessageHandler.filters`

  - `telegram.ext.PrefixHandler.filters`

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

  __and__(other)

    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:

      `BaseFilter`

  __or__(other)

    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:

      `BaseFilter`

  __xor__(other)

    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:

      `BaseFilter`

  __invert__()

    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:

      `BaseFilter`

  __repr__()

    Gives name for this filter.

    See also

    `name()`

    Return type:

      `str`

  property data_filter

    Whether this filter is a data filter.

    Type:

      `bool`

  property name

    Name for this filter.

    Type:

      `str`

  check_update(update)

    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 contains `business_message` or `edited_business_message`.

    Parameters:

      update (`telegram.Update`) – The update to check.

    Returns:

      `True` if the update contains one of `channel_post`, `message`, `edited_channel_post`, `edited_message`, `telegram.Update.business_message`, `telegram.Update.edited_business_message`, or `False` otherwise.

    Return type:

      `bool`

class telegram.ext.filters.Caption(strings=None)

  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

  `telegram.ext.filters.CAPTION`

  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)

  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)

  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)

  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

    Which chat ID(s) to allow through.

    Type:

      set(`int`)

  allow_empty

    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)

    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)

    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)

    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.

  property name

    Name for this filter.

    Type:

      `str`

  remove_usernames(username)

    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

    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

  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

    Updates from channel.

  GROUP = filters.ChatType.GROUP

    Updates from group.

  GROUPS = filters.ChatType.GROUPS

    Update from group or supergroup.

  PRIVATE = filters.ChatType.PRIVATE

    Update from private chats.

  SUPERGROUP = filters.ChatType.SUPERGROUP

    Updates from supergroup.

class telegram.ext.filters.Command(only_start=True)

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

  See also

  `telegram.ext.filters.COMMAND`.

  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)

  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.

  ALL = filters.Dice.ALL

    Dice messages with any value and any emoji.

  class Basketball(values)

    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

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

  class Bowling(values)

    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

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

  class Darts(values)

    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

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

  class Dice(values)

    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

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

  class Football(values)

    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

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

  class SlotMachine(values)

    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

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

class telegram.ext.filters.Document

  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

    Messages that contain a `telegram.Message.document`.

  class Category(category)

    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/')

    Use as `filters.Document.APPLICATION`.

  AUDIO = filters.Document.Category('audio/')

    Use as `filters.Document.AUDIO`.

  IMAGE = filters.Document.Category('image/')

    Use as `filters.Document.IMAGE`.

  VIDEO = filters.Document.Category('video/')

    Use as `filters.Document.VIDEO`.

  TEXT = filters.Document.Category('text/')

    Use as `filters.Document.TEXT`.

  class FileExtension(file_extension, case_sensitive=False)

    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) – Pass `True` 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)

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

    Use as `filters.Document.APK`.

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

    Use as `filters.Document.DOC`.

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

    Use as `filters.Document.DOCX`.

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

    Use as `filters.Document.EXE`.

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

    Use as `filters.Document.MP4`.

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

    Use as `filters.Document.GIF`.

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

    Use as `filters.Document.JPG`.

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

    Use as `filters.Document.MP3`.

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

    Use as `filters.Document.PDF`.

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

    Use as `filters.Document.PY`.

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

    Use as `filters.Document.SVG`.

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

    Use as `filters.Document.TXT`.

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

    Use as `filters.Document.TARGZ`.

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

    Use as `filters.Document.WAV`.

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

    Use as `filters.Document.XML`.

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

    Use as `filters.Document.ZIP`.

class telegram.ext.filters.Entity(entity_type)

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

class telegram.ext.filters.ForwardedFrom(chat_id=None, username=None, allow_empty=False)

  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 particular

  - `telegram.MessageOriginUser.sender_user`

  - `telegram.MessageOriginChat.sender_chat`

  - `telegram.MessageOriginChannel.chat`

  Added in version 13.5.

  Changed in version 20.8: Was previously based on `telegram.Message.forward_from` and `telegram.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 type `telegram.MessageOriginHiddenUser`. 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

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

    Type:

      set(`int`)

  allow_empty

    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)

    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)

    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)

    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.

  property name

    Name for this filter.

    Type:

      `str`

  remove_usernames(username)

    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

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

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

  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)

  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.

  Available In

  - `telegram.ext.CommandHandler.filters`

  - `telegram.ext.MessageHandler.filters`

  - `telegram.ext.PrefixHandler.filters`

  See also

  Advanced Filters

  check_update(update)

    Checks if the specified update should be handled by this filter by passing `effective_message` to `filter()`.

    Parameters:

      update (`telegram.Update`) – The update to check.

    Returns:

      If the update should be handled by this filter, returns `True` or a dict with lists, in case the filter is a data filter. If the update should not be handled by this filter, `False` or `None`.

    Return type:

      `bool` | dict[`str`, `list`] | `None`

  abstract filter(message)

    This method must be overwritten.

    Parameters:

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

    Returns:

      `dict` or `bool`

class telegram.ext.filters.Regex(pattern)

  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.

  See also

  Types of Handlers

  Parameters:

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

class telegram.ext.filters.SenderChat(chat_id=None, username=None, allow_empty=False)

  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.

  See also

  `telegram.ext.filters.IS_AUTOMATIC_FORWARD`

  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

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

    Type:

      set(`int`)

  allow_empty

    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

    All messages with a `telegram.Message.sender_chat`.

  SUPER_GROUP = filters.SenderChat.SUPER_GROUP

    Messages whose sender chat is a super group.

  CHANNEL = filters.SenderChat.CHANNEL

    Messages whose sender chat is a channel.

  add_chat_ids(chat_id)

    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)

    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)

    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.

  property name

    Name for this filter.

    Type:

      `str`

  remove_usernames(username)

    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

    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

  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

    Messages that contain any of the below.

  CHAT_BACKGROUND_SET = filters.StatusUpdate.CHAT_BACKGROUND_SET

    Messages that contain `telegram.Message.chat_background_set`.

  CHAT_CREATED = filters.StatusUpdate.CHAT_CREATED

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

  CHAT_SHARED = filters.StatusUpdate.CHAT_SHARED

    Messages that contain `telegram.Message.chat_shared`.

    Added in version 20.1.

  CONNECTED_WEBSITE = filters.StatusUpdate.CONNECTED_WEBSITE

    Messages that contain `telegram.Message.connected_website`.

  DELETE_CHAT_PHOTO = filters.StatusUpdate.DELETE_CHAT_PHOTO

    Messages that contain `telegram.Message.delete_chat_photo`.

  FORUM_TOPIC_CLOSED = filters.StatusUpdate.FORUM_TOPIC_CLOSED

    Messages that contain `telegram.Message.forum_topic_closed`.

    Added in version 20.0.

  FORUM_TOPIC_CREATED = filters.StatusUpdate.FORUM_TOPIC_CREATED

    Messages that contain `telegram.Message.forum_topic_created`.

    Added in version 20.0.

  FORUM_TOPIC_EDITED = filters.StatusUpdate.FORUM_TOPIC_EDITED

    Messages that contain `telegram.Message.forum_topic_edited`.

    Added in version 20.0.

  FORUM_TOPIC_REOPENED = filters.StatusUpdate.FORUM_TOPIC_REOPENED

    Messages that contain `telegram.Message.forum_topic_reopened`.

    Added in version 20.0.

  GENERAL_FORUM_TOPIC_HIDDEN = filters.StatusUpdate.GENERAL_FORUM_TOPIC_HIDDEN

    Messages that contain `telegram.Message.general_forum_topic_hidden`.

    Added in version 20.0.

  GENERAL_FORUM_TOPIC_UNHIDDEN = filters.StatusUpdate.GENERAL_FORUM_TOPIC_UNHIDDEN

    Messages that contain `telegram.Message.general_forum_topic_unhidden`.

    Added in version 20.0.

  GIVEAWAY_CREATED = filters.StatusUpdate.GIVEAWAY_CREATED

    Messages that contain `telegram.Message.giveaway_created`.

    Added in version 20.8.

  GIVEAWAY_COMPLETED = filters.StatusUpdate.GIVEAWAY_COMPLETED

    Messages that contain `telegram.Message.giveaway_completed`. .. versionadded:: 20.8

  LEFT_CHAT_MEMBER = filters.StatusUpdate.LEFT_CHAT_MEMBER

    Messages that contain `telegram.Message.left_chat_member`.

  MESSAGE_AUTO_DELETE_TIMER_CHANGED = filters.StatusUpdate.MESSAGE_AUTO_DELETE_TIMER_CHANGED

    Messages that contain `telegram.Message.message_auto_delete_timer_changed`

    Added in version 13.4.

  MIGRATE = filters.StatusUpdate.MIGRATE

    Messages that contain `telegram.Message.migrate_from_chat_id` or `telegram.Message.migrate_to_chat_id`.

  NEW_CHAT_MEMBERS = filters.StatusUpdate.NEW_CHAT_MEMBERS

    Messages that contain `telegram.Message.new_chat_members`.

  NEW_CHAT_PHOTO = filters.StatusUpdate.NEW_CHAT_PHOTO

    Messages that contain `telegram.Message.new_chat_photo`.

  NEW_CHAT_TITLE = filters.StatusUpdate.NEW_CHAT_TITLE

    Messages that contain `telegram.Message.new_chat_title`.

  PINNED_MESSAGE = filters.StatusUpdate.PINNED_MESSAGE

    Messages that contain `telegram.Message.pinned_message`.

  PROXIMITY_ALERT_TRIGGERED = filters.StatusUpdate.PROXIMITY_ALERT_TRIGGERED

    Messages that contain `telegram.Message.proximity_alert_triggered`.

  REFUNDED_PAYMENT = filters.StatusUpdate.REFUNDED_PAYMENT

    Messages that contain `telegram.Message.refunded_payment`. .. versionadded:: 21.4

  USER_SHARED = filters.StatusUpdate.USER_SHARED

    Messages that contain `"user_shared"` in `telegram.TelegramObject.api_kwargs`.

    Warning

    This will only catch the legacy `user_shared` field, not the new `telegram.Message.users_shared` attribute!

    Changed in version 21.0: Now relies on `telegram.TelegramObject.api_kwargs` as the native attribute `Message.user_shared` was removed.

    Added in version 20.1.

    Deprecated since version 20.8: Use `USERS_SHARED` instead.

  USERS_SHARED = filters.StatusUpdate.USERS_SHARED

    Messages that contain `telegram.Message.users_shared`.

    Added in version 20.8.

  VIDEO_CHAT_ENDED = filters.StatusUpdate.VIDEO_CHAT_ENDED

    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

    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

    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

    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

    Messages that contain `telegram.Message.web_app_data`.

    Added in version 20.0.

  WRITE_ACCESS_ALLOWED = filters.StatusUpdate.WRITE_ACCESS_ALLOWED

    Messages that contain `telegram.Message.write_access_allowed`.

    Added in version 20.0.

class telegram.ext.filters.Sticker

  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

    Messages that contain `telegram.Message.sticker`.

  ANIMATED = filters.Sticker.ANIMATED

    Messages that contain `telegram.Message.sticker` and `is animated`.

    Added in version 20.0.

  STATIC = filters.Sticker.STATIC

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

    Added in version 20.0.

  VIDEO = filters.Sticker.VIDEO

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

    Added in version 20.0.

  PREMIUM = filters.Sticker.PREMIUM

    Messages that contain `telegram.Message.sticker` and have a `premium animation`.

    Added in version 20.0.

class telegram.ext.filters.SuccessfulPayment(invoice_payloads=None)

  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)

  See also

  `telegram.ext.filters.SUCCESSFUL_PAYMENT`

  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)

  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

  `telegram.ext.filters.TEXT`

  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.

class telegram.ext.filters.UpdateFilter(name=None, data_filter=False)

  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.

  Available In

  - `telegram.ext.CommandHandler.filters`

  - `telegram.ext.MessageHandler.filters`

  - `telegram.ext.PrefixHandler.filters`

  check_update(update)

    Checks if the specified update should be handled by this filter.

    Parameters:

      update (`telegram.Update`) – The update to check.

    Returns:

      If the update should be handled by this filter, returns `True` or a dict with lists, in case the filter is a data filter. If the update should not be handled by this filter, `False` or `None`.

    Return type:

      `bool` | dict[`str`, `list`] | `None`

  abstract filter(update)

    This method must be overwritten.

    Parameters:

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

    Returns:

      `dict` or `bool`.

class telegram.ext.filters.UpdateType

  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

    Updates with `telegram.Update.channel_post`.

  CHANNEL_POSTS = filters.UpdateType.CHANNEL_POSTS

    Updates with either `telegram.Update.channel_post` or `telegram.Update.edited_channel_post`.

  EDITED = filters.UpdateType.EDITED

    Updates with `telegram.Update.edited_message`, `telegram.Update.edited_channel_post`, or `telegram.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

    Updates with `telegram.Update.edited_channel_post`.

  EDITED_MESSAGE = filters.UpdateType.EDITED_MESSAGE

    Updates with `telegram.Update.edited_message`.

  MESSAGE = filters.UpdateType.MESSAGE

    Updates with `telegram.Update.message`.

  MESSAGES = filters.UpdateType.MESSAGES

    Updates with either `telegram.Update.message` or `telegram.Update.edited_message`.

  BUSINESS_MESSAGE = filters.UpdateType.BUSINESS_MESSAGE

    Updates with `telegram.Update.business_message`.

    Added in version 21.1.

  EDITED_BUSINESS_MESSAGE = filters.UpdateType.EDITED_BUSINESS_MESSAGE

    Updates with `telegram.Update.edited_business_message`.

    Added in version 21.1.

  BUSINESS_MESSAGES = filters.UpdateType.BUSINESS_MESSAGES

    Updates with either `telegram.Update.business_message` or `telegram.Update.edited_business_message`.

    Added in version 21.1.

class telegram.ext.filters.User(user_id=None, username=None, allow_empty=False)

  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

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

    Type:

      `bool`

  add_usernames(username)

    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.

  property name

    Name for this filter.

    Type:

      `str`

  remove_usernames(username)

    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

    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

    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)

    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)

    Remove one or more users from allowed user ids.

    Parameters:

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

class telegram.ext.filters.ViaBot(bot_id=None, username=None, allow_empty=False)

  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

  `VIA_BOT`

  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

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

    Type:

      `bool`

  add_usernames(username)

    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.

  property name

    Name for this filter.

    Type:

      `str`

  remove_usernames(username)

    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

    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

    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)

    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)

    Remove one or more bots from allowed bot ids.

    Parameters:

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