Why an emoji can shift your Telegram bot's bold text

Telegram MessageEntity offsets and lengths use UTF-16 code units. Build correct bold and link ranges around emoji, and keep entities separate from MarkdownV2 parsing.

Why an emoji can shift your Telegram bot's bold text

If a Telegram bot bolds the wrong characters or places a link one position too early, check MessageEntity.offset and length: both use UTF-16 code units. An earlier emoji may occupy two units. Counting visible characters or UTF-8 bytes shifts everything that follows.

This article checks MessageEntity, sendMessage, and Formatting options on November 28, 2026. The latest documentation entry is Bot API 10.5, November 22; UTF-16 offsets are an existing rule, not a feature introduced in that release. The examples ran locally without sending a Telegram message.

Why does the same text have several lengths?

Bytes, Unicode code points, and UTF-16 units measure different things, and Telegram explicitly uses UTF-16 units for entities.

TextUnicode code pointsUTF-16 unitsUTF-8 bytes
A111
中113
🧭124
a followed by combining acute accent223

The final row usually looks like one character, but consists of two code points. JavaScript string length and slice use UTF-16 units. [...text].length counts code points, so it is not a replacement for Telegram entity offsets. In Python, len(text.encode('utf-16-le')) // 2 counts the units; specifying the little-endian encoding avoids adding a BOM.

Visible characters, code points, UTF-16 units, and UTF-8 bytes count different representations

Decode network bytes correctly before measuring text. If the input is already corrupted, follow the SSE byte and event boundaries first. Fixing an entity offset cannot repair damaged source text.

How can entity positions stay attached to the right text?

Build the message from ordered fragments, recording the current UTF-16 length before adding each formatted fragment.

This public example bolds “产品 Q7” and makes “手册” a link. The Chinese strings are intentional: they keep the same verified offsets as the localized example while also exercising non-ASCII text. Save it as entities.mjs and run node entities.mjs with Node.js 22+:

import assert from 'node:assert/strict';

const fragments = [
  { text: '🧭 结果:' },
  { text: '产品 Q7', type: 'bold' },
  { text: '\n查看' },
  { text: '手册', type: 'text_link', url: 'https://example.com/manual' },
];
let text = '';
const entities = [];
for (const fragment of fragments) {
  if (fragment.type) {
    const entity = {
      type: fragment.type,
      offset: text.length,
      length: fragment.text.length,
    };
    if (fragment.type === 'text_link') entity.url = fragment.url;
    entities.push(entity);
  }
  text += fragment.text;
}
assert.deepEqual(entities, [
  { type: 'bold', offset: 6, length: 5 },
  { type: 'text_link', offset: 14, length: 2, url: 'https://example.com/manual' },
]);
for (const entity of entities) {
  assert.ok(entity.offset >= 0 && entity.offset + entity.length <= text.length);
}
assert.equal(text.slice(6, 11), '产品 Q7');
assert.equal(text.slice(14, 16), '手册');
console.log({ text, entities });

The prefix 🧭 结果: has five code points but six UTF-16 units, so the bold entity starts at offset: 6. A text_link URL is the destination, not part of the displayed text length. The URL above is an illustrative public address; use a verified documentation destination in the real application.

Append a plain prefix, locate the bold fragment, then record the link's independent range

Place text and entities in the same sendMessage payload with the correct chat target, and omit parse_mode. Telegram documents entities as an alternative to parse-mode processing. Building from fragments also handles repeated words without accidentally selecting the first match with indexOf.

Can a model's Markdown be sent unchanged?

General Markdown is not automatically valid Telegram MarkdownV2; the application needs an explicit conversion policy.

MarkdownV2 escapes punctuation in ordinary text, including underscores, asterisks, brackets, parentheses, tildes, backticks, and the characters > # + - = | { } . !. Code spans and link destinations have different rules. See the complete MarkdownV2 specification. Applying one escaping expression to text, code, and URLs can over-escape some sections and break others.

For a few bold phrases and links, controlled entity fragments are straightforward. Supporting model-generated tables, nested lists, and code blocks requires parsing a deliberately supported Markdown subset and translating it into Telegram's available formatting. Setting parse_mode: MarkdownV2 alone does not establish general Markdown support.

Plain text, explicit entities, and MarkdownV2 are separate representation choices

For example, release_1.2 remains ordinary literal text when using entities, with bold ranges specified separately. Under MarkdownV2, its underscore and period need the ordinary-text escaping rules. Do not escape a string first and then derive entities from the unescaped version: those are different text representations.

A plain-text fallback should also be explicit. Removing format-processing parameters leaves asterisks and fences visible; it does not automatically create a clean layout. An intact code sample or table may work better as a document attachment.

Can old entities survive a split or edit?

Recompute entity positions from the new full message whenever its text changes.

Adding a completion label, replacing line breaks, or extracting a second message part changes positions. Unicode normalization can change the underlying sequence too. Finalize the text, derive its entities, and treat both as one version when sending, saving, or retrying.

Prepending “完成:” to the example adds three UTF-16 units. The bold offset moves from 6 to 9 and the manual link from 14 to 17. Updating only the total message length or an entity’s length does not correct its start; rebuilding from fragments updates both together.

For long-message splitting, determine each part first. Formatting that spans a boundary needs an explicit reconstruction policy; copying the original entities into every part is incorrect. During streaming updates, each edit likewise needs entities for that revision's full text.

Telegram also restricts nesting. Overlapping entities must be fully contained, and types such as code and pre have additional rules. The example uses disjoint bold and link ranges and is not a general entity validator.

How can you verify an offset?

Extract the text covered by each entity and compare it with the intended label, then separately verify allowed formatting and actual client rendering.

Local checks confirmed both exact ranges, the prefix's code-point/UTF-16 difference, and that the incorrect offset 5 does not select “产品 Q7.” Before deployment, add repeated labels, multiple emoji, combining marks, split messages, and revised text. Confirm their appearance with an isolated bot instead of treating “the API did not reject it” as a formatting test. Model configuration belongs in the Nbility chat documentation; Telegram text layout remains the bot application's responsibility.

Related posts

View all posts
Send Telegram bot replies back to the right topic

Send Telegram bot replies back to the right topic

Keep chat_id and message_thread_id together when replying to Telegram topics. Use reply_parameters separately, and pause delivery when the original destination becomes unavailable.

TelegramBots

Run your Agent workflow through Nbility

Get an API key and connect OpenAI-compatible models and developer tools from one place.

Get an API key