Bad Request: message is too long — Telegram bot error and how to fix it
Bad Request: message is too long means your bot tried to send more than 4096 characters in one text message, counted after HTML or Markdown is parsed out. A caption has a lower limit, 1024 characters, and fails as message caption is too long. Split the text at paragraph or line breaks before you format it and send each part as its own message, or send the whole text as a .txt document.
By Livops team, the people who build and run LivopsUpdated
The error, as the Telegram Bot API returns it when a text message is over the limit:
{"ok":false,"error_code":400,"description":"Bad Request: message is too long"}
Each library wraps it in its own words:
| Library | What you see |
|---|---|
| aiogram 3 | TelegramBadRequest: Telegram server says - Bad Request: message is too long[6][7] |
| python-telegram-bot | telegram.error.BadRequest: Message is too long[8][9] |
| grammY | GrammyError: Call to 'sendMessage' failed! (400: Bad Request: message is too long)[11] |
| Telegraf | TelegramError: 400: Bad Request: message is too long[12] |
This page explains the 4096-character limit and how Telegram counts it, the 1024-character limit on captions and the error it gives, and the fixes: split the text at paragraph and line breaks without cutting a tag in half, format each part on its own, or send the whole text as a document. It ends with how to find the long message on Livops.
What does the error mean?
sendMessage takes the text of a message in its text parameter: 1-4096 characters after entities parsing[1]. editMessageText has the same limit for the new text[1]. Over that, nothing is sent.
The check happens before the message leaves for Telegram’s servers. For a bot, TDLib — the library the Bot API server is built on — measures the parsed text, and when it is longer than the limit it refuses it with Message is too long[3]. The Bot API server turns that into Bad Request: message is too long, with code 400[2].
Match the error by its description, not by its code alone: a failed request has ok set to false and the reason in description, while the contents of error_code are subject to change[1]. Many other mistakes are a 400 too.
How Telegram counts the 4096
- After parsing. With
parse_modeset, HTML tags and Markdown marks are taken out first, and only the text that is left is counted[1].<b>Total</b>counts as 5. - In characters, not bytes. TDLib counts the length of the text in characters[3]: every character that starts a new UTF-8 sequence counts once[4]. A Cyrillic letter, the Uzbek
ʻinoʻor a simple emoji is one character, as a Latin letter is. A Russian or Uzbek text has the same 4096 as an English one. - What your language counts. Python’s
len()counts characters the same way. JavaScript’s.lengthcounts UTF-16 code units, so an emoji counts as 2 there: a check with.lengthis stricter than Telegram’s, which is safe.
One more ceiling sits in front of all this: the raw text you send, markup included, may not be longer than 32768 bytes, or the Bot API server answers Bad Request: text is too long before it parses anything[2].
The close relatives
message caption is too long
A caption is shorter. Photos, videos, documents, audio, animations and voice messages take a caption of 0-1024 characters after entities parsing[1], and so do the items of an album and editMessageCaption[1]. Over that, TDLib refuses it with Message caption is too long[3]:
{"ok":false,"error_code":400,"description":"Bad Request: message caption is too long"}
MESSAGE_TOO_LONG
Telegram’s own servers have a name for the same condition, MESSAGE_TOO_LONG: “The provided message is too long”[5]. The Bot API server passes such upper-case error names through as they are, after Bad Request: [2]. So if you ever see Bad Request: MESSAGE_TOO_LONG, it is this error under Telegram’s own name, and the fix is the same.
Where the long text comes from
- An AI model’s answer. The commonest source now: a model asked for a detailed answer easily writes more than 4096 characters, and the bot sends it as it is.
- A list built from the database. Orders, users, search results joined with
"\n". It fits with ten rows in testing and fails with five hundred in production. - An error or log sent to an admin chat. A Python traceback, a JSON response or a build log, pasted into a message.
- A description used as a caption. A product card sent as a photo with its full description, which passes 4096 easily and 1024 even sooner.
- The user’s own text echoed back. A message quoted back with a header around it is longer than the one the user sent.
How to fix it
Split at paragraph and line breaks
Cut the text into parts under the limit, at the last paragraph break before the limit, else the last line break, else the last space, and only as a last resort in the middle of a word. Send each part as its own message, in order.
def split_text(text: str, limit: int = 4096) -> list[str]:
parts = []
while len(text) > limit:
cut = text.rfind("\n\n", 0, limit)
if cut <= 0:
cut = text.rfind("\n", 0, limit)
if cut <= 0:
cut = text.rfind(" ", 0, limit)
if cut <= 0:
cut = limit
parts.append(text[:cut].rstrip())
text = text[cut:].lstrip()
parts.append(text)
return [p for p in parts if p.strip()]
for part in split_text(answer):
await message.answer(part)
function splitText(text: string, limit = 4096): string[] {
const parts: string[] = [];
let rest = text;
while (rest.length > limit) {
let cut = rest.lastIndexOf("\n\n", limit - 1);
if (cut <= 0) cut = rest.lastIndexOf("\n", limit - 1);
if (cut <= 0) cut = rest.lastIndexOf(" ", limit - 1);
if (cut <= 0) cut = limit;
if (cut === limit && /[\uD800-\uDBFF]/.test(rest[cut - 1])) cut -= 1; // keep an emoji whole
parts.push(rest.slice(0, cut).trimEnd());
rest = rest.slice(cut).trimStart();
}
parts.push(rest);
return parts.filter((p) => p.trim() !== "");
}
for (const part of splitText(answer)) {
await ctx.reply(part);
}
Both drop empty parts, because an empty part fails as message text is empty. Send the parts one after another, not all at once: a long answer split into many messages to one chat is also how a bot meets 429 Too Many Requests.
Never cut formatted text: split first, format each part
The splitter above is for plain text. Cut an HTML or Markdown string at a fixed position and the cut can land inside <a href="…"> or between <b> and </b>; the first part then has a tag that never closes, and Telegram refuses it with can’t parse entities.
So split the content before it becomes markup. Build the message from blocks — one order, one search result, one paragraph — format each block on its own, and pack whole blocks into messages by their visible length:
import html
import re
TAG = re.compile(r"<[^>]+>")
def visible_len(html_text: str) -> int:
return len(html.unescape(TAG.sub("", html_text)))
def pack(blocks: list[str], limit: int = 4096, sep: str = "\n\n") -> list[str]:
messages, current = [], ""
for block in blocks:
candidate = f"{current}{sep}{block}" if current else block
if current and visible_len(candidate) > limit:
messages.append(current)
candidate = block
current = candidate
if current:
messages.append(current)
return messages
blocks = [f"<b>Order {o.id}</b>\n{html.escape(o.summary)}" for o in orders]
for text in pack(blocks):
await message.answer(text, parse_mode="HTML")
Every message ends where a block ends, so every tag that opens in it also closes in it. A single block that is longer than the limit by itself — one huge model answer — has to be split as plain text with split_text first, and each part escaped and formatted after.
Send it as a document
For a report, an export or a log, a file is better than a dozen messages. sendDocument takes files of up to 50 MB[1], and the text never has to be split.
aiogram 3. BufferedInputFile sends bytes from memory under a file name you choose[13]:
from aiogram.types import BufferedInputFile
if len(text) > 4096:
doc = BufferedInputFile(text.encode("utf-8"), filename="report.txt")
await message.answer_document(doc, caption="The full report")
else:
await message.answer(text)
python-telegram-bot. reply_document accepts bytes, with the name in filename[14]. The library also keeps the limits as constants: MessageLimit.MAX_TEXT_LENGTH is 4096 and MessageLimit.CAPTION_LENGTH is 1024[10]:
from telegram.constants import MessageLimit
if len(text) > MessageLimit.MAX_TEXT_LENGTH:
await update.message.reply_document(
document=text.encode("utf-8"),
filename="report.txt",
caption="The full report",
)
else:
await update.message.reply_text(text)
Keep the caption short: it has its own limit of 1024 characters[1]. For files over 50 MB, see file is too big.
A long caption: send the text after the media
When a description does not fit in 1024 characters, send the photo or video with a short caption — a title, a price — and the full text as an ordinary message right after it, where it has 4096 characters, or split it as above.
Or send a rich message
The Bot API now also has rich messages, sent with sendRichMessage: up to 32768 characters of text with headings, lists, tables and collapsible blocks[1]. If your library has the method, a long structured answer can go in one rich message instead of several plain ones. Check your library’s version before you rely on it.
Catch the error where you cannot check
When the text comes from somewhere you do not control, catch this one error and fall back to a file, and raise everything else.
from aiogram.exceptions import TelegramBadRequest
from aiogram.types import BufferedInputFile
try:
await message.answer(text)
except TelegramBadRequest as e:
if "message is too long" not in e.message and "MESSAGE_TOO_LONG" not in e.message:
raise
await message.answer_document(BufferedInputFile(text.encode("utf-8"), filename="message.txt"))
aiogram raises Telegram’s 400 as TelegramBadRequest, with Telegram’s description in message[6][7]. python-telegram-bot raises BadRequest[9], removes the Bad Request: prefix and capitalizes what is left[8], so compare e.message.lower() with "message is too long". In grammY and Telegraf, test the error’s description[11][12].
On Livops
This error happens while the bot runs, when one handler builds a message that is too long; the deploy can be green while one command fails for long answers only.
- Logs. The error line, with the handler it came from, is on the project’s Logs page.
livops logs <service> -ffollows it from the terminal; see CLI. Over MCP,get_logsreturns up to 5000 lines. - Log the length, not the text. When you fall back to a file or split, log the length of the text and where it came from. A 30,000-character answer copied into every log line makes the log hard to read.
- Ship the fix with a push. Every
git pushto the project’s branch starts a new deploy; push the splitter or the fallback, and the new version replaces the old one.
A bot costs 19 credits a month (19,000 so’m); see Pricing.
Questions
What is the maximum message length for a Telegram bot?
4096 characters of text in one message, counted after entities parsing: the visible text, not the HTML or Markdown tags around it. A caption on a photo, video, document or other media is shorter, 0 to 1024 characters.
Does Telegram count characters or bytes?
Characters. A Cyrillic or Uzbek letter counts as one, the same as a Latin one, so a Russian text gets the same 4096 as an English one. Bytes are the rule for callback_data on buttons, not for message text.
Why do I get message caption is too long instead?
Your text is the caption of a photo, video, document or other media, and captions stop at 1024 characters. Send the media with a short caption, and the long text as a separate message right after it.
Can I just cut the text at 4096 characters?
Only if it is plain text. With HTML or Markdown a blind cut can land inside a tag or between an opening and a closing mark, and Telegram then refuses the part with can't parse entities. Split the plain text at paragraph or line breaks first, then format each part on its own.
How do I send a text that is much longer, like a report or a log?
Send it as a document. Put the text in a .txt file in memory and send it with sendDocument; files up to 50 MB are accepted. The user gets one file instead of a dozen messages, and nothing has to be split.
Is there a setting to raise the 4096 limit for my bot?
No. The limit is part of the Bot API for every bot. Rich messages, sent with sendRichMessage, take up to 32768 characters, if your library supports that method; otherwise split the text or send a file.
Sources
- Telegram Bot API — Making requests, sendMessage, sendPhoto, sendDocument, editMessageText, Rich messages (core.telegram.org). Checked .
- Telegram Bot API server source — telegram-bot-api/Client.cpp (raw.githubusercontent.com). Checked .
- TDLib source — td/telegram/MessageContent.cpp (raw.githubusercontent.com). Checked .
- TDLib source — tdutils/td/utils/utf8.h (raw.githubusercontent.com). Checked .
- Telegram API — messages.sendMessage, possible errors (core.telegram.org). Checked .
- aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Checked .
- aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/error.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/request/_baserequest.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/constants.py (raw.githubusercontent.com). Checked .
- grammY source — src/core/error.ts (raw.githubusercontent.com). Checked .
- Telegraf source — src/core/network/error.ts (raw.githubusercontent.com). Checked .
- aiogram source — aiogram/types/input_file.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/_message.py (raw.githubusercontent.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your botRelated
- Bad Request: message text is empty — Telegram bot error and how to fix itBad Request: message text is empty means your bot called sendMessage or editMessageText with no text: an empty string, a variable that came back empty, or no text parameter at all. Text made only of spaces and line breaks fails too, as text must be non-empty. Check the text before you send, and send a fallback line instead.
- Bad Request: can't parse entities — Telegram bot error and how to fix itBad Request: can't parse entities means Telegram could not read the formatting in your message: with parse_mode set to HTML, Markdown or MarkdownV2, some text — usually a user's name, a username with an underscore, a price with a dot, or an unclosed tag — breaks the markup. Escape that text for the parse mode you use, send entities instead of parse_mode, or send it without parse_mode.
- Bad Request: BUTTON_DATA_INVALID — Telegram bot error and how to fix itBad Request: BUTTON_DATA_INVALID means Telegram refused the callback_data of an inline keyboard button, almost always because it is longer than 64 bytes. The limit is in bytes, not characters: a Cyrillic letter takes 2 bytes and an emoji 3 or 4, so 40 characters can be too long. Put a short id in the button and keep the rest on your server, or use aiogram's CallbackData or python-telegram-bot's arbitrary_callback_data.
- Bad Request: file is too big — Telegram bot file size limits and how to get around themBad Request: file is too big means the bot called getFile for a file over the Bot API's 20 MB download limit. Request Entity Too Large (413) is the upload side: a file uploaded over the 50 MB limit. Resend by file_id, which has no limit, compress or split the file, or run a Local Bot API Server, which downloads without a size limit and uploads up to 2000 MB.
- Telegram 429: Too Many Requests, flood control: retry after N — how to fix itTelegram flood control (429 Too Many Requests) is telling your bot to slow down: wait the number of seconds in retry_after, then send the same request again. It comes from sending too fast — more than about one message a second to one chat, 20 a minute to a group, or about 30 a second in a broadcast. Wait and retry in code, and send broadcasts from one queue at a steady pace.
- Telegram bot hosting in 2026: the options comparedA Telegram bot needs a process that never stops, or a public HTTPS address for a webhook. On Livops it runs from a GitHub push for 19 credits a month (19,000 so'm). Here is how a VPS, Railway, Render, Fly.io and Vercel compare.
- aiogram bot hosting: how to deploy an aiogram 3 botAn aiogram 3 bot needs one process that never stops, the token in an environment variable, state kept outside memory and a clean exit on SIGTERM. On Livops you push a repository with bot.py and requirements.txt, and it runs for 19 credits a month (19,000 so'm), polling or webhook.
- python-telegram-bot hosting: deploying a v22 botA python-telegram-bot bot runs as one Application: run_polling() for polling, run_webhook() with the webhooks extra for a webhook. Both stop cleanly on SIGTERM. On Livops it runs from a push with bot.py and requirements.txt for 19 credits a month (19,000 so'm).
- grammY bot deploy: polling, webhooks and hostingDeploy a grammY bot as one always-on Node.js process: bot.start() for polling, or webhookCallback() behind an HTTP server, with bot.stop() on SIGTERM. On Livops a repository with grammy in package.json runs as a bot from every push, for 19 credits a month (19,000 so'm).
- Telegraf bot hosting: deploying a Telegraf 4 bot on Node.jsA Telegraf bot is one Node.js process: bot.launch() for polling, or bot.webhookCallback() behind an HTTP server for a webhook, with bot.stop() on SIGTERM. On Livops a repository with telegraf in package.json is run as a bot from every push, for 19 credits a month (19,000 so'm).