Unhandled rejection error etelegram 400 bad request message text is empty

I'm new to telegram bot and node js, I'm developing a simple bot that calls api urls to get json objects, but I've this error with a command

342

April 24, 2019, at 8:10 PM

I’m new to telegram bot and node js, I’m developing a simple bot that calls api urls to get json objects, but I’ve this error with a command. This is the command’s code:

bot.onText(//fixtures/, (msg) => {
  const chatId = msg.chat.id;
  var out = "";
  function myFunction(arr) {
      var i;
      for(i = 0; i < arr.length; i++) {
          out += arr[i].name + "--";
      }
  }
  request.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          myFunction(myArr);
      }
  };
  request.open("GET", url, true);
  request.send();
  bot.sendMessage(chatId, out);

And this is full error:

Unhandled rejection Error: ETELEGRAM: 400 Bad Request: message text is empty
at request.then.resp (C:UsersUtente1DesktopMyFootballBotnode_modulesnode-telegram-bot-apisrctelegram.js:280:15)
at tryCatcher (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleaseutil.js:16:23)
at Promise._settlePromiseFromHandler (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleasepromise.js:512:31)
at Promise._settlePromise (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleasepromise.js:569:18)
at Promise._settlePromise0 (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleasepromise.js:614:10)
at Promise._settlePromises (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleasepromise.js:694:18)
at _drainQueueStep (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleaseasync.js:138:12)
at _drainQueue (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleaseasync.js:131:9)
at Async._drainQueues (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleaseasync.js:147:5)
at Immediate.Async.drainQueues [as _onImmediate] (C:UsersUtente1DesktopMyFootballBotnode_modulesbluebirdjsreleaseasync.js:17:14)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)

Answer 1

You should send your message after your success ajax request reply. Move bot.sendMessage(chatId, out); inside onReadyStateChange callback:

request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        myFunction(myArr);
        bot.sendMessage(chatId, out);
    }
};

  • 05:30

    Trying to take the file extension out of my URL

  • 04:00

    display list that in each row 1 li

  • 00:00

    Read audio channel data from video file nodejs

  • 10:30

    session not saved after running on the browser

  • 9:10

    Best way to trigger worker_thread OOM exception in Node.js

  • 07:40

    Firebase Cloud Functions: PubSub, «res.on is not a function»

  • 04:00

    TypeError: Cannot read properties of undefined (reading ‘createMessageComponentCollector’)

  • 9:20

    AWS XRAY on Fargate service

  • 7:40

    How to resolve getting Error 429 Imgur Api

Rent Charter Buses Company

Request: message text is empty
at request.then.resp (/Users/macbook/Desktop/Bot/node_modules/node-telegram-bot-api/src/telegram.js:280:15)
at tryCatcher (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues [as _onImmediate] (/Users/macbook/Desktop/Bot/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:756:18)
at tryOnImmediate (timers.js:717:5)
at processImmediate [as _immediateCallback] (timers.js:697:5)
Пытаюсь обратиться к массиву с информацией

russian

programming

it

ai

bot-development


2

ответов

Может из за типа данных он не видит содержимое.?

node-telegram-bot-api не лечим )

Похожие вопросы

Well, i wrote wrapper on C language to communicate via SSL with telegram bot api. SO now I can clearly answer questions about telegram API spec.

Problem number one

First of all if we are talking about raw queries we need to remember about specifications.

By default HTTP/HTTPS post requests should consists of:

  1. <METHOD>[space]<PATH with only valid chars> <rn>
  2. <HOST valid regexedrn>
  3. <Content-type valid regexed><rn>
  4. <Content-Length with length of your POST body data><rn>
  5. <rn before body>
  6. <body>

So, i tried to send raw queries with out Content-Length and i had error same as yours. That’s the first problem.

Problem number two

By default if you trying to send non valid request with sendMessage method — telegram bot api will response with error same as yours. So, yeah, that’s pretty tricky error to debug…

If you trying to send raw query, be sure that your JSON data is serialized nicely and there is no errors like shielding.

Summarizing

Request:

POST /bot<token>/sendMessage HTTP/1.1
Host: api.telegram.org:443
Connection: close
Content-Type: application/json
Content-Length: 36

{"chat_id":<integer>, "text":"test \lol"}

Second backslash if shielding.

Code on C

sprintf(reqeustCtx.request,
            "POST /bot%s/%s HTTP/1.1rn"
            "Host: %srn"
            "Connection: closern"
            "Content-Type: application/jsonrn"
            "Content-Length: %drn"
            "rn"
            "%srn", bot_token, bot_method,
            reqeustCtx.res_addr, strlen(body), body);
    BIO_puts(bio, reqeustCtx.request);
    BIO_flush(bio);

    memset(reqeustCtx.response, '', BUFFSIZE);
    read_bytes = BIO_read(bio, reqeustCtx.response, BUFFSIZE);
    if (read_bytes <= 0) {
        printf("No response");
        exit(-1);
    }

    cert_free(cert_store, ssl_ctx, ca_cert_bio);
    // free memory //
    reqeustCtx.method(reqeustCtx.res_addr, reqeustCtx.request,
                      reqeustCtx.current_work_dir, reqeustCtx.current_cert);

    /* json response, need to parse */
    return reqeustCtx.response;

/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 — пользователь не написал ничего в ваш телеграм бот. Пользователю нужно написать сообщение в бот, прежде чем бот сможет написать сообщение пользователю.

После получения указанных выше ошибок происходит автоматическая отписка пользователя от вашего телеграм-бота. Статус его подписки изменяется с «Подключен» на «Отключен».

Раздражает, когда какой-то сайт не загружается и отзывается непонятными ошибками. Обычно они сопровождаются одним из десятков HTTP-кодов, которые как раз намекают на характер сбоя, а также его вероятные причины. 

В этом материале поговорим об ошибке 400 Bad Request. Почему она появляется и как ее исправить. 

Чуть подробнее об ошибке 400

Как и другие коды, начинающиеся на четверку, 400 Bad Request говорит о том, что возникла проблема на стороне пользователя. Зачастую сервер отправляет ее, когда появившаяся неисправность не подходит больше ни под одну категорию ошибок. 

Стоит запомнить — код 400 напрямую связан с клиентом (браузером, к примеру) и намекает на то, что отправленный запрос со стороны пользователя приводит к сбою еще до того, как его обработает сервер (вернее, так считает сам сервер). 

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Из-за чего всплывает Bad Request?

Есть 4 повода для возникновения ошибки сервера 400 Bad Request при попытке зайти на сайт:

  1. Некорректно настроенные HTTP-заголовки в запросе со стороны клиента. Некоторые приложения и сайты мониторят заголовки на предмет наличия в них чего-нибудь подозрительного. Если ваш запрос не соответствует ожиданиям сервера, то высока вероятность появления ошибки 400 (но это не всегда вина пользователя).
  2. Такой же сбой появляется, если клиент пытается загрузить на сервер файл слишком большого размера. Это происходит, потому что на большинстве сайтов есть ограничения по размеру загружаемых данных. Причем ограничение может быть как в 2 гигабайта, так и в 600 килобайт.
  3. Еще ошибка 400 появляется, когда пользователь пытается получить доступ к несуществующей странице. То есть в браузер банально ввели ссылку с опечаткой, некорректным доменом или поддоменом.
  4. Устаревшие или измененные куки-файлы. Сервер может воспринять подмену куки-файлов как попытку атаковать или воспользоваться дырой в безопасности. Поэтому такие запросы сходу блокируются.

Читайте также

Ошибка сервера 401

Ошибка 502 Bad Gateway Error

Исправляем ошибку 400 Bad Request на стороне клиента

Так как ошибка 400 в 99 случаев из 100 возникает на стороне клиента, начнем с соответствующих методов. Проверим все элементы, участвующие в передаче запроса со стороны клиента (браузера).

Проверяем адрес сайта

Банальщина, но необходимая банальщина. Перед тем как бежать куда-то жаловаться и предпринимать более серьезные шаги, повнимательнее взгляните на ссылку в адресной строке. Может, где-то затесалась опечатка или вы случайно написали большую букву вместо маленькой. Некоторые части адреса чувствительны к регистру. 

А еще стоит поискать запрашиваемую страницу через поисковик, встроенный в сайт. Есть вероятность, что конкретная страница куда-то переехала, но сервер не может показать подходящий HTTP-код в духе 404 Not Found. Если, конечно, сам сайт работает. 

Сбрасываем параметры браузера

Этот метод срабатывает, если сервер отказывается принимать запросы из-за «битых» куки или других данных. Дело в том, что сайт использует куки-файлы, чтобы хранить информацию о пользователе у него же в браузере. При входе конкретного человека на ресурс, он пытается распознать куки и сравнить информацию с той, что уже есть на сервере.

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

В зависимости от браузера процесс удаления куки-файлов может немного отличаться. В Chrome это работает так:

  • Открываем настройки браузера. 
  • Переходим в раздел «Конфиденциальность и безопасность».
  • Выбираем «Файлы cookie и другие данные».
  • Нажимаем на кнопку «Удалить все».Удаление кукис в Google Chrome

Для чистки cookies можно использовать стороннюю программу в духе CCleaner или CleanMyPC.

Загружаем файл подходящего размера

Если ошибка 400 Bad Request появляется при попытке загрузить на сайт какой-нибудь файл, то стоит попробовать загрузить файл поменьше. Иногда вебмастера ленятся грамотно настроить ресурс, и вместо понятного объяснения вроде «Загружаемые файлы не должны быть размером больше 2 мегабайт» люди получают Bad Request. Остается только гадать, какой там у них лимит. 

Устраняем проблемы, связанные с Windows и сторонним софтом

Помимо браузера, на работу сети могут влиять другие программные продукты (экраны, защищающие от «непонятных подключений»). И вирусы. Да и сама Windows может стать проблемой. Почти любой ее компонент. Поэтому надо бы проделать следующее:

  • Повторно установить NET.Framework. Желательно перед этим удалить предыдущую версию.
  • Установить какой-нибудь приличный антивирус (а лучше два) и запустить глубокую проверку систему. Возможно, подключению и входу на ресурс мешает вредоносная программа.
  • Если у вас уже установлен антивирус, то, наоборот, попробуйте его отключить. Иногда встроенные в них экраны проверки подключений блокируют работу браузера целиком или отдельных страниц. Лучше выдать браузеру больше прав на выполнение своих задач или установить антивирус, который более лояльно относится к установленному на компьютере софту.
  • Еще надо поменять параметры брандмауэра. Его можно разыскать в панели управления Windows. Там надо добавить в список исключений ваш браузер. Тогда брандмауэр не будет мешать подключению к запрашиваемому сайту.
  • Почистить Windows от программного мусора. Можно пройтись приложением CCleaner. 
  • Обновить драйверы для сетевых устройств. 
  • Обновить Windows или просканировать систему на наличие погрешностей в системных компонентах.

Ищем проблему на стороне сервера

Если что-то происходит на стороне ресурса, то это редко заканчивается ошибкой 400. Но все-таки есть несколько сценариев, при которых клиента обвиняют в сбое зря, а настоящая вина лежит на сервере. 

Проверяем требования к HTTP-заголовкам

Пока настраиваешь сайт, несложно допустить ошибку или даже парочку. Возможно, требования к HTTP-заголовком указаны некорректно, и сервер ожидает запросы с ошибками, которые по объективным причинам не может распознать адекватно. Тогда администратору стоит перепроверить ожидаемые заголовки на своем сайте или в приложении. 

Удаляем свежие обновления и плагины

Иногда ошибка 400 Bad Request появляется после обновления CMS или установки новых плагинов. Если у вас она появилась из-за этого, то наиболее логичное решение — откатиться до более ранней версии CMS и удалить все новые плагины. 

Главное, перед этим сделать резервную копию данных. И перед установкой обновлений тоже стоило бы.

Проверяем состояние базы данных

Некоторые сторонние расширения для того же WordPress получают полный доступ к ресурсу и имеют право вносить изменения даже в подключенную базу данных. Если после удаления свежих плагинов ошибка 400 никуда не исчезла и появляется у всех, кто пытается зайти на сайт, стоит проверить, в каком состоянии находится база данных. Нужно вручную проверить все записи на наличие подозрительных изменений, которые могли быть сделаны установленными расширениями.

Исправляем ошибки в коде и скриптах

Ничего из вышеперечисленного не помогло? Тогда осталось проверить свой код и работающие скрипты. Лучше провести дебаггинг вручную и не надеяться на помощь компьютера. Сделать копию приложения или сайта, потом пошагово проверить каждый отрезок кода в поисках ошибок. 

В крайнем случае придется кричать «полундра» и звать на помощь техподдержку хостинга. Возможно, возникли сложности на их стороне. Тогда вообще ничего не надо будет делать. Просто ждать, пока все исправят за вас. 

На этом все. Основные причины появления 400 Bad Request разобрали. Как ее лечить — тоже. Теперь дело за вами. Пользуйтесь полученной информацией, чтобы больше не пришлось мучиться в попытках зайти на нужный ресурс.

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.

Понравилась статья? Поделить с друзьями:
  • Unhandled promise rejection syntaxerror json parse error unexpected identifier object
  • Unhandled php plugin error call the php plugin vendor
  • Unhandled exception произошла одна или несколько ошибок фазмофобия
  • Unhandled exception type segmentation error vmstate 0x00000000
  • Unhandled exception occurred see log for details dead air как исправить