Skip to content
Back to top
View this page

# MessageEntity

class telegram.MessageEntity(type, offset, length, url=None, user=None, language=None, custom_emoji_id=None, *, api_kwargs=None)

  Bases: `telegram.TelegramObject`

  This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc.

  Objects of this class are comparable in terms of equality. Two objects of this class are considered equal, if their `type`, `offset` and `length` are equal.

  Use In

  - `telegram.Bot.copy_message()`

  - `telegram.Bot.edit_message_caption()`

  - `telegram.Bot.edit_message_text()`

  - `telegram.Bot.edit_story()`

  - `telegram.Bot.gift_premium_subscription()`

  - `telegram.Bot.post_story()`

  - `telegram.Bot.send_animation()`

  - `telegram.Bot.send_audio()`

  - `telegram.Bot.send_document()`

  - `telegram.Bot.send_gift()`

  - `telegram.Bot.send_media_group()`

  - `telegram.Bot.send_message()`

  - `telegram.Bot.send_paid_media()`

  - `telegram.Bot.send_photo()`

  - `telegram.Bot.send_poll()`

  - `telegram.Bot.send_video()`

  - `telegram.Bot.send_voice()`

  Available In

  - `telegram.Checklist.title_entities`

  - `telegram.ChecklistTask.text_entities`

  - `telegram.Game.text_entities`

  - `telegram.GiftInfo.entities`

  - `telegram.InlineQueryResultAudio.caption_entities`

  - `telegram.InlineQueryResultCachedAudio.caption_entities`

  - `telegram.InlineQueryResultCachedDocument.caption_entities`

  - `telegram.InlineQueryResultCachedGif.caption_entities`

  - `telegram.InlineQueryResultCachedMpeg4Gif.caption_entities`

  - `telegram.InlineQueryResultCachedPhoto.caption_entities`

  - `telegram.InlineQueryResultCachedVideo.caption_entities`

  - `telegram.InlineQueryResultCachedVoice.caption_entities`

  - `telegram.InlineQueryResultDocument.caption_entities`

  - `telegram.InlineQueryResultGif.caption_entities`

  - `telegram.InlineQueryResultMpeg4Gif.caption_entities`

  - `telegram.InlineQueryResultPhoto.caption_entities`

  - `telegram.InlineQueryResultVideo.caption_entities`

  - `telegram.InlineQueryResultVoice.caption_entities`

  - `telegram.InputChecklist.title_entities`

  - `telegram.InputChecklistTask.text_entities`

  - `telegram.InputMedia.caption_entities`

  - `telegram.InputMediaAnimation.caption_entities`

  - `telegram.InputMediaAudio.caption_entities`

  - `telegram.InputMediaDocument.caption_entities`

  - `telegram.InputMediaPhoto.caption_entities`

  - `telegram.InputMediaVideo.caption_entities`

  - `telegram.InputPollOption.text_entities`

  - `telegram.InputTextMessageContent.entities`

  - `telegram.Message.caption_entities`

  - `telegram.Message.entities`

  - `telegram.OwnedGiftRegular.entities`

  - `telegram.Poll.explanation_entities`

  - `telegram.Poll.question_entities`

  - `telegram.PollOption.text_entities`

  - `telegram.ReplyParameters.quote_entities`

  - `telegram.TextQuote.entities`

  Parameters:

    - type (`str`) –

      Type of the entity. Can be `MENTION` (`@username`), `HASHTAG` (`#hashtag` or `#hashtag@chatusername`), `CASHTAG` (`$USD` or `USD@chatusername`), `BOT_COMMAND` (`/start@jobs_bot`), `URL` (`https://telegram.org`), `EMAIL` (`do-not-reply@telegram.org`), `PHONE_NUMBER` (`+1-212-555-0123`), `BOLD` (bold text), `ITALIC` (italic text), `UNDERLINE` (underlined text), `STRIKETHROUGH`, `SPOILER` (spoiler message), `BLOCKQUOTE` (block quotation), `CODE` (monowidth string), `PRE` (monowidth block), `TEXT_LINK` (for clickable text URLs), `TEXT_MENTION` (for users without usernames), `CUSTOM_EMOJI` (for inline custom emoji stickers).

      Added in version 20.0: Added inline custom emoji

      Added in version 20.8: Added block quotation

    - offset (`int`) – Offset in UTF-16 code units to the start of the entity.

    - length (`int`) – Length of the entity in UTF-16 code units.

    - url (`str`, optional) – For `TEXT_LINK` only, url that will be opened after user taps on the text.

    - user (`telegram.User`, optional) – For `TEXT_MENTION` only, the mentioned user.

    - language (`str`, optional) – For `PRE` only, the programming language of the entity text.

    - custom_emoji_id (`str`, optional) –

      For `CUSTOM_EMOJI` only, unique identifier of the custom emoji. Use `telegram.Bot.get_custom_emoji_stickers()` to get full information about the sticker.

      Added in version 20.0.

  type

    Type of the entity. Can be `MENTION` (`@username`), `HASHTAG` (`#hashtag` or `#hashtag@chatusername`), `CASHTAG` (`$USD` or `USD@chatusername`), `BOT_COMMAND` (`/start@jobs_bot`), `URL` (`https://telegram.org`), `EMAIL` (`do-not-reply@telegram.org`), `PHONE_NUMBER` (`+1-212-555-0123`), `BOLD` (bold text), `ITALIC` (italic text), `UNDERLINE` (underlined text), `STRIKETHROUGH`, `SPOILER` (spoiler message), `BLOCKQUOTE` (block quotation), `CODE` (monowidth string), `PRE` (monowidth block), `TEXT_LINK` (for clickable text URLs), `TEXT_MENTION` (for users without usernames), `CUSTOM_EMOJI` (for inline custom emoji stickers).

    Added in version 20.0: Added inline custom emoji

    Added in version 20.8: Added block quotation

    Type:

      `str`

  offset

    Offset in UTF-16 code units to the start of the entity.

    Type:

      `int`

  length

    Length of the entity in UTF-16 code units.

    Type:

      `int`

  url

    Optional. For `TEXT_LINK` only, url that will be opened after user taps on the text.

    Type:

      `str`

  user

    Optional. For `TEXT_MENTION` only, the mentioned user.

    Type:

      `telegram.User`

  language

    Optional. For `PRE` only, the programming language of the entity text.

    Type:

      `str`

  custom_emoji_id

    Optional. For `CUSTOM_EMOJI` only, unique identifier of the custom emoji. Use `telegram.Bot.get_custom_emoji_stickers()` to get full information about the sticker.

    Added in version 20.0.

    Type:

      `str`

  ALL_TYPES = [<MessageEntityType.BLOCKQUOTE>, <MessageEntityType.BOLD>, <MessageEntityType.BOT_COMMAND>, <MessageEntityType.CASHTAG>, <MessageEntityType.CODE>, <MessageEntityType.CUSTOM_EMOJI>, <MessageEntityType.EMAIL>, <MessageEntityType.EXPANDABLE_BLOCKQUOTE>, <MessageEntityType.HASHTAG>, <MessageEntityType.ITALIC>, <MessageEntityType.MENTION>, <MessageEntityType.PHONE_NUMBER>, <MessageEntityType.PRE>, <MessageEntityType.SPOILER>, <MessageEntityType.STRIKETHROUGH>, <MessageEntityType.TEXT_LINK>, <MessageEntityType.TEXT_MENTION>, <MessageEntityType.UNDERLINE>, <MessageEntityType.URL>]

    A list of all available message entity types.

    Type:

      list[`str`]

  BLOCKQUOTE = 'blockquote'

    `telegram.constants.MessageEntityType.BLOCKQUOTE`

    Added in version 20.8.

  BOLD = 'bold'

    `telegram.constants.MessageEntityType.BOLD`

  BOT_COMMAND = 'bot_command'

    `telegram.constants.MessageEntityType.BOT_COMMAND`

  CASHTAG = 'cashtag'

    `telegram.constants.MessageEntityType.CASHTAG`

  CODE = 'code'

    `telegram.constants.MessageEntityType.CODE`

  CUSTOM_EMOJI = 'custom_emoji'

    `telegram.constants.MessageEntityType.CUSTOM_EMOJI`

    Added in version 20.0.

  EMAIL = 'email'

    `telegram.constants.MessageEntityType.EMAIL`

  EXPANDABLE_BLOCKQUOTE = 'expandable_blockquote'

    `telegram.constants.MessageEntityType.EXPANDABLE_BLOCKQUOTE`

    Added in version 21.3.

  HASHTAG = 'hashtag'

    `telegram.constants.MessageEntityType.HASHTAG`

  ITALIC = 'italic'

    `telegram.constants.MessageEntityType.ITALIC`

  MENTION = 'mention'

    `telegram.constants.MessageEntityType.MENTION`

  PHONE_NUMBER = 'phone_number'

    `telegram.constants.MessageEntityType.PHONE_NUMBER`

  PRE = 'pre'

    `telegram.constants.MessageEntityType.PRE`

  SPOILER = 'spoiler'

    `telegram.constants.MessageEntityType.SPOILER`

    Added in version 13.10.

  STRIKETHROUGH = 'strikethrough'

    `telegram.constants.MessageEntityType.STRIKETHROUGH`

  TEXT_LINK = 'text_link'

    `telegram.constants.MessageEntityType.TEXT_LINK`

  TEXT_MENTION = 'text_mention'

    `telegram.constants.MessageEntityType.TEXT_MENTION`

  UNDERLINE = 'underline'

    `telegram.constants.MessageEntityType.UNDERLINE`

  URL = 'url'

    `telegram.constants.MessageEntityType.URL`

  static adjust_message_entities_to_utf_16(text, entities)

    Utility functionality for converting the offset and length of entities from Unicode (`str`) to UTF-16 (`utf-16-le` encoded `bytes`).

    Tip

    Only the offsets and lengths calulated in UTF-16 is acceptable by the Telegram Bot API. If they are calculated using the Unicode string (`str` object), errors may occur when the text contains characters that are not in the Basic Multilingual Plane (BMP). For more information, see Unicode and Plane (Unicode).

    Added in version 21.4.

    Examples

    Below is a snippet of code that demonstrates how to use this function to convert entities from Unicode to UTF-16 space. The `unicode_entities` are calculated in Unicode and the utf_16_entities are calculated in UTF-16.

        text = "𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍"
        unicode_entities = [
            MessageEntity(offset=2, length=4, type=MessageEntity.BOLD),
            MessageEntity(offset=9, length=6, type=MessageEntity.ITALIC),
            MessageEntity(offset=28, length=3, type=MessageEntity.UNDERLINE),
        ]
        utf_16_entities = MessageEntity.adjust_message_entities_to_utf_16(
            text, unicode_entities
        )
        await bot.send_message(
            chat_id=123,
            text=text,
            entities=utf_16_entities,
        )
        # utf_16_entities[0]: offset=3, length=4
        # utf_16_entities[1]: offset=11, length=6
        # utf_16_entities[2]: offset=30, length=6

    Parameters:

      - text (`str`) – The text that the entities belong to

      - entities (Sequence[`telegram.MessageEntity`]) – Sequence of entities with offset and length calculated in Unicode

    Returns:

      Sequence of entities with offset and length calculated in UTF-16 encoding

    Return type:

      Sequence[`telegram.MessageEntity`]

  classmethod concatenate(*args)

    Utility functionality for concatenating two text along with their formatting entities.

    Tip

    This function is useful for prefixing an already formatted text with a new text and its formatting entities. In particular, it automatically correctly handles UTF-16 encoding.

    Examples

    This example shows a callback function that can be used to add a prefix and suffix to the message in a `CallbackQueryHandler`:

        async def prefix_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
            prefix = "𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍 | "
            prefix_entities = [
                MessageEntity(offset=2, length=4, type=MessageEntity.BOLD),
                MessageEntity(offset=9, length=6, type=MessageEntity.ITALIC),
                MessageEntity(offset=28, length=3, type=MessageEntity.UNDERLINE),
            ]
            suffix = " | 𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍"
            suffix_entities = [
                MessageEntity(offset=5, length=4, type=MessageEntity.BOLD),
                MessageEntity(offset=12, length=6, type=MessageEntity.ITALIC),
                MessageEntity(offset=31, length=3, type=MessageEntity.UNDERLINE),
            ]

            message = update.effective_message
            first = (prefix, prefix_entities, True)
            second = (message.text, message.entities)
            third = (suffix, suffix_entities, True)

            new_text, new_entities = MessageEntity.concatenate(first, second, third)
            await update.callback_query.edit_message_text(
                text=new_text,
                entities=new_entities,
            )

    Hint

    The entities are not modified in place. The function returns a new sequence of objects.

    Added in version 21.5.

    Parameters:

      *args (tuple[`str`, Sequence[`telegram.MessageEntity`]] | tuple[`str`, Sequence[`telegram.MessageEntity`], `bool`]) – Arbitrary number of tuples containing the text and its entities to concatenate. If the last element of the tuple is a `bool`, it is used to determine whether to adjust the entities to UTF-16 via `adjust_message_entities_to_utf_16()`. UTF-16 adjustment is disabled by default.

    Returns:

      The concatenated text and its entities

    Return type:

      tuple[`str`, Sequence[`telegram.MessageEntity`]]

  classmethod de_json(data, bot=None)

    See `telegram.TelegramObject.de_json()`.

  static shift_entities(by, entities)

    Utility functionality for shifting the offset of entities by a given amount.

    Examples

    Shifting by an integer amount:

        text = "Hello, world!"
        entities = [
            MessageEntity(offset=0, length=5, type=MessageEntity.BOLD),
            MessageEntity(offset=7, length=5, type=MessageEntity.ITALIC),
        ]
        shifted_entities = MessageEntity.shift_entities(1, entities)
        await bot.send_message(
            chat_id=123,
            text="!" + text,
            entities=shifted_entities,
        )

    Shifting using a string:

        text = "Hello, world!"
        prefix = "𝄢"
        entities = [
            MessageEntity(offset=0, length=5, type=MessageEntity.BOLD),
            MessageEntity(offset=7, length=5, type=MessageEntity.ITALIC),
        ]
        shifted_entities = MessageEntity.shift_entities(prefix, entities)
        await bot.send_message(
            chat_id=123,
            text=prefix + text,
            entities=shifted_entities,
        )

    Tip

    The `entities` are not modified in place. The function returns a sequence of new objects.

    Added in version 21.5.

    Parameters:

      - by (`str` | `int`) – Either the amount to shift the offset by or a string whose length will be used as the amount to shift the offset by. In this case, UTF-16 encoding will be used to calculate the length.

      - entities (Sequence[`telegram.MessageEntity`]) – Sequence of entities

    Returns:

      Sequence of entities with the offset shifted

    Return type:

      Sequence[`telegram.MessageEntity`]