Ошибка телеграм bad request method is available only for supergroups 400

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.

So the first error is saying it doesn’t like the group because its a supergroup… and the second error says it can’t use a certain command because its NOT a supergroup…. however the bot automatically bans someone i’m trying to unban…. i need this to work. how can i make it work?

TelegramError: 400: Bad Request: group chat was upgraded to a supergroup chat
    at /app/node_modules/telegraf/core/network/client.js:281:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 1)
    at nowarnsHandler (/app/handlers/commands/nowarns.js:46:3)
    at removeCommandsHandler (/app/handlers/middlewares/removeCommands.js:22:2)
    at async Promise.all (index 0) {
  code: 400,
  response: {
    ok: false,
    error_code: 400,
    description: 'Bad Request: group chat was upgraded to a supergroup chat',
    parameters: { migrate_to_chat_id: -1001201784679 }
  },
  description: 'Bad Request: group chat was upgraded to a supergroup chat',
  parameters: { migrate_to_chat_id: -1001201784679 },
  on: {
    method: 'unbanChatMember',
    payload: { chat_id: -364298668, user_id: 183356440 }
  }
}
TelegramError: 400: Bad Request: method is available for supergroup and channel chats only
    at /app/node_modules/telegraf/core/network/client.js:281:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 4)
    at unbanHandler (/app/handlers/commands/unban.js:39:2)
    at removeCommandsHandler (/app/handlers/middlewares/removeCommands.js:22:2)
    at async Promise.all (index 0) {
  code: 400,
  response: {
    ok: false,
    error_code: 400,
    description: 'Bad Request: method is available for supergroup and channel chats only'
  },
  description: 'Bad Request: method is available for supergroup and channel chats only',
  parameters: {},
  on: {
    method: 'unbanChatMember',
    payload: { chat_id: -246215113, user_id: 183356440 }
  }
}
TelegramError: 400: Bad Request: method is available for supergroup and channel chats only
    at /app/node_modules/telegraf/core/network/client.js:281:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 0)
    at unbanHandler (/app/handlers/commands/unban.js:39:2)
    at removeCommandsHandler (/app/handlers/middlewares/removeCommands.js:22:2)
    at async Promise.all (index 0) {
  code: 400,
  response: {
    ok: false,
    error_code: 400,
    description: 'Bad Request: method is available for supergroup and channel chats only'
  },
  description: 'Bad Request: method is available for supergroup and channel chats only',
  parameters: {},
  on: {
    method: 'unbanChatMember',
    payload: { chat_id: -293457926, user_id: 183356440 }
  }
}

Ошибка 400 Bad Request – это код ответа HTTP, который означает, что сервер не смог обработать запрос, отправленный клиентом из-за неверного синтаксиса. Подобные коды ответа HTTP отражают сложные взаимоотношения между клиентом, веб-приложением, сервером, а также зачастую сразу несколькими сторонними веб-сервисами. Из-за этого поиск причины появления ошибки может быть затруднён даже внутри контролируемой среды разработки.

В этой статье мы разберём, что значит ошибка 400 Bad Request (переводится как «Неверный запрос»), и как ее исправить

  • На стороне сервера или на стороне клиента?
  • Начните с тщательного резервного копирования приложения
  • Диагностика ошибки 400 Bad Request
  • Исправление проблем на стороне клиента
    • Проверьте запрошенный URL
    • Очистите соответствующие куки
    • Загрузка файла меньшего размера
    • Выйдите и войдите
  • Отладка на распространённых платформах
    • Откатите последние изменения
    • Удалите новые расширения, модули или плагины
    • Проверьте непреднамеренные изменения в базе данных
  • Поиск проблем на стороне сервера
    • Проверка на неверные заголовки HTTP
    • Просмотрите логи
  • Отладьте код приложения или скриптов

Все коды ответа HTTP из категории 4xx считаются ошибками на стороне клиента. Несмотря на это, появление ошибки 4xx не обязательно означает, что проблема как-то связана с клиентом, под которым понимается веб-браузер или устройство, используемое для доступа к приложению. Зачастую, если вы пытаетесь диагностировать проблему со своим приложением, можно сразу игнорировать большую часть клиентского кода и компонентов, таких как HTML, каскадные таблицы стилей (CSS), клиентский код JavaScript и т.п. Это также применимо не только к сайтам. Многие приложения для смартфонов, которые имеют современный пользовательский интерфейс, представляют собой веб-приложения.

С другой стороны, ошибка 400 Bad Request означает, что запрос, присланный клиентом, был неверным по той или иной причине. Пользовательский клиент может попытаться загрузить слишком большой файл, запрос может быть неверно сформирован, заголовки HTTP запроса могут быть неверными и так далее.

Мы рассмотрим некоторые из этих сценариев (и потенциальные решения) ниже. Но имейте в виду: мы не можем однозначно исключить ни клиент, ни сервер в качестве источника проблемы. В этих случаях сервер является сетевым объектом, генерирующим ошибку 400 Bad Request и возвращающим её как код ответа HTTP клиенту, но возможно именно клиент ответственен за возникновение проблемы.

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

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

Ошибка 400 Bad Request означает, что сервер (удалённый компьютер) не может обработать запрос, отправленный клиентом (браузером), вследствие проблемы, которая трактуется сервером как проблема на стороне клиента.

Существует множество сценариев, в которых ошибка 400 Bad Request может появляться в приложении. Ниже представлены некоторые наиболее вероятные случаи:

  • Клиент случайно (или намеренно) отправляет информацию, перехватываемую маршрутизатором ложных запросов. Некоторые веб-приложения ищут особые заголовки HTTP, чтобы обрабатывать запросы и удостовериться в том, что клиент не предпринимает ничего зловредного. Если ожидаемый заголовок HTTP не найден или неверен, то ошибка 400 Bad Request – возможный результат.
  • Клиент может загружать слишком большой файл. Большинство серверов или приложений имеют лимит на размер загружаемого файла, Это предотвращает засорение канала и других ресурсов сервера. Во многих случаях сервер выдаст ошибку 400 Bad Request, когда файл слишком большой и поэтому запрос не может быть выполнен.
  • Клиент запрашивает неверный URL. Если клиент посылает запрос к неверному URL (неверно составленному), это может привести к возникновению ошибки 400 Bad Request.
  • Клиент использует недействительные или устаревшие куки. Это возможно, так как локальные куки в браузере являются идентификатором сессии. Если токен конкретной сессии совпадает с токеном запроса от другого клиента, то сервер/приложение может интерпретировать это как злонамеренный акт и выдать код ошибки 400 Bad Request.

Устранение ошибки 400 Bad Request (попробуйте позже) лучше начать с исправления на стороне клиента. Вот несколько советов, что следует попробовать в браузере или на устройстве, которые выдают ошибку.

Наиболее частой причиной ошибки 400 Bad Request является банальный ввод некорректного URL. Доменные имена (например, internet-technologies.ru) нечувствительны к регистру, поэтому ссылка, написанная в смешанном регистре, такая как interNET-technologies.RU работает так же, как и нормальная версия в нижнем регистре internet-technologies.ru. Но части URL, которые расположены после доменного имени, чувствительными к регистру. Кроме случаев, когда приложение/сервер специально осуществляет предварительную обработку всех URL и переводит их в нижний регистр перед исполнением запроса.

Важно проверять URL на неподходящие специальные символы, которых в нем не должно быть. Если сервер получает некорректный URL, он выдаст ответ в виде ошибки 400 Bad Request.

Одной из потенциальных причин возникновения ошибки 400 Bad Request являются некорректные или дублирующие локальные куки. Файлы куки в HTTP – это небольшие фрагменты данных, хранящиеся на локальном устройстве, которые используются сайтами и веб-приложениями для «запоминания» конкретного браузера или устройства. Большинство современных веб-приложений использует куки для хранения данных, специфичных для браузера или пользователя, идентифицируя клиента и позволяя делать следующие визиты быстрее и проще.

Но куки, хранящие информацию сессии о вашем аккаунте или устройстве, могут конфликтовать с другим токеном сессии от другого пользователя, выдавая кому-то из вас (или вам обоим) ошибку 400 Bad Request.

В большинстве случаев достаточно рассматривать только ваше приложение в отношении файлов куки, которые относятся к сайту или веб-приложению, выдающему ошибку 400 Bad Request.

Куки хранятся по принципу доменного имени веб-приложения, поэтому можно удалить только те куки, которые соответствуют домену сайта, сохранив остальные куки не тронутыми. Но если вы не знакомы с ручным удалением определённых файлов куки, гораздо проще и безопаснее очистить сразу все файлы куки.

Это можно сделать разными способами в зависимости от браузера, который вы используете:

  • Google Chrome;
  • Internet Explorer;
  • Microsoft Edge;
  • Mozilla Firefox;
  • Safari.

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

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

Также приложение может столкнуться с проблемой, связанной с вашей предыдущей сессией, являющейся лишь строкой, которую сервер посылает клиенту, чтобы идентифицировать клиента при будущих запросах. Как и в случае с другими данными, токен сессии (или строка сессии) хранится локально на вашем устройстве в файлах куки и передаётся клиентом на сервер при каждом запросе. Если сервер решает, что токен сессии некорректен или скомпрометирован, вы можете получить ошибку 400 Bad Request.

В большинстве веб-приложений выход повторный вход приводит к перегенерации локального токена сессии.

Если вы используете на сервере распространённые пакеты программ, которые выдают ошибку 400 Bad Request, изучите стабильность и функциональность этих платформ. Наиболее распространённые системы управления контентом, такие как WordPress, Joomla! и Drupal, хорошо протестированы в своих базовых версиях. Но как только вы начинаете изменять используемые ими расширения PHP, очень легко спровоцировать непредвиденные проблемы, которые выльются в ошибку 400 Bad Request.

Если вы обновили систему управления контентом непосредственно перед появлением ошибки 400 Bad Request, рассмотрите возможность отката к предыдущей версии, которая была установлена, как самый быстрый и простой способ убрать ошибку 400 bad request.

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

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

В зависимости от конкретной CMS, которую использует приложение, имена этих компонентов будут различаться. Но во всех системах они служат одной и той же цели: улучшение возможностей платформы относительно её стандартной функциональности.

При этом имейте в виду, что расширения могут так или иначе получать полный контроль над системой, вносить изменения в код PHP, HTML, CSS, JavaScript или базу данных. Поэтому мудрым решением может быть удаление любых новых расширений, которые были недавно добавлены.

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

Расширение может изменить записи в базе данных, которые «не принадлежат» ему, а созданы и управляются другими расширениями (или даже самой CMS). В подобных случаях модуль может не знать, как откатить назад изменения, внесенные в записи базы данных.

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

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

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

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

Логи сервера относятся к оборудованию, на котором выполняется приложение, и зачастую представляют собой детали о статусе подключённых сервисов или даже о самом сервере. Поищите в интернете “логи [ИМЯ_ПЛАТФОРМЫ]”, если вы используете CMS, или “логи [ЯЗЫК_ПРОГРАММИРОВАНИЯ]” и “логи [ОПЕРАЦИОННАЯ_СИСТЕМА]”, если у вас собственное приложение, чтобы получить подробную информацию по поиску логов.

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

Создайте копию всего приложения на локальном устройстве для разработки и пошагово повторите тот сценарий, который приводил к возникновению ошибки 400 Bad Request. А затем просмотрите код приложения в тот момент, когда что-то пойдёт не так.

Независимо от причины возникновения ошибки, даже если вам удалось исправить её в этот раз, появление в вашем приложении такой проблемы — это сигнал для того, чтобы внедрить инструмент обработки ошибок, который поможет автоматически обнаруживать их и оповещать в момент возникновения.

this is my code

private async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
    {

        var message = e.Message; if (message == null || message.Type != MessageType.Text) return; await Bot.SendTextMessageAsync(message.Chat.Id, "Hello?");

in this case, it works well with super groups

but
await Bot.SendTextMessageAsync([supergroup chat id], «Hello?»);

put Super Group ID in here[supergroup chat id], it won’t work.
I’ve set up all the group permissions.
After upgrading the super group, I had to drop the bot and invite again

asked Oct 8, 2018 at 17:18

syaneteu's user avatar

2

Just in case if you are haven’t figured it out already… When a group is upgraded to supergroup, new ID is generated:

{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: group chat was upgraded to a supergroup chat",
    "parameters": {
        "migrate_to_chat_id": -1001432162429
    }
}

Use this migrate_to_chat_id to send messages

answered Jun 18, 2019 at 12:53

piyushkantm's user avatar

piyushkantmpiyushkantm

5635 silver badges19 bronze badges

0

If you can’t see the above ‘migrate_to_chat_id’ field mentioned by piyushkantm you can
use:

bot.on('message', (msg) => {
    const chatId = msg.chat.id;
    console.log(chatId);
});

When your request fails send a test message to the group via mobile phone the above will return your updated super group chat.id.

answered May 19, 2021 at 11:34

David Robery's user avatar

В данной статье собраны ошибки, возвращаемые API Telegram. Числовое значение аналогично статусу HTTP. Содержит информацию о типе возникшей ошибки: например, ошибка ввода данных, ошибка конфиденциальности или ошибка сервера.

Telegram API Error - вернулась ошибка после отправки запроса к API

303 SEE_OTHER

Запрос необходимо повторить, но направить в другой центр обработки данных.

Примеры ошибок:

  • FILE_MIGRATE_X: файл, к которому нужно получить доступ, в настоящее время хранится в другом центре обработки данных.
  • PHONE_MIGRATE_X: номер телефона, который пользователь пытается использовать для авторизации, связан с другим центром обработки данных.
  • NETWORK_MIGRATE_X: исходный IP-адрес связан с другим центром обработки данных (для регистрации)
  • USER_MIGRATE_X: пользователь, личность которого используется для выполнения запросов, связан с другим центром обработки данных (для регистрации)

Во всех этих случаях строковый литерал описания ошибки содержит номер центра обработки данных (вместо X), в который должен быть отправлен повторный запрос.

ОШИБКА 400, НЕВЕРНЫЙ ЗАПРОС

Запрос содержит ошибки. В случае, если запрос был создан с использованием формы и содержит данные, созданные пользователем, пользователь должен быть уведомлен о том, что данные должны быть исправлены, прежде чем запрос будет повторен.

Примеры ошибок:

  • FIRSTNAME_INVALID: имя недействительно
  • LASTNAME_INVALID: фамилия недействительна
  • PHONE_NUMBER_INVALID: номер телефона недействителен
  • PHONE_CODE_HASH_EMPTY: phone_code_hash отсутствует
  • PHONE_CODE_EMPTY: phone_code отсутствует
  • PHONE_CODE_EXPIRED: срок действия кода подтверждения истек
  • API_ID_INVALID: комбинация api_id / api_hash недействительна
  • PHONE_NUMBER_OCCUPIED: номер телефона уже используется
  • PHONE_NUMBER_UNOCCUPIED: номер телефона еще не используется
  • USERS_TOO_FEW: недостаточно пользователей (например, для создания чата)
  • USERS_TOO_MUCH: превышено максимальное количество пользователей (например, для создания чата)
  • TYPE_CONSTRUCTOR_INVALID: конструктор типа недействителен
  • FILE_PART_INVALID: неверный номер части файла.
  • FILE_PARTS_INVALID: недопустимое количество частей файла.
  • FILE_PART_Х_MISSING: часть X (где X — номер) файла отсутствует в хранилище
  • MD5_CHECKSUM_INVALID: контрольные суммы MD5 не совпадают
  • PHOTO_INVALID_DIMENSIONS: размеры фотографии недействительны
  • FIELD_NAME_INVALID: поле с именем FIELD_NAME недействительно
  • FIELD_NAME_EMPTY: поле с названием FIELD_NAME отсутствует
  • MSG_WAIT_FAILED: запрос, который должен быть выполнен перед обработкой текущего запроса, возвратил ошибку
  • MSG_WAIT_TIMEOUT: запрос, который должен быть выполнен перед обработкой текущего запроса, еще не завершил обработку

401 ОШИБКА ДОСТУПА

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

Примеры ошибок:

  • AUTH_KEY_UNRIGN: Ключ не зарегистрирован в системе
  • AUTH_KEY_INVALID: ключ недействителен
  • USER_DEACTIVATED: пользователь удален / деактивирован
  • SESSION_REVOKED: авторизация была аннулирована из-за того, что пользователь завершил все сеансы
  • SESSION_EXPIRED: срок авторизации истек
  • AUTH_KEY_PERM_EMPTY: метод недоступен для временного ключа авторизации, не привязан к постоянному

403 ЗАПРЕЩЕНО

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

404 НЕ НАЙДЕНО

Попытка вызвать несуществующий объект, например метод.

406 NOT_ACCEPTABLE

Подобно 400 BAD_REQUEST , но приложение не должно отображать сообщения об ошибках для пользователя в пользовательском интерфейсе в результате этого ответа. Вместо этого сообщение об ошибке будет доставлено через updateServiceNotification.

420 FLOOD

Превышено максимально допустимое количество попыток вызвать данный метод с заданными входными параметрами. Например, при попытке запросить большое количество текстовых сообщений (SMS) на один и тот же номер телефона.

Пример ошибки:

  • FLOOD_WAIT_X: требуется ожидание X секунд (где X — число)

500 ВНУТРЕННИЙ

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

Если клиент получает ошибку 500 или вы считаете, что эта ошибка не должна была возникнуть, пожалуйста, соберите как можно больше информации о запросе и ошибке и отправьте ее разработчикам.

Другие коды ошибок

Если сервер возвращает ошибку с кодом, отличным от перечисленных выше, это может рассматриваться как ошибка 500 и рассматриваться как внутренняя ошибка сервера.

Что такое ошибка 400 Bad Request и как ее исправить

Ошибка 400 Bad Request возникает, когда запрос, отправленный на сервер сайта, является неправильным или поврежденным, и сервер, получающий запрос, не может его понять. Иногда проблема возникает на самом веб-сайте, и Вы вряд ли сможете что-то сделать. Но большую часть времени проблема заключается в том, что Вы можете решить — возможно, Вы неправильно набрали адрес, или, может быть, Ваш кеш браузера вызывает проблемы. Вот некоторые решения, которые Вы можете попробовать.

Ошибка 400 Bad Request возникает, когда сервер не может понять запрос, который был ему отправлен. Это называется ошибкой 400, потому что это код состояния HTTP, используемый веб-сервером для описания такой ошибки.

Ошибка 400 Bad Request может произойти из-за простой ошибки в запросе. Возможно, Вы ошибочно указали URL-адрес, и по какой-то причине сервер не может вернуть ошибку 404. Или, возможно, Ваш веб-браузер пытается использовать истекший или недействительный файл cookie. Некоторые серверы, которые не настроены должным образом, могут также вызывать ошибку 400 вместо более полезных ошибок в некоторых ситуациях. Например, при попытке загрузить файл, который слишком велик для некоторых сайтов, Вы можете получить ошибку 400 вместо ошибки, сообщающей Вам о максимальном размере файла.

Как и при ошибках 404 и 502, дизайнеры веб-сайтов могут настроить, как выглядит ошибка 400. Таким образом, Вы можете увидеть разные страницы ошибки 400 на разных сайтах. Веб-сайты также могут использовать несколько разных имен для этой ошибки. Например, Вы можете увидеть такие вещи, как:

  • 400 Bad Request
  • 400 Bad Request. Запрос не может быть принят сервером из-за неправильного синтаксиса
  • Bad Request — неверный URL-адрес
  • Bad Request. Ваш браузер отправил запрос, который этот сервер не мог понять
  • Ошибка HTTP 400. Недопустимое имя хоста запроса
  • Bad Request: ошибка 400
  • Ошибка HTTP 400 — Bad Request

Часто Вы можете сделать что-то, чтобы исправить ошибку 400, но выяснить, что именно может быть сложным из-за неопределенного характера ошибки. Вот некоторые вещи, которые Вы можете попробовать.

Обновите страницу

Обновление страницы всегда стоит того. Многократно ошибка 400 является временной, и простое обновление может помочь. Большинство браузеров используют клавишу F5 для обновления, а также предоставляют кнопку «Обновить» где-то в адресной строке. Это не часто исправляет проблему, но для ее выполнения требуется всего одна секунда.

Что такое ошибка 400 Bad Request и как ее исправить

Дважды проверьте адрес

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

Выполнить поиск

Если URL-адрес, который Вы пытаетесь найти, является описательным (или если Вы знаете приблизительное название статьи или страницы, которую Вы ожидаете), Вы можете использовать ключевые слова в адресе для поиска на веб-сайте. В приведенном ниже примере Вы не можете действительно сказать из самого URL-адреса, если что-то не так, но Вы можете увидеть некоторые слова из названия статьи.

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

Это же решение также работает, если веб-сайт, который Вы пытаетесь достичь, изменил URL-адрес по какой-либо причине и не перенаправил старый адрес на новый.

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

На изображении ниже мы используем Google и поисковую фразу «site:guidepc.ru локальная сеть» для поиска только сайта guidepc.ru по ключевым словам.

Что такое ошибка 400 Bad Request и как ее исправить

Очистите файлы cookie и кеш браузера

Многие веб-сайты (включая Google и YouTube) сообщают об ошибке 400, потому что куки, которые они читают, либо повреждены, либо слишком стары. Некоторые расширения браузера также могут изменять Ваши файлы cookie и вызывать ошибку 400. Также возможно, что Ваш браузер кэшировал поврежденную версию страницы, которую Вы пытаетесь открыть.

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

Что такое ошибка 400 Bad Request и как ее исправить

Очистите свой DNS

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

Проверьте размер файла

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

Попробуйте другие сайты

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

Перезагрузите компьютер и другое оборудование

Это решение является хитом и перезагрузка компьютера и особенно Вашего сетевого оборудования (маршрутизаторы, модемы) — это распространенный способ избавиться от множества ошибок сервера.

Связаться с веб-сайтом

Если Вы попробовали все решения, и ошибка, не исчезла, значит, сам сайт может иметь проблемы. Попытайтесь связаться с веб-сайтом на странице контактов (если это работает) или через социальные сети. Скорее всего, они уже знают о проблеме и работают над ее исправлением.

When a website fails to load, it’s simply annoying. It’s important to understand, though, why that happened so you know how to fix it.

The 4xx family of status codes is the one we’re investigating here as they relate to invalid or corrupt requests from the client. Specifically, we’ll take a closer look at the 400 Bad Request error: what this error means, what causes it as well as some specific steps to fix the issue.

  • What is 400 Bad Request Error?
  • What Causes a 400 Bad Request Error
  • 400 Bad Request Error: What Does It Look Like?
  • How to Fix 400 Bad Request Error

Check out our video guide to fixing 400 errors:

What is a 400 Bad Request Error?

A 400 Bad Request, also known as a 400 error or HTTP error 400, is perceived by the server as a generic client error and it is returned when the server determines the error doesn’t fall in any of the other status code categories.

The key concept to understand here is that the 400 Bad Request error is something that has to do with the submitted request from the client before it is even processed by the server.

The Internet Engineering Task Force (IETF) defines the 400 Bad Request as:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

What Causes the HTTP 400 Bad Request Error?

There are various root causes that can trigger the 400 Bad Request error and, even if this error isn’t specific to any particular browser or OS (operating system), the fixes do vary slightly.

1. URL String Syntax Error

The HTTP error 400 can occur due to incorrectly typed URL, malformed syntax, or a URL that contains illegal characters.

This is surprisingly easy to do by mistake and can happen if a URL has been encoding incorrectly. The following link is an example of a URL containing characters the server won’t be able to process, hence a 400 Bad Request error is triggered.

https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL

Note the extra % character immediately after the word malformed in the URL. A properly encoded space should be %20 and not %%20. This is what the result looks like in the Chrome browser.

An illegal character can also trigger a 400 Bad request error. The following URL contains a { character, which is not allowed. Therefore, it results in the same type of error.

https://twitter.com/share?lang=en&text=Example%20of%20malformed{%20characters%20in%20URL

2. Corrupted Browser Cache & Cookies

Even if the URL is 100% correct, the 400 Bad Request error can still occur because of corrupted files in the browser cache or problems with expired/corrupted browser cookies.

You may have encountered a 400 Bad Request error when trying to access the admin area of your WordPress site some time after your last log in. That’s happening because of the way the cookie handling your login authentication data may have gotten corrupted and can’t successfully authenticate you as a valid user with admin privileges. This will then result in the connection being refused and a 400 Bad Request error is triggered.

3. DNS Lookup Cache

The 400 Bad Request can happen when the DNS data stored locally is out of sync with registered DNS information.

All domain names are aliases for IP addresses. You can think of an IP address as a phone number “always calling” a specific server you want to connect to. When you first visit a website, a process called “name resolution” takes place and that’s when the domain name resolves to the specific IP address of the server.

To speed things up, these details are stored locally on your computer in the local DNS cache so the name resolution process doesn’t have to be done for every single visit for a given website. This is similar to how the browser cache works for HTML, CSS, JavaScript, media, and other files.

4. File Size Too Large

A 400 Bad Request can also occur when you try to upload a file to a website that’s too large for the upload request to be fulfilled. This is strictly related to the file size limit of the server and will vary based on how it has been set up.

Until now, we’ve focused on the 400 Bad Request error being triggered only due to client-side issues.

5. Generic Server Error

This error can sometimes be triggered because of server-side issues as well. Specifically, a 400 status code could indicate a general problem with the server, a server glitch, or other unspecified temporary issues.

If this happens when trying to connect to a third-party website, it’s really outside of your control and your best shot is to try refreshing the browser and check at regular intervals whether the issue has been fixed by the site owners.

One thing you can do to verify the issue is a server-side issue is to try loading the website on different browsers. If you want to go the extra mile, test it on an entirely different machine/device to rule out system-specific problems.

When you can’t connect to the site via any other browsers, computers, operating systems, or other devices then it’s likely to be a server-side issue. If you’d like, you can reach out to the site owner and let them know which OS, browser, and versions you were using when experienced the issue.

400 Bad Request Error: What Does It Look Like?

Most of the time a 400 Bad Request is related to client-side issues. We already saw what a 400 Bad Request error looks like in the Chrome browser.

400 bad request error in Chrome

400 bad request error in Chrome

But what about the other browsers?

400 Bad Request in Firefox

400 bad request error in Firefox

400 bad request error in Firefox

400 Bad Request in Safari

400 bad request error in Safari

400 bad request error in Safari

400 Bad Request in Microsoft Edge

400 bad request error in Microsoft Edge

400 bad request error in Microsoft Edge

As you can see, all browsers return a generic and unhelpful 400 status code message. It seems you’re pretty much left alone for finding a solution to the problem. In Firefox and Safari, it’s not even clear a 400 Bad Request error has occurred at all as the browser window is completely blank!

Fortunately, we’ve put together a series of simple steps you can take to fix the 400 Bad Request error. Let’s take a closer look at each one of these in the next section!

400 Bad Request (Glossary):

The 400 Bad Request Error is an HTTP response status code
that indicates the server was unable to process (understand) the request sent by the client due to incorrect syntax, invalid request message framing, or deceptive request routing.

How to Fix 400 Bad Request Error?

Complete the steps outlined in this section to help diagnose and correct a 400 Bad Request.

The proposed solutions include:

  • 1. Check the Submitted URL
  • 2. Clear Browser Cache
  • 3. Clear Browser Cookies
  • 4. File Upload Exceeds Server Limit
  • 5. Clear DNS Cache
  • 6. Deactivate Browser Extensions

Before digging deeper on the different ways to fix the 400 Bad Request error, you may notice that several steps involve flushing locally cached data.

It’s true that if your computer didn’t cache any files or data at all, there would probably be significantly less connection error issues.

However, the benefits of caching files/data are well documented and the web browsing experience would certainly suffer if caching techniques weren’t used by browsers. When it comes to Edge Caching, for example, you can reduce by more than 50% the time required to deliver full pages to browsers.

It all comes down to a compromise between optimization and user experience, where websites try to load as quickly as possible but can occasionally be prone to errors such as a 400 Bad Request without any warning.

1. Check the Submitted URL

As this is one of the most common reasons for a 400 Bad Request error let’s start with an obvious culprit, the URL string itself. It can be very easy to include unwanted characters in the URL when entering it manually in the browser.

Check that the domain name and specific page you’re trying to access are spelled and typed correctly. Also, make sure they’re separated with forward slashes. If the URL contains special characters, make sure they have been encoded correctly and are legal URL characters.

For long URLs, you might find it easier and less error-prone, to use an online URL encoder/decoder. These type of utilities should also be able to detect illegal characters automatically in the URL as well.

Once you’re sure the URL is correct, try to access it again in the browser. If you’re still getting the 400 Bad Request error it’s time to clear some cache!

2. Clear Browser Cache

If any locally stored website files have been corrupted this can cause a 400 Bad Request error to be returned instead of the expected website content.

This includes all types of files a website needs to properly run such as:

  • HTML
  • JavaScript
  • Text/config files
  • CSS
  • Media (images, videos, audio)
  • Data files (XML, JSON)

These files are stored locally on your computer by the browser when the website is originally visited.

To fix this, the browser cache needs to be cleared.

In Chrome, click on the three-dotted icon on the right-hand corner and select the More Tools > Clear Browsing Data from the popup menu.

Clearing the browser cache menu option

Clearing the browser cache menu option

This will display the Clear browsing data window. In here, you’ll want to make sure the Cached images and files option is checked and then click on the Clear data button to clear the browser cache.

You can also choose to delete recent files for a specific time range via the Time range dropdown. However, to make sure all potentially corrupted files are removed we recommend deleting all locally stored files by selecting the All time option.

Clear browsing data options

Clear browsing data options

If you’re using an alternative browser, check this guide for clearing the browser cache for all the major browsers (Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera).

3. Clear Browser Cookies

If clearing your browser cache didn’t work, then it’s time to delete the cookies too. A single website can use dozens of different cookies. If just one of them is expired or becomes corrupted, then it can be enough to trigger a 400 Bad Request.

To clear your cookies in Chrome, open up the Clear browsing data window by clicking the icon with the three dots in the top-right corner and select More Tools > Clear Browsing Data from the popup menu.

Make sure the Cookies and other site data is checked and select All time for the date range option to delete all current website cookies.

Clear browsing data options (cookies)

Clear browsing data options (cookies)

Once done, try loading the website which returned the 400 Bad Request error again. Assuming the site uses cookies, clearing them out from your browser could fix the issue as it’s often associated with corrupt or expired cookies.

To clear cookies in browsers other than Chrome please read this guide here.

4. File Upload Exceeds Server Limit

If you’re trying to upload a file to a website that’s exceeding the server file size limit, you’ll encounter a 400 Bad Request error.

You can test this out by uploading a smaller file first. If this is successful then the initial file is probably too large and you’ll need to find some way to reduce it before uploading it again.

This will depend on the type of file you’re trying to upload but there are plenty of resources available online that can help to compress large images, video, and audio files.

5. Clear DNS Cache

Another common cause of a 400 Bad Request is when local DNS lookup data becomes either corrupted or out-of-date.

Local DNS data isn’t stored by the browser but by the operating system itself. We have put together a detailed guide to clear the DNS cache for Windows and macOS operating systems.

6. Deactivate Browser Extensions

If you have browser extensions installed that affect website cookies then these could actually be the culprit here. Try temporarily disabling them to see if it makes a difference before trying to connect to the website again.

You may not have considered this could be an issue, but it’s certainly worth a try if you’ve exhausted all other options.

Experiencing a 400 Bad Request error? Check out our detailed guide on how to fix it once and for all! ❌🦊Click to Tweet

Summary

If you’re experiencing a 400 Bad Request error there are several actions you can perform to try and fix the issue.

In the vast majority of possible scenarios, a 400 Bad Request is a client-side issue caused by the submitted request to the server or a local caching issue. The solutions outlined in this article are easy to implement by anyone with minimal technical knowledge. You should be able to get your website working again in no time!

On occasions, though, a 400 Bad Request status code could hint to a generic server issue. This can be quickly diagnosed by testing the given site on different devices. If you suspect this to be a server-side error, there’s not much you can do other than keep trying to load the site at regular intervals and inform the site admin.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

When a website fails to load, it’s simply annoying. It’s important to understand, though, why that happened so you know how to fix it.

The 4xx family of status codes is the one we’re investigating here as they relate to invalid or corrupt requests from the client. Specifically, we’ll take a closer look at the 400 Bad Request error: what this error means, what causes it as well as some specific steps to fix the issue.

  • What is 400 Bad Request Error?
  • What Causes a 400 Bad Request Error
  • 400 Bad Request Error: What Does It Look Like?
  • How to Fix 400 Bad Request Error

Check out our video guide to fixing 400 errors:

What is a 400 Bad Request Error?

A 400 Bad Request, also known as a 400 error or HTTP error 400, is perceived by the server as a generic client error and it is returned when the server determines the error doesn’t fall in any of the other status code categories.

The key concept to understand here is that the 400 Bad Request error is something that has to do with the submitted request from the client before it is even processed by the server.

The Internet Engineering Task Force (IETF) defines the 400 Bad Request as:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

What Causes the HTTP 400 Bad Request Error?

There are various root causes that can trigger the 400 Bad Request error and, even if this error isn’t specific to any particular browser or OS (operating system), the fixes do vary slightly.

1. URL String Syntax Error

The HTTP error 400 can occur due to incorrectly typed URL, malformed syntax, or a URL that contains illegal characters.

This is surprisingly easy to do by mistake and can happen if a URL has been encoding incorrectly. The following link is an example of a URL containing characters the server won’t be able to process, hence a 400 Bad Request error is triggered.

https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL

Note the extra % character immediately after the word malformed in the URL. A properly encoded space should be %20 and not %%20. This is what the result looks like in the Chrome browser.

An illegal character can also trigger a 400 Bad request error. The following URL contains a { character, which is not allowed. Therefore, it results in the same type of error.

https://twitter.com/share?lang=en&text=Example%20of%20malformed{%20characters%20in%20URL

2. Corrupted Browser Cache & Cookies

Even if the URL is 100% correct, the 400 Bad Request error can still occur because of corrupted files in the browser cache or problems with expired/corrupted browser cookies.

You may have encountered a 400 Bad Request error when trying to access the admin area of your WordPress site some time after your last log in. That’s happening because of the way the cookie handling your login authentication data may have gotten corrupted and can’t successfully authenticate you as a valid user with admin privileges. This will then result in the connection being refused and a 400 Bad Request error is triggered.

3. DNS Lookup Cache

The 400 Bad Request can happen when the DNS data stored locally is out of sync with registered DNS information.

All domain names are aliases for IP addresses. You can think of an IP address as a phone number “always calling” a specific server you want to connect to. When you first visit a website, a process called “name resolution” takes place and that’s when the domain name resolves to the specific IP address of the server.

To speed things up, these details are stored locally on your computer in the local DNS cache so the name resolution process doesn’t have to be done for every single visit for a given website. This is similar to how the browser cache works for HTML, CSS, JavaScript, media, and other files.

4. File Size Too Large

A 400 Bad Request can also occur when you try to upload a file to a website that’s too large for the upload request to be fulfilled. This is strictly related to the file size limit of the server and will vary based on how it has been set up.

Until now, we’ve focused on the 400 Bad Request error being triggered only due to client-side issues.

5. Generic Server Error

This error can sometimes be triggered because of server-side issues as well. Specifically, a 400 status code could indicate a general problem with the server, a server glitch, or other unspecified temporary issues.

If this happens when trying to connect to a third-party website, it’s really outside of your control and your best shot is to try refreshing the browser and check at regular intervals whether the issue has been fixed by the site owners.

One thing you can do to verify the issue is a server-side issue is to try loading the website on different browsers. If you want to go the extra mile, test it on an entirely different machine/device to rule out system-specific problems.

When you can’t connect to the site via any other browsers, computers, operating systems, or other devices then it’s likely to be a server-side issue. If you’d like, you can reach out to the site owner and let them know which OS, browser, and versions you were using when experienced the issue.

400 Bad Request Error: What Does It Look Like?

Most of the time a 400 Bad Request is related to client-side issues. We already saw what a 400 Bad Request error looks like in the Chrome browser.

400 bad request error in Chrome

400 bad request error in Chrome

But what about the other browsers?

400 Bad Request in Firefox

400 bad request error in Firefox

400 bad request error in Firefox

400 Bad Request in Safari

400 bad request error in Safari

400 bad request error in Safari

400 Bad Request in Microsoft Edge

400 bad request error in Microsoft Edge

400 bad request error in Microsoft Edge

As you can see, all browsers return a generic and unhelpful 400 status code message. It seems you’re pretty much left alone for finding a solution to the problem. In Firefox and Safari, it’s not even clear a 400 Bad Request error has occurred at all as the browser window is completely blank!

Fortunately, we’ve put together a series of simple steps you can take to fix the 400 Bad Request error. Let’s take a closer look at each one of these in the next section!

400 Bad Request (Glossary):

The 400 Bad Request Error is an HTTP response status code
that indicates the server was unable to process (understand) the request sent by the client due to incorrect syntax, invalid request message framing, or deceptive request routing.

How to Fix 400 Bad Request Error?

Complete the steps outlined in this section to help diagnose and correct a 400 Bad Request.

The proposed solutions include:

  • 1. Check the Submitted URL
  • 2. Clear Browser Cache
  • 3. Clear Browser Cookies
  • 4. File Upload Exceeds Server Limit
  • 5. Clear DNS Cache
  • 6. Deactivate Browser Extensions

Before digging deeper on the different ways to fix the 400 Bad Request error, you may notice that several steps involve flushing locally cached data.

It’s true that if your computer didn’t cache any files or data at all, there would probably be significantly less connection error issues.

However, the benefits of caching files/data are well documented and the web browsing experience would certainly suffer if caching techniques weren’t used by browsers. When it comes to Edge Caching, for example, you can reduce by more than 50% the time required to deliver full pages to browsers.

It all comes down to a compromise between optimization and user experience, where websites try to load as quickly as possible but can occasionally be prone to errors such as a 400 Bad Request without any warning.

1. Check the Submitted URL

As this is one of the most common reasons for a 400 Bad Request error let’s start with an obvious culprit, the URL string itself. It can be very easy to include unwanted characters in the URL when entering it manually in the browser.

Check that the domain name and specific page you’re trying to access are spelled and typed correctly. Also, make sure they’re separated with forward slashes. If the URL contains special characters, make sure they have been encoded correctly and are legal URL characters.

For long URLs, you might find it easier and less error-prone, to use an online URL encoder/decoder. These type of utilities should also be able to detect illegal characters automatically in the URL as well.

Once you’re sure the URL is correct, try to access it again in the browser. If you’re still getting the 400 Bad Request error it’s time to clear some cache!

2. Clear Browser Cache

If any locally stored website files have been corrupted this can cause a 400 Bad Request error to be returned instead of the expected website content.

This includes all types of files a website needs to properly run such as:

  • HTML
  • JavaScript
  • Text/config files
  • CSS
  • Media (images, videos, audio)
  • Data files (XML, JSON)

These files are stored locally on your computer by the browser when the website is originally visited.

To fix this, the browser cache needs to be cleared.

In Chrome, click on the three-dotted icon on the right-hand corner and select the More Tools > Clear Browsing Data from the popup menu.

Clearing the browser cache menu option

Clearing the browser cache menu option

This will display the Clear browsing data window. In here, you’ll want to make sure the Cached images and files option is checked and then click on the Clear data button to clear the browser cache.

You can also choose to delete recent files for a specific time range via the Time range dropdown. However, to make sure all potentially corrupted files are removed we recommend deleting all locally stored files by selecting the All time option.

Clear browsing data options

Clear browsing data options

If you’re using an alternative browser, check this guide for clearing the browser cache for all the major browsers (Mozilla Firefox, Safari, Internet Explorer, Microsoft Edge, Opera).

3. Clear Browser Cookies

If clearing your browser cache didn’t work, then it’s time to delete the cookies too. A single website can use dozens of different cookies. If just one of them is expired or becomes corrupted, then it can be enough to trigger a 400 Bad Request.

To clear your cookies in Chrome, open up the Clear browsing data window by clicking the icon with the three dots in the top-right corner and select More Tools > Clear Browsing Data from the popup menu.

Make sure the Cookies and other site data is checked and select All time for the date range option to delete all current website cookies.

Clear browsing data options (cookies)

Clear browsing data options (cookies)

Once done, try loading the website which returned the 400 Bad Request error again. Assuming the site uses cookies, clearing them out from your browser could fix the issue as it’s often associated with corrupt or expired cookies.

To clear cookies in browsers other than Chrome please read this guide here.

4. File Upload Exceeds Server Limit

If you’re trying to upload a file to a website that’s exceeding the server file size limit, you’ll encounter a 400 Bad Request error.

You can test this out by uploading a smaller file first. If this is successful then the initial file is probably too large and you’ll need to find some way to reduce it before uploading it again.

This will depend on the type of file you’re trying to upload but there are plenty of resources available online that can help to compress large images, video, and audio files.

5. Clear DNS Cache

Another common cause of a 400 Bad Request is when local DNS lookup data becomes either corrupted or out-of-date.

Local DNS data isn’t stored by the browser but by the operating system itself. We have put together a detailed guide to clear the DNS cache for Windows and macOS operating systems.

6. Deactivate Browser Extensions

If you have browser extensions installed that affect website cookies then these could actually be the culprit here. Try temporarily disabling them to see if it makes a difference before trying to connect to the website again.

You may not have considered this could be an issue, but it’s certainly worth a try if you’ve exhausted all other options.

Experiencing a 400 Bad Request error? Check out our detailed guide on how to fix it once and for all! ❌🦊Click to Tweet

Summary

If you’re experiencing a 400 Bad Request error there are several actions you can perform to try and fix the issue.

In the vast majority of possible scenarios, a 400 Bad Request is a client-side issue caused by the submitted request to the server or a local caching issue. The solutions outlined in this article are easy to implement by anyone with minimal technical knowledge. You should be able to get your website working again in no time!

On occasions, though, a 400 Bad Request status code could hint to a generic server issue. This can be quickly diagnosed by testing the given site on different devices. If you suspect this to be a server-side error, there’s not much you can do other than keep trying to load the site at regular intervals and inform the site admin.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Должен проверять имя, если оно совпадает, то мутить человека.

@bot.message_handler(content_types=["new_chat_members"])
def cmd_mute(message): 
    name = message.from_user.first_name
    if name == 'Кто-то':
        bot.restrict_chat_member(message.chat.id, message.from_user.id,can_send_messages=False,can_send_media_messages=True,can_send_other_messages=True,can_add_web_page_previews=True,until_date=1)
        bot.send_message(message.chat_id, 'Успешно')

Ошибка:

File ".main.py", line 10, in cmd_mute
    bot.restrict_chat_member(message.chat.id, message.from_user.id,can_send_messages=False,can_send_media_messages=True,can_send_other_messages=True,can_add_web_page_previews=True,until_date=1)
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: method is available only for supergroups"}']

Should check the name, if it’s the same, then screw the person.

@bot.message_handler(content_types=["new_chat_members"])
def cmd_mute(message):
name = message.from_user.first_name
if name == 'Кто-то':
bot.restrict_chat_member(message.chat.id, message.from_user.id,can_send_messages=False,can_send_media_messages=True,can_send_other_messages=True,can_add_web_page_previews=True,until_date=1)
bot.send_message(message.chat_id, 'Успешно')

Error:

File ".main.py", line 10, in cmd_mute
bot.restrict_chat_member(message.chat.id, message.from_user.id,can_send_messages=False,can_send_media_messages=True,can_send_other_messages=True,can_add_web_page_previews=True,until_date=1)
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: method is available only for supergroups"}']

So the first error is saying it doesn’t like the group because its a supergroup… and the second error says it can’t use a certain command because its NOT a supergroup…. however the bot automatically bans someone i’m trying to unban…. i need this to work. how can i make it work?

TelegramError: 400: Bad Request: group chat was upgraded to a supergroup chat
    at /app/node_modules/telegraf/core/network/client.js:281:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 1)
    at nowarnsHandler (/app/handlers/commands/nowarns.js:46:3)
    at removeCommandsHandler (/app/handlers/middlewares/removeCommands.js:22:2)
    at async Promise.all (index 0) {
  code: 400,
  response: {
    ok: false,
    error_code: 400,
    description: 'Bad Request: group chat was upgraded to a supergroup chat',
    parameters: { migrate_to_chat_id: -1001201784679 }
  },
  description: 'Bad Request: group chat was upgraded to a supergroup chat',
  parameters: { migrate_to_chat_id: -1001201784679 },
  on: {
    method: 'unbanChatMember',
    payload: { chat_id: -364298668, user_id: 183356440 }
  }
}
TelegramError: 400: Bad Request: method is available for supergroup and channel chats only
    at /app/node_modules/telegraf/core/network/client.js:281:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 4)
    at unbanHandler (/app/handlers/commands/unban.js:39:2)
    at removeCommandsHandler (/app/handlers/middlewares/removeCommands.js:22:2)
    at async Promise.all (index 0) {
  code: 400,
  response: {
    ok: false,
    error_code: 400,
    description: 'Bad Request: method is available for supergroup and channel chats only'
  },
  description: 'Bad Request: method is available for supergroup and channel chats only',
  parameters: {},
  on: {
    method: 'unbanChatMember',
    payload: { chat_id: -246215113, user_id: 183356440 }
  }
}
TelegramError: 400: Bad Request: method is available for supergroup and channel chats only
    at /app/node_modules/telegraf/core/network/client.js:281:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 0)
    at unbanHandler (/app/handlers/commands/unban.js:39:2)
    at removeCommandsHandler (/app/handlers/middlewares/removeCommands.js:22:2)
    at async Promise.all (index 0) {
  code: 400,
  response: {
    ok: false,
    error_code: 400,
    description: 'Bad Request: method is available for supergroup and channel chats only'
  },
  description: 'Bad Request: method is available for supergroup and channel chats only',
  parameters: {},
  on: {
    method: 'unbanChatMember',
    payload: { chat_id: -293457926, user_id: 183356440 }
  }
}

this is my code

private async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
    {

        var message = e.Message; if (message == null || message.Type != MessageType.Text) return; await Bot.SendTextMessageAsync(message.Chat.Id, "Hello?");

in this case, it works well with super groups

but
await Bot.SendTextMessageAsync([supergroup chat id], «Hello?»);

put Super Group ID in here[supergroup chat id], it won’t work.
I’ve set up all the group permissions.
After upgrading the super group, I had to drop the bot and invite again

asked Oct 8, 2018 at 17:18

syaneteu's user avatar

2

Just in case if you are haven’t figured it out already… When a group is upgraded to supergroup, new ID is generated:

{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: group chat was upgraded to a supergroup chat",
    "parameters": {
        "migrate_to_chat_id": -1001432162429
    }
}

Use this migrate_to_chat_id to send messages

answered Jun 18, 2019 at 12:53

piyushkantm's user avatar

piyushkantmpiyushkantm

5745 silver badges19 bronze badges

0

If you can’t see the above ‘migrate_to_chat_id’ field mentioned by piyushkantm you can
use:

bot.on('message', (msg) => {
    const chatId = msg.chat.id;
    console.log(chatId);
});

When your request fails send a test message to the group via mobile phone the above will return your updated super group chat.id.

answered May 19, 2021 at 11:34

David Robery's user avatar

  • Ошибка телевизора е16 4
  • Ошибка текущий разделитель требуется битрикс
  • Ошибка текущий домен не валидный bitrix
  • Ошибка текущий вошедший пользователь не обладает правами администратора
  • Ошибка текущий вошедший пользователь не имеет привилегий владельца на файл или папку