Delivering a long AI reply through a Telegram bot

Handle Telegram's message is too long error with conservative text limits, grapheme-safe splitting, and a receipt for every part of the answer.

Delivering a long AI reply through a Telegram bot

When a Telegram bot reports message is too long, split the answer you already have and track delivery of each part. A model's output allowance does not determine Telegram's message limit. Generating the answer again usually leaves the delivery problem unresolved and loses your place in the original response.

This article checks the Telegram Bot API on November 28, 2026. Its latest entry is Bot API 10.5, released November 22. The scope is ordinary sendMessage text, whose limits should not be mixed with media captions or Rich Messages. The examples ran locally on synthetic text; no bot or model API was called.

Where should the length check happen?

The documented sendMessage.text limit is 1–4096 characters after entities parsing, so check the text the recipient will receive, rather than model tokens or the byte length of a JSON request.

An answer can pass through model deltas, complete text, formatting, and message splitting. Checking too early misses a later title or “Part 1/3” label. Measuring serialized JSON counts escaping and field names that are not part of the displayed message.

Model output, visible text, message parts, and the final payload have separate boundaries

The example uses a local budget of 3800 UTF-16 code units per part. This is a conservative application choice with room for short labels. It is not Telegram's definition of “character,” and 3800 is not a platform limit. Apply the same budget check to the final text after adding anything. Model calls and message delivery are separate responsibilities: Nbility's chat endpoint does not format Telegram messages for your application.

How can a splitter preserve emoji and paragraphs?

Iterate over complete graphemes, then prefer a paragraph boundary that fits within the budget.

JavaScript's slice(0, 4096) cuts at UTF-16 positions and can split a surrogate pair. The following Node.js 22+ example uses Intl.Segmenter to preserve grapheme clusters, including combining marks and joined emoji. At the limit, a paragraph break in the latter half of the buffer takes precedence. This is a plain-text splitter; it does not preserve Markdown or entities.

Save as split.mjs and run node split.mjs:

import assert from 'node:assert/strict';

function splitPlainText(text, limit = 3800) {
  if (typeof text !== 'string' || !text.isWellFormed() || !text.trim()) {
    throw new Error('Expected non-empty, well-formed text');
  }
  if (!Number.isInteger(limit) || limit < 1 || limit > 4096) {
    throw new Error('Invalid local limit');
  }
  const parts = [];
  let current = '';
  const segments = new Intl.Segmenter('zh', { granularity: 'grapheme' });
  for (const { segment } of segments.segment(text)) {
    if (segment.length > limit) throw new Error('Grapheme exceeds local limit');
    if (current.length + segment.length > limit) {
      const paragraphEnd = current.lastIndexOf('\n\n') + 2;
      const cut = paragraphEnd > 1 && paragraphEnd >= current.length / 2
        ? paragraphEnd : current.length;
      parts.push(current.slice(0, cut));
      current = current.slice(cut);
      if (current.length + segment.length > limit) {
        parts.push(current);
        current = '';
      }
    }
    current += segment;
  }
  if (current) parts.push(current);
  if (parts.some((part) => !part.trim())) throw new Error('Whitespace-only part');
  return parts;
}

const source = '甲乙\n\n丙丁戊己庚辛';
const parts = splitPlainText(source, 8);
assert.deepEqual(parts, ['甲乙\n\n', '丙丁戊己庚辛']);
assert.equal(parts.join(''), source);
assert.deepEqual(
  splitPlainText('A'.repeat(4095) + '🧭', 4096).map((part) => part.length),
  [4095, 2]
);
console.log(parts);

The eight-unit budget makes the paragraph boundary visible in a small example. Use the default budget for normal calls, and separately cap total answer size and message count before splitting. An arbitrary input should not create an unbounded delivery queue. Empty input, whitespace-only parts, and a single grapheme larger than the budget are rejected; the application can explain the failure or offer a file without silently removing content.

Grapheme-safe counting and a paragraph boundary produce parts that reconstruct the exact source

For bold text or links, choose each part's text first and then build its UTF-16 entities. Arbitrarily cutting formatted Markdown can leave code fences, links, and emphasis markers open across messages.

Why can only half of a split answer arrive?

Splitting fixes individual message size; per-part receipts tell you whether the whole answer was delivered.

Save the complete answer and its delivery plan before sending. Send the first part, record its returned message_id, then proceed to the second. Submitting everything through Promise.all makes completion order harder to control. A queue for the same conversation also prevents separate tasks from interleaving their parts.

Each saved part gets a receipt; an uncertain send pauses the delivery plan

Result for one partRecordNext action
ok: true with a returned MessageConfirmed, plus message IDContinue to the next part
Explicit length or formatting rejectionRejected, plus reasonCorrect this part and validate it
Connection lost after submission, no resultOutcome unknownPause and investigate available records

An uncertain send is not a reason to resend the entire answer or ask the model for a replacement. Ordinary Telegram sends do not promise support for an arbitrary application idempotency key. See duplicate updates and send receipts for that recovery boundary. A stored message_id records a successful send response; it does not prove the user read the message.

When is a document a better delivery format?

Use a short chat summary with an attached document when the reader needs an intact report, long code, or preserved indentation.

The choice depends on how the answer will be used. A dozen message fragments can be awkward to save and reference. A named text document may be easier. Uploading, reusing a file_id, and obtaining a download URL are different operations, covered in Telegram file identifiers and downloads. A bot download URL should not become a public sharing link.

For an answer displayed while it is generated, use the separate draft and streaming update path; a model delta is not automatically a new Telegram message. In a chat with multiple topics, every part must also retain the correct message_thread_id; a queue keyed only by chat is insufficient for routing. If the bot is not connected yet, start with the Hermes Telegram setup.

What should the local checks cover?

Check boundaries, non-ASCII text, grapheme clusters, and the point from which delivery would resume.

Local checks covered 4096/4097 ASCII characters, 4095 ASCII characters followed by an emoji, combining marks, exact paragraph reconstruction, and rejection of empty input, whitespace, lone surrogates, oversized graphemes, invalid budgets, and whitespace-only parts. Every accepted part must stay within the local budget, preserve complete graphemes, and reconstruct the source exactly. Actual formatting, API receipts, and interrupted delivery still need verification with an isolated bot; string tests do not establish those network behaviors.

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