Telegram 400: Bad Request: chat not found — cómo solucionarlo
El bot le pidió a Telegram un chat que no conoce. O el chat_id es incorrecto (una errata, un id de canal sin su prefijo -100, el @username de un usuario, un id recortado a 32 bits), o es correcto pero este bot nunca ha estado en ese chat: el usuario nunca pulsó Start, el bot nunca se añadió al grupo o al canal, o el token pertenece a otro bot.
Por El equipo de Livops, las personas que construyen y operan LivopsActualizado el
El error, tal como lo devuelve la Bot API de Telegram con el código de error 400[2]:
Bad Request: chat not found
Cada biblioteca lo envuelve con sus propias palabras:
| Biblioteca | Lo que ves |
|---|---|
| aiogram 3 | TelegramBadRequest: Telegram server says - Bad Request: chat not found[6][7] |
| python-telegram-bot | telegram.error.BadRequest: Chat not found[9][10] |
| grammY | GrammyError: Call to 'sendMessage' failed! (400: Bad Request: chat not found)[11] |
| Telegraf | TelegramError: 400: Bad Request: chat not found[12] |
python-telegram-bot quita el prefijo Bad Request: y pone en mayúscula el resto[9], por eso su mensaje se ve distinto. Esta página explica qué significa el error, enumera las causas de la más común a la menos, muestra cómo encontrar el chat_id correcto de un usuario, un grupo y un canal, y qué revisar cuando el bot se ejecuta en Livops.
¿Qué significa el error?
Todos los métodos que envían a un chat reciben un chat_id: un id entero, o un nombre de usuario en la forma @username para un bot, un supergrupo o un canal[1]. Antes de enviar nada, el servidor de la Bot API busca el chat para este bot. Si el bot no conoce el id, o el @username no corresponde a un chat al que se pueda dirigir por nombre, responde Bad Request: chat not found[2].
Así que hay dos familias de causas: el chat_id no es el id que querías, o es el id correcto y este bot no tiene acceso a ese chat. Un chat que el servidor sí encuentra pero en el que el bot no está da otro error, un 403: Forbidden: bot was kicked from the channel chat, Forbidden: bot is not a member of the supergroup chat, etc.[2]; lo cubre Forbidden: bot was blocked by the user.
Causas, de la más común a la menos
1. El usuario nunca inició el bot
Los bots no pueden iniciar conversaciones con usuarios: el usuario tiene que añadir el bot a un grupo o enviarle antes un mensaje[4]. Un id de usuario que conseguiste por otra vía (un formulario, un CRM, otro bot, un grupo en el que está el usuario) es un id real, pero el bot todavía no tiene un chat privado con esa persona. Envíale el enlace del bot, https://t.me/<bot_username>[5], y guarda su chat id cuando escriba. Un 403 relacionado, bot can't initiate conversation with a user[8], significa lo mismo para un usuario que el bot ya conoce.
2. Un id de canal o de supergrupo sin -100
La Bot API convierte el id interno de un canal o de un supergrupo en -(1000000000000 + id), así que todos esos ids son negativos, entre -1000000000001 y -1997852516352, y los actuales empiezan por -100; los ids de los grupos básicos son simplemente negativos; los de los usuarios son positivos[3]. Las herramientas y los clientes web que muestran el número interno te dan 1234567890, mientras que el bot tiene que enviar a:
-1001234567890
Escribir 1234567890 o -1234567890 apunta a otro chat, o a ninguno.
3. Un @username donde solo vale un id
@username se acepta para canales, supergrupos y bots[1]. Para un chat privado con una persona, el servidor de la Bot API solo admite un nombre de usuario cuando el destino es un bot, y en otro caso responde chat not found[2]. Envía al id numérico del usuario. El nombre de usuario de un canal también necesita la @: @mychannel, no mychannel ni t.me/mychannel.
4. El bot no está en el grupo o en el canal
Un bot que nunca se añadió a un grupo o canal privado no lo conoce, así que su id da chat not found. Un canal o supergrupo público se puede encontrar por su @username, y entonces la respuesta es un 403: Forbidden: bot is not a member of the channel chat; un bot que fue eliminado recibe Forbidden: bot was kicked from the channel chat[2]. En cualquier caso, añade el bot; en un canal, hazlo administrador con permiso para publicar mensajes[1].
5. El token de otro bot
Los chats son de cada bot. El usuario A inició @shop_bot, y el código envía con el token de @shop_test_bot: el id es el id real de A, pero el bot de pruebas nunca ha hablado con A. Es habitual cuando staging y producción usan bots distintos, o después de cambiar el token del entorno. Comprueba a qué bot pertenece el token:
curl -s "https://api.telegram.org/bot$BOT_TOKEN/getMe"
getMe devuelve el username del bot; tiene que ser el bot que inició el usuario.
6. El id se recortó o se estropeó
Los chat ids pueden tener más de 32 bits significativos, pero como mucho 52, así que un entero con signo de 64 bits o un double son seguros para ellos[1]. Una columna INT de 32 bits o un tipo entero de 32 bits estropea en silencio un id grande. En SQL, usa BIGINT. E imprime el valor que envías de verdad, comillas incluidas: un CHAT_ID definido en el entorno con comillas o con un espacio al final no es el número que crees.
7. Un grupo pasó a ser supergrupo
Cuando un grupo básico se convierte en supergrupo, recibe un id nuevo; el antiguo falla con otro error, Bad Request: group chat was upgraded to a supergroup chat, y el campo parameters.migrate_to_chat_id de la respuesta lleva el id nuevo[2][1]. Guarda ese id y úsalo a partir de entonces.
Cómo encontrar el chat_id correcto
Un usuario. Haz que pulse Start o escriba al bot, y lee message.chat.id del update. Guárdalo cuando llegue (en tu handler de /start) en lugar de buscarlo más tarde. Telegram también envía un update my_chat_member en un chat privado cuando el usuario bloquea o desbloquea el bot[1].
Un grupo. Añade el bot, envía un mensaje en el grupo y lee message.chat.id. Es negativo.
Un canal. Añade el bot como administrador. Si el canal es público, pide su id por el nombre de usuario: getChat acepta @username para un supergrupo o un canal[1]:
curl -s "https://api.telegram.org/bot$BOT_TOKEN/getChat?chat_id=@mychannel"
El result.id empieza por -100. Para un canal privado, publica algo en él y lee channel_post.chat.id del update[1].
Leer los updates a mano con getUpdates solo funciona mientras nada más los recibe: falla mientras hay un webhook configurado, y entra en conflicto con un bot en ejecución que hace polling con el mismo token; consulta Conflict: terminated by other getUpdates request. Lo más sencillo en un bot en ejecución es registrar chat.id en un handler.
Cómo confirmar la solución
Envía un mensaje con el id y el token exactos que usa la app:
curl -s "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
--data-urlencode "chat_id=$CHAT_ID" \
--data-urlencode "text=test"
"ok":true significa que la pareja funciona y que el problema está en cómo construye el id el código. Si vuelve a salir chat not found, el id o el bot son incorrectos: ejecuta getMe y la búsqueda de arriba, y compara.
En Livops
- El id y el token son variables. Pon
BOT_TOKENy, para un destino fijo como un chat de administración o un canal,CHAT_IDen Variables, sin comillas. Los valores nuevos se aplican en el siguiente despliegue; para aplicarlos ya, reinicia el servicio. Marca el token como secreto, y su valor no se vuelve a mostrar nunca, solo su nombre. - Staging copia las variables. Un entorno nuevo, como
staging, recibe copias de los servicios y las variables de producción. Dale el token de su propio bot de pruebas, o las dos copias harán polling con un mismo token y entrarán en conflicto. Una vez que tiene un bot de pruebas, sus usuarios y sus chats son los de ese bot, y un chat id de producción dachat not foundallí. - Un worker puede usar las variables del bot. La variable de un worker puede tomar su valor de la variable de otro servicio por referencia, así que un proceso que envía mensajes en el mismo proyecto usa el mismo token sin copiarlo; consulta Variables.
- Chat ids en PostgreSQL. Añade PostgreSQL en Databases, y
DATABASE_URLse escribe en todos los servicios del entorno. Guarda los chat ids comoBIGINT. Un archivo junto al código desaparece en el siguiente despliegue. - Logs. Registra el
chat_idy el nombre de usuario del bot junto a cada envío fallido; la página Logs del proyecto ylivops logs <service> -flos muestran. El asistente ve el log de un despliegue fallido y los nombres de las variables, nunca sus valores, así que puede señalar unCHAT_IDque falta, pero no uno incorrecto.
Un bot, un worker o un servicio cron cuesta 19 créditos al mes (19,000 so’m); consulta Precios.
Preguntas
¿Puede un bot enviar el primer mensaje a un usuario?
No. Los bots no pueden iniciar conversaciones: un usuario tiene que escribir al bot, pulsar Start o añadirlo antes a un grupo. Hasta entonces, enviar al id de ese usuario falla. Dales a los usuarios el enlace t.me del bot y guarda su chat id cuando escriban.
¿Por qué el id de mi canal necesita -100 delante?
La Bot API numera los canales y los supergrupos como menos un billón menos el id interno del canal, así que los ids de canal son negativos y, para los ids actuales, empiezan por -100. Un id copiado sin ese prefijo, como 1234567890, apunta a otro chat o a ninguno.
¿Puedo enviar un mensaje a un usuario por su @username?
No. La forma @username funciona para canales, supergrupos y otros bots. Para una persona necesitas su chat id numérico, que el bot obtiene de su primer mensaje o de su Start.
¿Es mi chat_id demasiado grande para un entero?
Puede serlo para uno de 32 bits. Los chat ids pueden tener más de 32 bits significativos, pero como mucho 52, así que guárdalos como entero de 64 bits, BIGINT en SQL. Una columna de 32 bits recorta el id y el bot envía entonces a un chat que no existe.
Ayer funcionaba y ahora dice chat not found. ¿Qué ha cambiado?
Normalmente el bot o el chat. El token de otro bot, por ejemplo un bot de pruebas en staging, solo llega a los chats de ese bot. Un bot eliminado de un grupo o canal lo pierde. Un grupo convertido en supergrupo recibe un id nuevo, y el antiguo devuelve su propio error con el id nuevo en migrate_to_chat_id.
¿Cómo encuentro el chat id de un canal?
Añade el bot al canal como administrador y luego llama a getChat con chat_id igual a @tucanal si es público, o publica algo en el canal y lee chat.id en el update channel_post. El id empieza por -100.
Fuentes
- Telegram Bot API — sendMessage, getChat, getUpdates, Chat, Update, ResponseParameters (core.telegram.org). Consultado el .
- Telegram Bot API server source — telegram-bot-api/Client.cpp (raw.githubusercontent.com). Consultado el .
- Telegram — Bot API dialog IDs (core.telegram.org). Consultado el .
- Telegram — Bots, an introduction for developers (core.telegram.org). Consultado el .
- Telegram — Bot features (deep linking) (core.telegram.org). Consultado el .
- aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Consultado el .
- aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Consultado el .
- aiogram 2.x source — aiogram/utils/exceptions.py (raw.githubusercontent.com). Consultado el .
- python-telegram-bot source — telegram/error.py (raw.githubusercontent.com). Consultado el .
- python-telegram-bot source — telegram/request/_baserequest.py (raw.githubusercontent.com). Consultado el .
- grammY source — src/core/error.ts (raw.githubusercontent.com). Consultado el .
- Telegraf source — src/core/network/error.ts (raw.githubusercontent.com). Consultado el .
Pon tu proyecto en línea hoy
Conecta GitHub o sube una carpeta. No se pide tarjeta.
Despliega tu botRelacionado
- Telegram 403: Forbidden: bot can't initiate conversation with a user — how to fix itTelegram bots cannot write first. The user you are sending to has never started a private chat with your bot: you got their id from a group, a shared contact or another system, not from their own /start. Send them your bot's t.me link with a start parameter, save their chat id when the /start arrives, and on this 403 mark the user as unreachable instead of retrying.
- Telegram 400: Bad Request: group chat was upgraded to a supergroup chat — how to fix itThe group your bot writes to was upgraded to a supergroup, and the supergroup has a new chat id: the old one no longer takes messages. The error carries the new id in parameters.migrate_to_chat_id. Save it in place of the old id and send again, and handle the migrate_to_chat_id service message so the id is updated before the next send fails.
- Telegram 400: Bad Request: not enough rights to send text messages to the chat — how to fix itBad Request: not enough rights to send text messages to the chat means the bot is in the group, but its permissions there do not allow this kind of message: the group's default permissions turn sending off for members, or the bot itself was restricted. Make the bot an administrator, or turn the permission back on; check with getChatMember for the bot's own id. In a channel the bot needs to be an administrator that can post.
- Bad Request: can't parse entities — error del bot de Telegram y cómo solucionarloBad Request: can't parse entities significa que Telegram no ha podido leer el formato de tu mensaje: con parse_mode en HTML, Markdown o MarkdownV2, algún texto (casi siempre el nombre de un usuario, un username con guion bajo, un precio con punto o una etiqueta sin cerrar) rompe el marcado. Escapa ese texto para el parse mode que usas, envía entities en lugar de parse_mode o envíalo sin parse_mode.
- Telegram 403: Forbidden: bot was blocked by the user — how to handle itThe user blocked the bot, and Telegram refuses every message the bot sends them. Nothing is broken and a retry will not help: catch the 403, mark that user as inactive in your database, skip them in broadcasts, and mark them active again when they write to the bot.
- Error 429 de Telegram «Too Many Requests: retry after N»: cómo solucionarloEl control de flood de Telegram le está pidiendo a tu bot que vaya más despacio: espera el número de segundos que indica retry_after y vuelve a enviar la misma petición. Se debe a enviar demasiado rápido: más de un mensaje por segundo, aproximadamente, a un mismo chat, 20 por minuto a un grupo o unos 30 por segundo en un envío masivo. Espera y reintenta en el código, y haz los envíos masivos desde una sola cola a un ritmo constante.
- Conflict: terminated by other getUpdates request: cómo solucionarloTelegram le está diciendo a tu bot que otro proceso llamó a getUpdates con el mismo token y se quedó con la conexión. Hay dos copias del bot haciendo polling a la vez: detén la otra (normalmente la copia que sigue en ejecución en tu ordenador o en un servidor antiguo), o consigue un token nuevo en @BotFather, y el error desaparece.
- Hosting para bots de Telegram en 2026: las opciones comparadasUn bot de Telegram necesita un proceso que no se detenga nunca, o una dirección HTTPS pública para un webhook. En Livops se ejecuta a partir de un push a GitHub por 19 créditos al mes (19,000 so'm). Así se comparan un VPS, Railway, Render, Fly.io y Vercel.
- 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.
- Hosting para python-telegram-bot: cómo desplegar un bot v22Un bot de python-telegram-bot se ejecuta como una sola Application: run_polling() para polling, y run_webhook() con el extra webhooks para un webhook. Los dos se detienen limpiamente con SIGTERM. En Livops se ejecuta a partir de un push con bot.py y requirements.txt por 19 créditos al mes (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).
- Forbidden: user is deactivated — the Telegram 403 for a deleted accountThe user deleted their Telegram account, or it was deleted for inactivity, and the Bot API refuses every message to it with a 403. It is permanent: the account cannot come back. Catch the error, mark the user inactive or delete the row, and keep the broadcast going.
- Telegram 403: Forbidden: bot is not a member of the channel chat — how to fix itTelegram knows the channel, but your bot is not in it, so every send, edit or delete there fails with a 403. Usually the bot was never added (a public channel is found by its @username even so), it left with leaveChat, it was removed and then unbanned, or the token belongs to a different bot. Add the bot to the channel as an administrator that can post messages. The same error exists for supergroups and groups.
- Telegram 400: Bad Request: PEER_ID_INVALID — what it means and how to fix itBad 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.