Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

Telegram 400: Bad Request: PEER_ID_INVALID — what it means and how to fix it

Bad Request: PEER_ID_INVALID is Telegram's own error code, passed on unchanged by the Bot API server: Telegram's servers did not accept the user or chat id in the request. For a bot it usually means a user id the bot has never received in an update, such as a user who never wrote to this bot or an id taken from another bot or account, or an id that is not the one you meant. Use ids from your own bot's updates, check the id's shape, and catch the error where one bad id should not stop the rest.

By Livops team, the people who build and run LivopsUpdated

The error, as the Telegram Bot API returns it[1]:

{"ok":false,"error_code":400,"description":"Bad Request: PEER_ID_INVALID"}

Each library wraps it in its own words:

Library What you see
aiogram 3 TelegramBadRequest: Telegram server says - Bad Request: PEER_ID_INVALID[14][15]
python-telegram-bot telegram.error.BadRequest: Peer_id_invalid[16]
grammY GrammyError: Call to 'banChatMember' failed! (400: Bad Request: PEER_ID_INVALID)[17]
Telegraf TelegramError: 400: Bad Request: PEER_ID_INVALID[18]

python-telegram-bot removes Bad Request: and capitalizes what is left with Python’s str.capitalize[16], so the upper-case code comes out as Peer_id_invalid. This page explains where the error comes from, how it differs from chat not found, the checks that find the cause, and how to handle it in code and on Livops.

What does the error mean?

A peer is a user, a group or a channel. PEER_ID_INVALID is not a Bot API message but an error of Telegram’s own API, which its documentation describes as “The provided peer id is invalid.”[2] Telegram’s error types are upper-case names like this one, and a 400 means the query contains errors[3].

The Bot API server is a program that runs your bot’s requests through TDLib against Telegram’s servers. When an error comes back from Telegram, the server turns a 404 into a 400, keeps an upper-case code as it is, and puts Bad Request: in front[1]. That is why you see a raw code here, where most Bot API errors are sentences.

So the request got past the Bot API server’s own checks, and Telegram’s servers refused the user or chat id in it. Telegram’s API lists PEER_ID_INVALID among the possible errors of sending a message, banning or restricting a member, promoting one, answering a join request, setting a game score and reading a user’s boosts[2][8][9][10][11][12]. Telegram says the numeric error_code may change in the future[6], so match on the description.

PEER_ID_INVALID or chat not found?

The two come from different places, and that tells you where to look:

  • Bad Request: chat not found is the Bot API server’s own answer. Before a method runs, the server looks up its chat_id; if the lookup fails, it answers chat not found and Telegram is never asked to do the action[1]. The causes — a user who never pressed Start, a channel id without -100, an @username for a person — are on Bad Request: chat not found.
  • Bad Request: PEER_ID_INVALID comes later, from Telegram’s servers, about an id the Bot API server passed on.

The Bot API server does not check every id the same way. For the user_id of banChatMember, unbanChatMember, restrictChatMember, promoteChatMember, getChatMember, approveChatJoinRequest, declineChatJoinRequest, setGameScore, getGameHighScores and getUserChatBoosts, it does not require that the bot already knows the user: it hands the request on either way[1]. Other methods check first and answer user not found for a user the bot does not know — getUserProfilePhotos does[1]. A send method with allow_paid_broadcast also skips the lookup for a positive (user) chat_id[1]. And the sender_chat_id of banChatSenderChat and unbanChatSenderChat is passed on without a lookup failure too[1].

Causes and checks

1. The bot has never received this user

A Bot API user id is the user’s Telegram id, the same number for every bot[5]. What differs is what each bot’s server knows: the Bot API server keeps the users that reached it through updates[1]. For a user TDLib has no record of, a bot sends the id with an empty access hash (0)[4], and it is then up to Telegram’s servers whether to accept it.

So an id from somewhere other than this bot’s own updates is the first thing to check:

  • a user who never wrote to this bot — bots cannot start conversations; a user must add the bot to a group or send it a message first[7];
  • an id collected by another bot, by a user account or a script logged in as one, or exported from a CRM or a web form;
  • an id stored by a test bot and used with the production bot’s token, or the other way round.

Fix: take user ids from this bot’s updates — the message, callback query, chat_member or chat_join_request update that carries the user — and store them as they arrive. For a user who has not written to the bot yet, send them the bot’s link first; chat not found shows how, and how to check which bot a token belongs to with getMe.

2. The id is not the one you meant

Check the id’s shape against Telegram’s own ranges[5]:

The id is Range in the Bot API
a user positive, 1 to 1099511627775
a basic group negative: minus the group’s id
a supergroup or channel -1000000000001 to -1997852516352, so today’s ids start with -100

A user_id that is zero, negative or not a number does not reach Telegram at all: the Bot API server answers Bad Request: invalid user_id specified[1]. So if you see PEER_ID_INVALID for a user_id, the value was read as a positive number, and the question is whether it is the right one:

  • A chat id in a user field. A channel id copied without its -100 and its minus sign is a positive number, and a user_id field takes it as a user. Check which id each parameter expects.
  • An id cut to 32 bits. Ids may have more than 32 significant bits but at most 52, so a 64-bit integer or a double-precision float is safe[6][5]. A JavaScript number is a double and holds them exactly; a 32-bit INT column or variable does not, and turns the id into another number. Store ids as BIGINT.
  • Number or string. chat_id is documented as Integer or String[6], so sending the digits as a string is not the problem in itself; the digits are. Print the exact value you send, with quotes, to see a stray space or a wrong variable.

For a chat_id, a wrong id usually fails earlier, as chat not found[1]; see that page for channel ids and -100.

3. A channel the bot does not know, in sender_chat_id

banChatSenderChat and unbanChatSenderChat pass sender_chat_id on even when the bot has never seen that chat[1], and for an unknown channel a bot sends the id with an empty access hash[13]. Use the sender_chat.id from the message the channel sent in your group, not an id typed in by hand.

How to handle it in code

The same id gives the same answer every time, so retrying does not help. Where the bot works through a list — a broadcast, a clean-up of members, a batch of join requests — catch this one error, log the id, skip it, and raise everything else.

aiogram 3. Telegram’s 400 is TelegramBadRequest, with Telegram’s description in message[14][15]:

from aiogram.exceptions import TelegramBadRequest

try:
    await bot.ban_chat_member(chat_id, user_id)
except TelegramBadRequest as e:
    if "PEER_ID_INVALID" not in e.message:
        raise
    logging.warning("PEER_ID_INVALID for user_id=%s in chat_id=%s", user_id, chat_id)

python-telegram-bot. Telegram’s 400 is BadRequest, and the message arrives as Peer_id_invalid, so compare in lower case[16]:

from telegram.error import BadRequest

try:
    await context.bot.ban_chat_member(chat_id, user_id)
except BadRequest as e:
    if "peer_id_invalid" not in e.message.lower():
        raise
    logging.warning("PEER_ID_INVALID for user_id=%s in chat_id=%s", user_id, chat_id)

grammY. API errors are GrammyError, with Telegram’s description[17]:

import { GrammyError } from "grammy";

try {
  await bot.api.banChatMember(chatId, userId);
} catch (e) {
  if (!(e instanceof GrammyError && e.description.includes("PEER_ID_INVALID"))) throw e;
  console.warn(`PEER_ID_INVALID for user_id=${userId} in chat_id=${chatId}`);
}

Telegraf. API errors are TelegramError, with a description getter[18]:

import { TelegramError } from "telegraf";

try {
  await bot.telegram.banChatMember(chatId, userId);
} catch (e) {
  if (!(e instanceof TelegramError && e.description.includes("PEER_ID_INVALID"))) throw e;
  console.warn(`PEER_ID_INVALID for user_id=${userId} in chat_id=${chatId}`);
}

Logging the method, the chat_id and the user_id together is what lets you tell the causes apart afterwards: an id that came from another bot, a test bot’s id, or a number that was cut.

On Livops

This error happens while the bot runs, when it calls the Bot API; a deploy does not make those calls, so it can be green while one fails.

  • Logs. The error line is on the project’s Logs page, and livops logs <service> -f follows it from the terminal; see CLI. Over MCP, get_logs returns up to 5000 lines.
  • The token is a variable. Put BOT_TOKEN under Variables and mark it as a secret. New values take effect on the next deploy; restart the service to apply them now. See Variables.
  • Staging copies the variables. A new environment such as staging gets copies of production’s services and variables. Give it its own test bot’s token; then its users are that bot’s, and user ids stored by the production bot are not ones the test bot has received. See Environments.
  • Store ids in PostgreSQL. Add PostgreSQL under Databases, and its address is written as a variable to every service in the environment. Store user and chat ids as BIGINT. A file written next to the code is gone after the next deploy.

A bot costs 19 credits a month; see Pricing.

Questions

What does PEER_ID_INVALID mean?

A peer is a user, group or channel. PEER_ID_INVALID is Telegram's own error, which its API documentation describes as the provided peer id is invalid. The Bot API server passes it on unchanged, as Bad Request: PEER_ID_INVALID, when Telegram's servers refuse the id in your request.

How is it different from chat not found?

Chat not found comes from the Bot API server itself, when it cannot look up the chat_id before doing anything. PEER_ID_INVALID comes from Telegram's servers, after the Bot API server has passed the request on, which it does for example with the user_id of banChatMember, getChatMember or approveChatJoinRequest without checking that the bot knows the user.

Why does python-telegram-bot show Peer_id_invalid?

python-telegram-bot removes the Bad Request: prefix and capitalizes the rest with Python's str.capitalize, which also lowercases everything after the first letter. Peer_id_invalid is the same PEER_ID_INVALID error.

Can my bot use a user id it got from another bot?

The number is the same everywhere, since a Bot API user id equals the user's Telegram id. But the bot's server only has the users it has received in updates; for any other user it sends the id without the access data it would normally have, and Telegram can refuse it. Have the user write to this bot first, and store the id from this bot's update.

Is a chat id too big for JavaScript?

No. Telegram says chat and user ids have at most 52 significant bits, so a 64-bit integer or a double-precision float, which is what a JavaScript number is, holds them exactly. A 32-bit integer does not: store ids as BIGINT.

Should I retry on PEER_ID_INVALID?

No. The same id gives the same answer. Log it with the method and the id, skip that user or chat, and fix where the id came from.

Sources

  1. Telegram Bot API server source — telegram-bot-api/Client.cpp (raw.githubusercontent.com). Checked .
  2. Telegram API — messages.sendMessage (possible errors) (core.telegram.org). Checked .
  3. Telegram API — Error handling (core.telegram.org). Checked .
  4. TDLib source — td/telegram/UserManager.cpp (raw.githubusercontent.com). Checked .
  5. Telegram API — Bot API dialog IDs (core.telegram.org). Checked .
  6. Telegram Bot API — Making requests, sendMessage, banChatMember, User, Chat (core.telegram.org). Checked .
  7. Telegram — Bots, an introduction for developers (core.telegram.org). Checked .
  8. Telegram API — channels.editBanned (possible errors) (core.telegram.org). Checked .
  9. Telegram API — channels.editAdmin (possible errors) (core.telegram.org). Checked .
  10. Telegram API — messages.hideChatJoinRequest (possible errors) (core.telegram.org). Checked .
  11. Telegram API — messages.setGameScore (possible errors) (core.telegram.org). Checked .
  12. Telegram API — premium.getUserBoosts (possible errors) (core.telegram.org). Checked .
  13. TDLib source — td/telegram/ChatManager.cpp (raw.githubusercontent.com). Checked .
  14. aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Checked .
  15. aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Checked .
  16. python-telegram-bot source — telegram/error.py (raw.githubusercontent.com). Checked .
  17. grammY source — src/core/error.ts (raw.githubusercontent.com). Checked .
  18. Telegraf source — src/core/network/error.ts (raw.githubusercontent.com). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your bot

Got a question? — @livops_uz