Telegram Bot API Errors: What Each Error Means and How to Fix It
Telegram Bot API errors come back as JSON with "ok": false, a numeric error_code such as 400, 403 or 429, and a human-readable description like Bad Request: chat not found. Most of them have one of a dozen well-known causes: a wrong chat id, a user who blocked the bot, a second bot instance, or too many messages per second. Below is the response format, a table of the most common errors with fixes, grouped by code, and copy-paste handling code in Python and JavaScript that respects retry_after and migrate_to_chat_id.
Error response format
Every Bot API response is a JSON object with a Boolean ok. On success the data is in result; on failure you get this instead:
{
"ok": false,
"error_code": 400,
"description": "Bad Request: chat not found"
}
| Field | Meaning |
|---|---|
ok | false for every failed request. |
error_code | Integer, mirrors the HTTP status: 400, 401, 403, 404, 409, 413, 429, 5xx. |
description | Plain-text explanation, usually prefixed with the status name: Bad Request:, Forbidden:, Conflict:. |
parameters | Optional ResponseParameters that help handle the error automatically: retry_after (seconds to wait after flood control) and migrate_to_chat_id (the new id of a group that became a supergroup). |
Two responses with parameters you should handle in code:
{"ok": false, "error_code": 429, "description": "Too Many Requests: retry after 35", "parameters": {"retry_after": 35}}
{"ok": false, "error_code": 400, "description": "Bad Request: group chat was upgraded to a supergroup chat", "parameters": {"migrate_to_chat_id": -1001234567890}}
Don't build logic on description text
Telegram doesn't publish a complete list of Bot API error messages. The descriptions in this guide are the texts the API returns today, but they are plain text for humans and may change without notice. The official docs even say the contents of error_code are subject to change. A robust bot therefore:
- branches on
error_codefirst (400, 403, 429, 5xx); - relies on
parameters.retry_afterandparameters.migrate_to_chat_idwhenever they are present, rather than parsing numbers out of the description; - matches description substrings only where it must tell apart errors with the same code, case-insensitively, with a safe fallback when nothing matches;
- logs the full description, so new messages show up in your logs instead of being swallowed.
400 Bad Request: common Telegram errors
A Telegram error 400 Bad Request means the request reached the API but something in it is wrong: a parameter, the target chat or the state of the message.
| Description | Cause | Fix |
|---|---|---|
chat not found | Wrong chat_id, a group id without -100, a user who never started the bot, a bot that isn't in the group or channel, or a production id used on the test server. | Message the bot (or add it to the chat) and copy the id from getUpdates; see the chat id guide. |
PEER_ID_INVALID | The id is malformed or points to a chat the bot has never interacted with. | Same as chat not found: get a fresh id from an update. |
message is not modified | An edit method was called with exactly the same text and reply markup the message already has. Typical when a user presses the same button twice. | Compare before editing, or catch and ignore this error. |
message to edit not found | Wrong message_id/chat_id pair, or the message was deleted. | Store the message_id returned by the send method together with its chat id. |
message can't be edited | The message wasn't sent by the bot, or it can no longer be edited. | Send a new message instead of editing. |
can't parse entities: … | Broken parse_mode markup: an unescaped < or & in HTML, or one of _ * [ ] ( ) ~ ` > # + - = | { } . ! unescaped in MarkdownV2. The text after the colon points to the byte offset. | Escape user-provided text, or send it without parse_mode. |
message text is empty | text is missing or empty, often a JSON body sent without Content-Type: application/json. | Check the value and the request encoding. |
wrong file identifier/HTTP URL specified | A file_id from another bot (file ids are tied to one bot), or a URL Telegram can't download or that exceeds the by-URL limits (5 MB for photos, 20 MB for other files). | Re-upload the file as multipart/form-data, or use a public direct link. |
query is too old and response timeout expired or query ID is invalid | answerCallbackQuery or answerInlineQuery was called too late, twice, or with a wrong id. | Answer right at the start of the handler, before slow work; after a restart, skip stale callback queries. |
not enough rights to send text messages to the chat (photos, documents…) | The bot is restricted in the group or has no posting rights in the channel. | Give the bot the needed permission or admin rights. |
group chat was upgraded to a supergroup chat | The basic group became a supergroup and got a new id, returned in parameters.migrate_to_chat_id. | Save the new id and repeat the request with it. |
BUTTON_DATA_INVALID and other reply markup errors | callback_data outside 1–64 bytes (non-Latin characters take 2–4 bytes each), or a malformed reply_markup. | Store long payloads on your server and put a short key into callback_data. |
member list is inaccessible | A member-related method was called where the bot can't read the member list, typically a channel where it isn't an administrator. | Make the bot an administrator, or don't query members there. |
To reproduce an error safely, open sendMessage in the Bot API Tester, enter a made-up chat_id and look at the raw JSON answer.
401 Unauthorized and 404 Not Found
401 Unauthorized: the token is wrong or was revoked. It also happens when a production token is sent to the test server or vice versa. Check the token withgetMe; if it leaked and was revoked, take the new one from @BotFather.404 Not Found: the URL doesn't matchhttps://api.telegram.org/bot<token>/METHOD_NAME. Typical causes: a missingbotprefix before the token, a token with spaces or line breaks, or a misspelled method name. Method names are case-insensitive, sosendmessageworks, butsendMesagedoes not.
403 Forbidden: bot was blocked by the user and similar errors
Error 403 means the bot is not allowed to write to this chat. Retrying won't help; update your data instead.
| Description | What happened | What to do |
|---|---|---|
bot was blocked by the user | The user blocked or stopped the bot. | Mark the user inactive and stop messaging them. In private chats the bot also receives a my_chat_member update when it is blocked or unblocked. |
bot can't initiate conversation with a user | The user has never opened the bot. Bots can't write first. | Ask the user to press Start, for example with a t.me/your_bot link. |
bot is not a member of the channel chat | The bot isn't in the channel. | Add the bot to the channel as an administrator with posting rights. |
bot was kicked from the group chat | The bot was removed from the group (the supergroup variant mentions the supergroup chat). | Remove the chat from your list or ask an admin to add the bot again. |
user is deactivated | The account was deleted. | Delete the user from your mailing list. |
409 Conflict in getUpdates
Conflict: terminated by other getUpdates request; make sure that only one bot instance is running— two processes poll with the same token: a forgotten terminal, a second container, a deploy that started before the old one stopped. Keep exactly one poller per token.Conflict: can't use getUpdates method while webhook is active; use deleteWebhook to delete the webhook first— the bot has a webhook, and getUpdates doesn't work while one is set. CalldeleteWebhook, or keep the webhook and stop polling.
413, 429 and 5xx errors
413 Request Entity Too Large: the upload is bigger than the API accepts. Bots can upload up to 50 MB throughapi.telegram.org; a local Bot API server raises that to 2000 MB.429 Too Many Requests: retry after N: flood control. Waitparameters.retry_afterseconds and repeat. Then slow down: about 1 message per second per chat, 20 per minute in a group, about 30 per second in total. The numbers and queueing strategies are in the limits guide.500,502 Bad Gatewayand other 5xx: a problem on Telegram's side or on the way to it. Retry with exponential backoff. The body of a 502 can be a non-JSON page, so don't assumeresponse.json()always succeeds.
Error handling code with retry_after and migrate_to_chat_id
This wrapper retries 429 after retry_after, follows migrate_to_chat_id, backs off on 5xx and network errors, and raises a typed error for everything else so the caller can decide. Python uses requests; the JavaScript version needs Node.js 18+ and runs as an .mjs file.
import os
import time
import requests
TOKEN = os.environ["BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"
class TelegramError(Exception):
def __init__(self, method, code, description, parameters=None):
super().__init__(f"{method}: {code} {description}")
self.code = code
self.description = description
self.parameters = parameters or {}
def call(method, max_retries=5, **params):
for attempt in range(max_retries):
try:
data = requests.post(f"{API}/{method}", json=params, timeout=40).json()
except (requests.RequestException, ValueError):
# network error or a non-JSON answer (e.g. an HTML 502 page)
time.sleep(2 ** attempt)
continue
if data.get("ok"):
return data["result"]
code = data.get("error_code")
extra = data.get("parameters") or {}
if "retry_after" in extra: # 429 flood control: wait as told
time.sleep(extra["retry_after"])
continue
if "migrate_to_chat_id" in extra and "chat_id" in params:
print(f"chat {params['chat_id']} migrated to {extra['migrate_to_chat_id']}: update your database")
params["chat_id"] = extra["migrate_to_chat_id"]
continue
if code is not None and code >= 500: # Telegram-side problem: back off
time.sleep(2 ** attempt)
continue
raise TelegramError(method, code, data.get("description", ""), extra)
raise TelegramError(method, None, "gave up after retries")
def notify(chat_id, text):
try:
return call("sendMessage", chat_id=chat_id, text=text)
except TelegramError as e:
if e.code == 403:
# blocked, kicked or deactivated: stop messaging this chat
print(f"chat {chat_id} is unreachable: {e.description}")
elif e.code == 400 and "chat not found" in e.description.lower():
print(f"wrong chat id {chat_id}")
else:
raise
notify(123456789, "Hello!")const TOKEN = process.env.BOT_TOKEN;
const API = `https://api.telegram.org/bot${TOKEN}`;
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
class TelegramError extends Error {
constructor(method, code, description, parameters = {}) {
super(`${method}: ${code} ${description}`);
this.code = code;
this.description = description;
this.parameters = parameters;
}
}
async function call(method, params = {}, maxRetries = 5) {
params = { ...params };
for (let attempt = 0; attempt < maxRetries; attempt++) {
let data;
try {
const res = await fetch(`${API}/${method}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
signal: AbortSignal.timeout(40_000),
});
data = await res.json();
} catch {
// network error or a non-JSON answer (e.g. an HTML 502 page)
await sleep(2 ** attempt);
continue;
}
if (data.ok) return data.result;
const code = data.error_code;
const extra = data.parameters ?? {};
if (extra.retry_after !== undefined) { // 429 flood control: wait as told
await sleep(extra.retry_after);
continue;
}
if (extra.migrate_to_chat_id !== undefined && "chat_id" in params) {
console.log(`chat ${params.chat_id} migrated to ${extra.migrate_to_chat_id}: update your database`);
params.chat_id = extra.migrate_to_chat_id;
continue;
}
if (code >= 500) { // Telegram-side problem: back off
await sleep(2 ** attempt);
continue;
}
throw new TelegramError(method, code, data.description ?? "", extra);
}
throw new TelegramError(method, null, "gave up after retries");
}
async function notify(chatId, text) {
try {
return await call("sendMessage", { chat_id: chatId, text });
} catch (err) {
if (!(err instanceof TelegramError)) throw err;
if (err.code === 403) {
// blocked, kicked or deactivated: stop messaging this chat
console.log(`chat ${chatId} is unreachable: ${err.description}`);
} else if (err.code === 400 && err.description.toLowerCase().includes("chat not found")) {
console.log(`wrong chat id ${chatId}`);
} else {
throw err;
}
}
}
await notify(123456789, "Hello!");One caveat: a request that timed out on your side may still have been processed, so retrying a send after a network error can occasionally deliver a message twice.
Debugging checklist
- Log the full JSON of every failed response:
error_code,descriptionandparameters. - Check the token with getMe in the Bot API Tester: 401 means the token itself is the problem.
- For
chat not foundand 403 errors, callgetUpdatesand compare the realchat.idwith the one in your config. - For 409, look for a second running instance and check
getWebhookInfo.
Related guides: how to get a Telegram chat id, sending messages and parse_mode escaping, Telegram Bot API limits and 429 handling and setting up a webhook.
Frequently asked questions
What does “Bad Request: chat not found” mean in Telegram?
The bot can't see the chat behind your chat_id: the id is wrong or lacks the -100 prefix, the user never started the bot, or the bot isn't a member of the group or channel. Message the bot first and take the id from getUpdates.
How do I handle “Forbidden: bot was blocked by the user”?
You can't fix it from the bot side: the user blocked the bot. Catch error code 403, mark the user as inactive in your database and stop sending to them until they write to the bot again.
Why does getUpdates return 409 Conflict?
Either another process is polling with the same token (terminated by other getUpdates request) or a webhook is set (can't use getUpdates method while webhook is active). Stop the second instance or call deleteWebhook.
How long should I wait after 429 Too Many Requests?
Exactly as long as parameters.retry_after says, in seconds, then repeat the request. Don't retry immediately and don't hardcode a delay: the value changes from response to response.
Should my code check the error description text?
As little as possible. The description is a human-readable string that Telegram may change. Branch on error_code and parameters first, and use case-insensitive substring checks on the description only where you need to tell two errors with the same code apart.
What does 401 Unauthorized mean in the Bot API?
The token is invalid: it was mistyped, revoked in @BotFather, or belongs to the other environment (production vs test server). Check it with getMe and get the current token via /mybots → API Token.
Related guides
How to Create a Telegram Bot: Step by Step with BotFather and Python
How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.
How to Deploy a Telegram Bot: VPS, Docker and Serverless Hosting
How to deploy a Telegram bot: polling vs webhook, a systemd service on a VPS, Docker, Cloudflare Workers with secret_token, plus a launch checklist.
Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More
What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.
Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length
Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.
Telegram Bot Commands: setMyCommands, Command Scopes and /start Deep Links
Set up Telegram bot commands: @BotFather /setcommands, setMyCommands with scopes and languages, /start deep link parameters and /cmd@bot in groups.
Telegram Bot Keyboards: Inline Keyboard, Callback Buttons and Reply Keyboard
Add Telegram bot buttons: inline keyboard with callback_data, answerCallbackQuery, editing the message after a press, reply keyboard and ForceReply.
n8n Telegram Integration: Connect a Telegram Bot, Trigger Workflows and Send Messages
Connect n8n to Telegram: bot token as Access Token, Telegram Trigger webhook over public HTTPS, sending messages by chat id, and fixes for common errors.
How to Send a Message with the Telegram Bot API (sendMessage)
Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.
Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe
Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.
How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting
Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.
How to Get a Telegram Chat ID for a User, Group, Channel or Topic
How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.
Telegram Inline Bot: How to Enable Inline Mode and Answer Inline Queries
Build a Telegram inline bot: enable inline mode with @BotFather or setMySettings, handle inline_query updates and reply with answerInlineQuery.
Telegram Stars Payments for Bots: Invoices, Pre-Checkout, Refunds and Subscriptions
Accept Telegram Stars payments in your bot: sendInvoice with XTR, pre_checkout_query, successful_payment, refunds, subscriptions, Python/JS code.
Telegram Test Server: How to Test a Bot in the Telegram Test Environment
Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.
Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button
Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.
TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits
TelegramWidget JavaScript API reference: properties, request(), events, error codes, CSS variables, widget_query and answerWidgetQuery, plus every limit.
Telegram Widget Examples: Complete HTML and Python Bot Code
Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.
Telegram Widgets: Interactive HTML Inside Bot Messages
Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.
How to Test a Telegram Mini App: From Browser Mock to Real Telegram
Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.