← All posts
Tutorial

Telegram MessageEntity Offsets: Parse UTF-16 Without Breaking Emoji

Telegram MessageEntity.offset and length count UTF-16 code units, not UTF-8 bytes, Python string indexes, or visible characters. To extract a mention, command, or formatted span, apply those coordinates to the exact original text. An emoji before the span can make ordinary Python slicing return the wrong substring even though the webhook and JSON are valid.

Key takeaways

  • Keep text with entities, and caption with caption_entities.
  • Extract spans before trimming, normalizing, translating, or adding prefixes.
  • In Python, convert to UTF-16 bytes and slice at twice the supplied offsets.
  • Native Telegram entities are not a documented field of UnifyPort’s normalized message.received contract.

Why an emoji shifts the extracted text

Telegram’s entity documentation explicitly uses UTF-16 code units for both the Bot API and MTProto. Code points in the Basic Multilingual Plane occupy one unit; code points outside it occupy two. A visible emoji sequence can contain several code points, so counting what a person sees is not a reliable substitute.

Consider this synthetic fragment of a native Telegram message—not a captured webhook or a complete Update:

{
  "text": "😀 /help",
  "entities": [
    { "type": "bot_command", "offset": 3, "length": 5 }
  ]
}

The emoji occupies two UTF-16 units, and the space occupies one. The command therefore starts at offset 3 and covers 5 units.

Python strings are sequences of Unicode code points. For this fixture, text[3:8] gives help, losing the slash. The coordinates are correct; the slicing unit is wrong. Adding one to every offset is not a fix: different prefixes contain different numbers of supplementary characters.

This is a receiving-side problem. If your failure occurs while sending HTML, use the separate Telegram dynamic-text formatting guide; escaping markup does not repair entity coordinates.

A Python extractor with explicit boundaries

The following illustrative helper extracts one span. It performs no network requests and is not a complete entity renderer. Its strict decoding rejects ranges that split a surrogate pair instead of silently inserting replacement characters.

def telegram_entity_text(text, entity):
    if not isinstance(text, str):
        raise TypeError("Expected original text")

    offset = entity["offset"]
    length = entity["length"]
    if type(offset) is not int or type(length) is not int:
        raise TypeError("Entity coordinates must be integers")
    if offset < 0 or length <= 0:
        raise ValueError("Invalid entity range")

    encoded = text.encode("utf-16-le")
    start = offset * 2
    end = (offset + length) * 2
    if end > len(encoded):
        raise ValueError("Entity extends beyond text")

    # An invalid boundary must not silently change the extracted target.
    return encoded[start:end].decode("utf-16-le")


text = "😀 /help"
entity = {"type": "bot_command", "offset": 3, "length": 5}
assert telegram_entity_text(text, entity) == "/help"

The explicit little-endian encoding avoids adding a byte-order mark to the coordinate space. Multiplication by two converts UTF-16 units to byte positions; it is not a conversion to UTF-8 positions.

Treat a rejected range as a parsing problem for that message. Preserve the original through your protected storage and retention policy, and record a sanitized diagnostic. Do not guess a corrected command or mention and execute it. The assertion is a proposed local check, not a reported test result.

Pair each entity array with its own source

The Bot API reference distinguishes message text entities from caption entities. Keep those pairs together:

Native fieldsSource used for extraction
text and entitiesThe unchanged text string
caption and caption_entitiesThe unchanged caption string
text_link entityExtract its label from the source; its destination is the entity’s url
text_mention entityExtract its display label; use its user object for the supplied identity

Do not apply caption offsets to a generated attachment summary. Likewise, a link’s visible label is not necessarily its destination, and a displayed person name is not an identity key.

Recommended processing order:

  1. Authenticate intake according to the receiving integration’s contract.
  2. Store the original string and associated entity array together.
  3. Validate ranges and extract against that original.
  4. Interpret only the entity types your application supports.
  5. Create a separate display or search representation afterward.

Extracting a valid span does not make its contents trusted. Validate link destinations before rendering or opening them; do not execute a command merely because Telegram labeled it bot_command. A full renderer also needs Telegram’s entity nesting rules. This helper deliberately handles extraction only.

Keep the UnifyPort boundary explicit

UnifyPort’s unofficial interface delivers a different public schema. Its message.received reference documents data.message.text, optional attachments and structured content such as mentions containing IDs. It does not document native entities or caption_entities arrays. Do not add those fields to a sample or promise that they pass through unchanged.

The Telegram media mapping guide explains how normalized text, attachments, contacts, and locations fit together. Consume that documented structure when building a shared inbox. Do not run the native extractor on normalized text using offsets obtained from a different representation.

If preserving Telegram’s exact native formatting entities is a hard requirement for a bot product, keep the official Bot API receiving path. If the goal is a connected-account inbox, design against the normalized fields rather than treating it as a raw Bot API archive.

Checks and FAQ

What should the regression fixtures cover?

Use plain ASCII, an emoji before a command, supplementary characters inside a span, combining marks, a caption with its own entities, and a range splitting a surrogate pair. Test that modifying the display copy leaves the stored source unchanged. These are suggested checks, not measured outcomes.

Can I trim whitespace before extraction?

No. Removing leading characters changes the coordinate space. Extract first or compute new coordinates for the modified text.

Should I count UTF-8 bytes because the request uses UTF-8?

No. Transport encoding and entity coordinates are separate. Telegram specifies UTF-16 units for the coordinates.

Does this helper preserve formatting when forwarding?

No. It extracts a substring only. Sending or rendering formatted content requires a separate supported contract and validation.

Next step and sources

Add the synthetic fixture to your native Telegram parser tests. For a normalized inbox, start with the UnifyPort received-message contract and keep native and normalized adapters separate.

Sources checked on 2026-11-21:

UnifyPort API

Turn messaging integration into a stable product pipeline.

Start by sending through one API, then bring every inbound message back into your business system with standard events.