I have the following code in Python to send a message to myself from a bot.
import requests
token = '123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHI'
method = 'sendMessage'
myuserid = 1949275XX
response = requests.post(
url='https://api.telegram.org/bot{0}/{1}'.format(token, method),
data={'chat_id': myuserid, 'text': 'hello friend'}
).json()
print(response)
but this returns {'description': 'Bad Request: chat not found', 'error_code': 400, 'ok': False}
What am I doing wrong? I got myuserid
by sending /getid
to @myidbot
and I got my token from @BotFather
PythoNic
3035 silver badges13 bronze badges
asked Dec 15, 2016 at 23:10
6
As @maak pointed out, you need to first send a message to the bot before the bot can send messages to you.
answered Dec 22, 2016 at 21:07
BijanBijan
7,10718 gold badges83 silver badges141 bronze badges
2
I was using prefix @ before the value of chat_id as suggested everywhere. I removed it and it started working.
Note: if your chat id is 12345678 then you need to prefix it with -100 such that it is -10012345678.
Example Postman call:
/sendMessage?chat_id=-10012345678&text=Let's get together
answered Jan 30, 2021 at 6:51
NKMNKM
5021 gold badge5 silver badges18 bronze badges
3
If your trying to send messages to a group, you must add a ‘-‘ in front of your chat ID.
For example:
TELEGRAM_REG_CHAT_ID="1949275XX"
should be
TELEGRAM_REG_CHAT_ID="-1949275XX"
answered Jul 10, 2020 at 13:12
Dan WaltersDan Walters
1,13815 silver badges27 bronze badges
3
There is a way to send notifications messages to telegram. It’s a bit tricky but the tutorial is great!
http://bernaerts.dyndns.org/linux/75-debian/351-debian-send-telegram-notification
I just sended a message of my apache state to a privat channel.
Works also on public channel but it’s not what i wantet. As you call a script (bash) you can prepare the parameters in any script language.
Hope that helps.
answered Mar 28, 2018 at 8:44
Martin S.Martin S.
2561 silver badge10 bronze badges
1
For me it worked only with @
prefix before channel id
answered May 14, 2021 at 19:47
kashlokashlo
2,1171 gold badge26 silver badges39 bronze badges
I had some trouble with this after upgrading to a supergroup. The chat_id was updated and it was a bit harder to find this new id.
In the end I solved this with this by following this comment: https://stackoverflow.com/a/56078309/14213187
answered Dec 7, 2022 at 9:36
If you use a username, it does not require any prefix. That means the following are incorrect:
https://t.me/vahid_esmaily_ie
t.me/vahid_esmaily_ie
And this is the correct case:
vahid_esmaily_ie
joanis
10.1k13 gold badges29 silver badges40 bronze badges
answered Jul 5, 2021 at 12:12
If you want to use a bot message to the channel, you can refer step here
Steps:
- Create a Telegram public channel
- Create a Telegram BOT (for example
x_bot
) via BotFather - Set the
x_bot
as an administrator in your channel
the chat_id is @x_bot
, it’s a part of https://t.me/x_bot
that does not add your channel name.
answered Nov 25, 2021 at 7:32
Tan NguyenTan Nguyen
7596 silver badges8 bronze badges
Telegram bots can’t send messages to user, if that user hasn’t started conversation with bot yet, or bot is not present in chat (if it’s a group chat). This issue is not related to the library, this is simply Telegram restriction, so that bots can’t spam users without their permission.
you need to first send a message to the bot before the bot can send messages to you.
answered Jan 18 at 9:02
Whenever I try to send a message to my telegram account I get the following error.
client.sendMessage('xxxxxx', 'Hello World').then(() => {
console.log('sent');
}).catch(err => console.log(err));
Error: Telegram API - 400 Bad Request: chat not found
at /Users/alexanderhoerl/Developer/reddit-script/node_modules/messaging-api-telegram/lib/TelegramClient.js:116:17
at Generator.throw (<anonymous>)
at step (/Users/alexanderhoerl/Developer/reddit-script/node_modules/messaging-api-telegram/lib/TelegramClient.js:8:362)
at /Users/alexanderhoerl/Developer/reddit-script/node_modules/messaging-api-telegram/lib/TelegramClient.js:8:561
at process._tickCallback (internal/process/next_tick.js:68:7)
Error Message -
Telegram API - 400 Bad Request: chat not found
Request -
POST https://api.telegram.org/bot701723441:AAGuTVaWZGG-fRJjfUWktZnI6M0BIJu21Ig/sendMessage
Request Data -
{
"chat_id": "xxxxxxx",
"text": "Hello World"
}
Response -
400 Bad Request
Response Data -
{
"ok": false,
"error_code": 400,
"description": "Bad Request: chat not found"
}
Do I need to start a conversation with my bot before he can send me notifications?
/public/img/default_profile_50.png
Статья была полезной?
Если при отправке сообщения через Telegram оно не было доставлено пользователю, то такое сообщение получает статус «Ошибка».
Для того чтобы проверить, почему не было доставлено сообщение, нужно проанализировать детали ошибки.
Сообщения со статусом «Ошибка» можно просмотреть из статистики каждой отправленной рассылки.
Детали ошибки (её описание) можно увидеть в колонке «Статус»:
Также информацию по полученной ошибке можно будет увидеть при переходе в конкретное письмо:
Открытое таким образом сообщение содержит в себе текст в том виде, в котором оно было отправлено пользователю.
Наиболее распространённые ошибки и их значения:
- user is deactivated — пользователь удалил свой номер телефона на стороне телеграм или его номер телефона находится в процессе деактивации.
- phone number invalid — пользователь неверно указал свой номер телефона на стороне телеграм.
- bad request chat not found — пользователь не написал ничего в ваш телеграм бот. Пользователю нужно написать сообщение в бот, прежде чем бот сможет написать сообщение пользователю.
- [400]Bad Request: wrong HTTP URL — возникает при неверном указании ссылки в рассылке telegram. Чаще всего это связано с опечаткой в ссылке.
- [400]Bad Request: can’t parse entities: Unexpected end tag at byte offset — может возникать в случае, если в теле письма были не закрыты какие-либо HTML-теги.
- [400]Bad Request: MEDIA_CAPTION_TOO_LONG — Эта ошибка связана с ограничением в количестве символов в подписи к медиафайлам (1024 символа, включая пробелы).
- [400]Bad Request: message is too long — говорит о том, что количество используемых символов в тексте письма превысило 4096 символов. Данное значение установлено самим Телеграмом.
- [400]Bad Request: wrong file identifier/HTTP URL specified — ссылается на неверный идентификатор файла. Обратите внимание, что при использовании «image url» изображение должно быть в формате «.jpeg».
- [400]Bad Request: failed to get HTTP URL content или Bad Request: wrong file identifier/HTTP URL specified — могут возникать в случае, если превышен максимальный размер вложения (5 мб для картинок и 20 мб для других типов файлов).
- [400]Bad Request: unsupported URL protocol — возникает из-за неправильного указания ссылки в синтаксисе кнопки. Например, при наличии лишнего пробела.
- bot was blocked by the user — пользователь удалил чат с ботом на стороне телеграм, таким образом отписавшись от получения сообщений.
- bad request chat not found — пользователь не написал ничего в ваш телеграм бот. Пользователю нужно написать сообщение в бот, прежде чем бот сможет написать сообщение пользователю.
После получения указанных выше ошибок происходит автоматическая отписка пользователя от вашего телеграм-бота. Статус его подписки изменяется с «Подключен» на «Отключен».
There will be errors when working with the API, and they must be correctly handled on the client.
An error is characterized by several parameters:
Error Code
Numerical value similar to HTTP status. Contains information on the type of error that occurred: for example, a data input error, privacy error, or server error. This is a required parameter.
Error Type
A string literal in the form of /[A-Z_0-9]+/
, which summarizes the problem. For example, AUTH_KEY_UNREGISTERED
. This is an optional parameter.
Error Database
A full machine-readable JSON list of RPC errors that can be returned by all methods in the API can be found here », what follows is a description of its fields:
errors
— All error messages and codes for each method (object).- Keys: Error codes as strings (numeric strings)
- Values: All error messages for each method (object)
- Keys: Error messages (string)
- Values: An array of methods which may emit this error (array of strings)
descriptions
— Descriptions for every error mentioned inerrors
(and a few other errors not related to a specific method)- Keys: Error messages
- Values: Error descriptions
user_only
— A list of methods that can only be used by users, not bots.
Error messages and error descriptions may contain printf
placeholders in key positions, for now only %d
is used to map durations contained in error messages to error descriptions.
Example:
{
"errors": {
"420": {
"2FA_CONFIRM_WAIT_%d": [
"account.deleteAccount"
],
"SLOWMODE_WAIT_%d": [
"messages.forwardMessages",
"messages.sendInlineBotResult",
"messages.sendMedia",
"messages.sendMessage",
"messages.sendMultiMedia"
]
}
},
"descriptions": {
"2FA_CONFIRM_WAIT_%d": "Since this account is active and protected by a 2FA password, we will delete it in 1 week for security purposes. You can cancel this process at any time, you'll be able to reset your account in %d seconds.",
"SLOWMODE_WAIT_%d": "Slowmode is enabled in this chat: wait %d seconds before sending another message to this chat.",
"FLOOD_WAIT_%d": "Please wait %d seconds before repeating the action."
},
"user_only": {
"account.deleteAccount"
}
}
Error Constructors
There should be a way to handle errors that are returned in rpc_error constructors.
Below is a list of error codes and their meanings:
303 SEE_OTHER
The request must be repeated, but directed to a different data center.
Examples of Errors:
- FILE_MIGRATE_X: the file to be accessed is currently stored in a different data center.
- PHONE_MIGRATE_X: the phone number a user is trying to use for authorization is associated with a different data center.
- NETWORK_MIGRATE_X: the source IP address is associated with a different data center (for registration)
- USER_MIGRATE_X: the user whose identity is being used to execute queries is associated with a different data center (for registration)
In all these cases, the error description’s string literal contains the number of the data center (instead of the X) to which the repeated query must be sent.
More information about redirects between data centers »
400 BAD_REQUEST
The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated.
Examples of Errors:
- FIRSTNAME_INVALID: The first name is invalid
- LASTNAME_INVALID: The last name is invalid
- PHONE_NUMBER_INVALID: The phone number is invalid
- PHONE_CODE_HASH_EMPTY: phone_code_hash is missing
- PHONE_CODE_EMPTY: phone_code is missing
- PHONE_CODE_EXPIRED: The confirmation code has expired
- API_ID_INVALID: The api_id/api_hash combination is invalid
- PHONE_NUMBER_OCCUPIED: The phone number is already in use
- PHONE_NUMBER_UNOCCUPIED: The phone number is not yet being used
- USERS_TOO_FEW: Not enough users (to create a chat, for example)
- USERS_TOO_MUCH: The maximum number of users has been exceeded (to create a chat, for example)
- TYPE_CONSTRUCTOR_INVALID: The type constructor is invalid
- FILE_PART_INVALID: The file part number is invalid
- FILE_PARTS_INVALID: The number of file parts is invalid
- FILE_PART_X_MISSING: Part X (where X is a number) of the file is missing from storage
- MD5_CHECKSUM_INVALID: The MD5 checksums do not match
- PHOTO_INVALID_DIMENSIONS: The photo dimensions are invalid
- FIELD_NAME_INVALID: The field with the name FIELD_NAME is invalid
- FIELD_NAME_EMPTY: The field with the name FIELD_NAME is missing
- MSG_WAIT_FAILED: A request that must be completed before processing the current request returned an error
- MSG_WAIT_TIMEOUT: A request that must be completed before processing the current request didn’t finish processing yet
401 UNAUTHORIZED
There was an unauthorized attempt to use functionality available only to authorized users.
Examples of Errors:
- AUTH_KEY_UNREGISTERED: The key is not registered in the system
- AUTH_KEY_INVALID: The key is invalid
- USER_DEACTIVATED: The user has been deleted/deactivated
- SESSION_REVOKED: The authorization has been invalidated, because of the user terminating all sessions
- SESSION_EXPIRED: The authorization has expired
- AUTH_KEY_PERM_EMPTY: The method is unavailable for temporary authorization key, not bound to permanent
403 FORBIDDEN
Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user.
404 NOT_FOUND
An attempt to invoke a non-existent object, such as a method.
406 NOT_ACCEPTABLE
Similar to 400 BAD_REQUEST, but the app must display the error to the user a bit differently.
Do not display any visible error to the user when receiving the rpc_error
constructor: instead, wait for an updateServiceNotification update, and handle it as usual.
Basically, an updateServiceNotification popup
update will be emitted independently (ie NOT as an Updates constructor inside rpc_result
but as a normal update) immediately after emission of a 406 rpc_error
: the update will contain the actual localized error message to show to the user with a UI popup.
An exception to this is the AUTH_KEY_DUPLICATED
error, which is only emitted if any of the non-media DC detects that an authorized session is sending requests in parallel from two separate TCP connections, from the same or different IP addresses.
Note that parallel connections are still allowed and actually recommended for media DCs.
Also note that by session we mean a logged-in session identified by an authorization constructor, fetchable using account.getAuthorizations, not an MTProto session.
If the client receives an AUTH_KEY_DUPLICATED
error, the session is already invalidated by the server and the user must generate a new auth key and login again.
420 FLOOD
The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number.
Error Example:
- FLOOD_WAIT_X: A wait of X seconds is required (where X is a number)
500 INTERNAL
An internal server error occurred while a request was being processed; for example, there was a disruption while accessing a database or file storage.
If a client receives a 500 error, or you believe this error should not have occurred, please collect as much information as possible about the query and error and send it to the developers.
Other Error Codes
If a server returns an error with a code other than the ones listed above, it may be considered the same as a 500 error and treated as an internal server error.
- SEO форум №1 »
- SMM »
- Telegram »
- Боты »
- Ошибка {«ok»:false,»error_code»:400,»description»:»Bad Request: chat not found»}
Тема:
(Прочитано 2336 раз)
Ошибка {«ok»:false,»error_code»:400,»description»:»Bad Request: chat not found»} возникает, когда вы неправильно вставили ссылку на сообщество, тут так и написано — Чат не существует…надо лишь правильно найти id телеграмм чата для бота об этом мы писали тут https://saitsozdanie.ru/forum/index.php?topic=8882.0
« Последнее редактирование: Апреля 11, 2021, 02:08:20 pm от saitikdev »
Записан
- SEO форум №1 »
- SMM »
- Telegram »
- Боты »
- Ошибка {«ok»:false,»error_code»:400,»description»:»Bad Request: chat not found»}
0 / 0 / 0
Регистрация: 20.11.2019
Сообщений: 32
1
13.03.2022, 12:04. Показов 3712. Ответов 1
У меня есть бот, он должен отправить админу сообщение через строчку кода:
Python | ||
|
В конфиге, соответственно, сохранен CHAT_ID. Так вот, код работает только с некоторыми айди, а иногда выдает ошибку ERROR — TeleBot: «A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: chat not found». Причем, в старой версии кода не работал первый айди, зато работал второй. А теперь, когда я поменял код, работает второй айди, но не работает первый… Вот такая вот головоломка… Причем, он даже не показывает строчку, где эта ошибка, а выдает 2022-03-13 13:56:06,625 (__init__.py:653 MainThread). Но когда я меняю айди, то все работает. Как это исправить, знает кто-нибудь?
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0