Error telebot a request to the telegram api was unsuccessful error code 400

What version of pyTelegramBotAPI are you using? 3.6.6 What OS are you using? Windows 10 What version of python are you using? 3.8.0 Hi! I just recived this error: 2020-02-23 19:33:38,069 (apihelper...
  1. What version of pyTelegramBotAPI are you using? 3.6.6

  2. What OS are you using? Windows 10

  3. What version of python are you using? 3.8.0

Hi! I just recived this error:

2020-02-23 19:33:38,069 (apihelper.py:55 WorkerThread2) DEBUG - TeleBot: "The server returned: 'b'{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unexpected end of name token at byte offset 291"}''"
2020/02/23 19:33:38 apihelper,line: 55    DEBUG | The server returned: 'b'{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unexpected end of name token at byte offset 291"}''
2020-02-23 19:33:38,070 (util.py:65 WorkerThread2) ERROR - TeleBot: "ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:n[b'{"ok":false,"error_code":400,"description":"Bad Request: can\'t parse entities: Unexpected end of name token at byte offset 291"}']',)
Traceback (most recent call last):
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotutil.py", line 59, in run
    task(*args, **kwargs)
  File "main.py", line 191, in handle_me
    bot.send_message(message.chat.id,Mymessage,parse_mode='html')
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebot__init__.py", line 597, in send_message
    apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id,
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotapihelper.py", line 140, in send_message
    return _make_request(token, method_url, params=payload, method='post')
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotapihelper.py", line 56, in _make_request
    return _check_result(method_name, result)['result']
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotapihelper.py", line 75, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unexpected end of name token at byte offset 291"}']
"
2020/02/23 19:33:38 util,line: 65    ERROR | ApiException occurred, args=('A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:n[b'{"ok":false,"error_code":400,"description":"Bad Request: can\'t parse entities: Unexpected end of name token at byte offset 291"}']',)
Traceback (most recent call last):
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotutil.py", line 59, in run
    task(*args, **kwargs)
  File "main.py", line 191, in handle_me
    bot.send_message(message.chat.id,Mymessage,parse_mode='html')
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebot__init__.py", line 597, in send_message
    apihelper.send_message(self.token, chat_id, text, disable_web_page_preview, reply_to_message_id,
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotapihelper.py", line 140, in send_message
    return _make_request(token, method_url, params=payload, method='post')
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotapihelper.py", line 56, in _make_request
    return _check_result(method_name, result)['result']
  File "C:UsersOlegAppDataLocalProgramsPythonPython38-32libsite-packagestelebotapihelper.py", line 75, in _check_result
    raise ApiException(msg, method_name, result)
telebot.apihelper.ApiException: A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unexpected end of name token at byte offset 291"}']

2020-02-23 19:33:38,073 (__init__.py:417 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unexpected end of name token at byte offset 291"}']"
2020/02/23 19:33:38 __init__,line: 417    ERROR | A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unexpected end of name token at byte offset 291"}']
2020-02-23 19:33:38,073 (__init__.py:420 MainThread) INFO - TeleBot: "Exception occurred. Stopping."
2020/02/23 19:33:38 __init__,line: 420     INFO | Exception occurred. Stopping.
2020-02-23 19:33:38,073 (__init__.py:433 MainThread) INFO - TeleBot: "Stopped polling."
2020/02/23 19:33:38 __init__,line: 433     INFO | Stopped polling.

I’m sending message like 500 characters long so it isn’t a problem.

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 in errors (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.

Вы уверены, что придерживаетесь подписи, send_message()подробно описанной в ваших API- документах ?

Похоже, вы указываете несколько аргументов для своего текстового параметра, попробуйте заключить его в оператор, например:

text = json.loads(response)
messageText = 'Продажа '+text["RUB"]["sell"]+'рублей'+'nПокупка '+text["RUB"]["buy"]+'рублей'

Затем вызовите send_message()метод, указав следующие три необязательных параметра:

  1. chat_id
  2. text
  3. parse_mode

Чтобы:

@bot.message_handler(commands=['bit']) 
def bit(message):
    link = 'https://blockchain.info/ru/ticker'
    response = requests.get(link).text
    text = json.loads(response)
    chatId = '@channelusername'
    messageText = 'Продажа '+text["RUB"]["sell"]+'рублей'+'nПокупка '+text["RUB"]["buy"]+'рублей'
    bot.send_message(chatId, messageText, parse_mode=HTML)

Конечно, не забудьте отредактировать свой chatId, который должен быть «Уникальный идентификатор целевого чата или имя пользователя целевого канала (в формате @channelusername)».

Telegram API Error Code 400: как убрать ошибку?

НА ЧТЕНИЕ2 минПРОСМОТРОВ216ОПУБЛИКОВАНО05.09.2022

Самых разных программ сейчас есть достаточно много. Они устанавливаются на телефоны, планшеты, компьютеры и ноутбуки. Использовать их можно для разных целей, но в большинстве случаев, каждый человек имеет что-то, что позволяет ему поддерживать связь с другими людьми. Это может быть социальная сеть, мессенджер или еще какой-то способ для обмена сообщениями. Некоторые из них даже позволяют проводить какую-то автоматизацию процессов, создавать группы и ботов, которые позволяют объединить людей.

Телеграм

Telegram — кроссплатформенная система мгновенного обмена сообщениями (мессенджер) с функциями VoIP, позволяющая обмениваться текстовыми, голосовыми и видеосообщениями, стикерами и фотографиями, файлами многих форматов. Также можно совершать видео- и аудиозвонки и трансляции в каналах и группах.

Является достаточно популярным мессенджером, потому что позволяет создавать разные группы, а в них добавлять ботов, которые могут собирать информацию. Так что им пользуется много человек, потому что он позволяет искать определенную информацию или общаться в формате чата.

Ошибка запроса

Telegram API Error Code 400 Bad request обычно связана с каким0то ботом или автоматизацией. Возникает она в том случае, когда вы хотите запросить или просмотреть какую-то информацию. Может появится и в других ситуациях но это маловероятно, потому что нужен именно запрос, иначе выдаст какой-то другой код ошибки.

Есть несколько случаев, когда вы с помощью бота можете получить такой ответ:

  • Подобный сбой может вылетать когда вы меняете текст на точно такой же текст. То есть текст “привет кукушка”, вы пытаетесь изменить на “привет кукушка”.
  • Либо кто-то из участников чата, либо вы ранее уже удалили это сообщение
  • Ошибка 400 Bad Request – это код ответа, который означает, что сервер не смог обработать запрос, отправленный клиентом из-за неверного синтаксиса

Первые ситуации относятся к тому, что вы пытаетесь сделать что-то, что сделать нельзя или обращаетесь к несуществующему объекту. Последний случай связан с самой программой и построение запроса. Если там была какая-то ошибка или команда, которую телеграмм или сервер не знает, то вы получите такой код.

В простейших случаях это бывают незакрытые скобки или кавычки, опечатка в команде, неправильное построение запроса или что-то подобное. Попробуйте заново перепроверить все это.

Telegram Bot

Ошибка файла при повторном отправлении

19.09.2020, 12:09. Показов 10429. Ответов 7


Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import telebot
bot = telebot.TeleBot('ТОКЕН')
video = open('v.mp4', 'rb')
video1 = open('v1.mp4', 'rb')
video2 = open('v2.mp4', 'rb')
 
@bot.message_handler(content_types=['text'])
def get_text_messages(message):
    if message.text == "Привет":
        bot.send_message(message.from_user.id, "Привет.")
        bot.send_video(message.chat.id, video)
    elif message.text == "/help":
        bot.send_message(message.from_user.id, "Напиши Привет")
        bot.send_video(message.chat.id, video1)
    else:
        bot.send_video(message.chat.id, video2)
 
bot.polling(none_stop=True, interval=0)

При запуске все ок, первый файл отправляет но при повторном отправление сообщение отправляется а файл нет, дальше бот работает только в консоли такие ошибки

2020-09-19 12:01:00,092 (util.py:75 WorkerThread2) ERROR — TeleBot: «ApiTelegramException occurred, args=(‘A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: file must be non-empty’,)
Traceback (most recent call last):
File «C:Users\AppDataLocalProgramsPythonPytho n38-32libsite-packagestelebotutil.py», line 69, in run
task(*args, **kwargs)
File «bot.py», line 16, in get_text_messages
bot.send_video(message.chat.id, video2)
File «C:Users\AppDataLocalProgramsPythonPytho n38-32libsite-packagestelebot__init__.py», line 807, in send_video
apihelper.send_video(self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup,
File «C:Users\AppDataLocalProgramsPythonPytho n38-32libsite-packagestelebotapihelper.py», line 511, in send_video
return _make_request(token, method_url, params=payload, files=files, method=’post’)
File «C:Users\AppDataLocalProgramsPythonPytho n38-32libsite-packagestelebotapihelper.py», line 108, in _make_request
json_result = _check_result(method_name, result)
File «C:Users\AppDataLocalProgramsPythonPytho n38-32libsite-packagestelebotapihelper.py», line 135, in _check_result
raise ApiTelegramException(method_name, result, result_json)
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: file must be non-empty
«
2020-09-19 12:01:00,093 (__init__.py:455 MainThread) ERROR — TeleBot: «A request to the Telegram API was unsuccessful. Error code: 400 Description: Bad Request: file must be non-empty»

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Понравилась статья? Поделить с друзьями:
  • Error tds wiki
  • Error tchar has not been declared
  • Error tattoo sccm
  • Error target voltage may be too low for reliable debugging
  • Error target not halted