Telegram ошибка 429

We have a Telegram bot. It has around 1.2 million subscribers.

Now we’re facing a problem in sending messages to these number of subscribers.

Telegram bot API does not provide any batch message functionality and we’d have to send individual requests to Telegram. The problem is, after a few thousand messages, Telegram starts responding with Error 429: too many requests, and does not accept any requests for a while.

How can we effectively message our subscribers?

Pang's user avatar

Pang

9,481146 gold badges81 silver badges122 bronze badges

asked Aug 10, 2015 at 7:39

Pooya Saberian's user avatar

Pooya SaberianPooya Saberian

9532 gold badges9 silver badges16 bronze badges

2

You should simply implement a global rate limiter to ensure no single user gets above a fixed number of messages per second. to be safe, set your limiter at lower than 30, maybe even to 5 msgs per second.

Really anything higher than 5 messages per second to a single user quickly becomes an annoyance.

cheers.

answered Jan 21, 2016 at 15:11

Charles Okwuagwu's user avatar

Charles OkwuagwuCharles Okwuagwu

10.4k16 gold badges87 silver badges154 bronze badges

2

I’m the owner of Ramona Bot.
There is a limit for sending message to users. as they said ~30 message per second. Otherwise you will get that Error 429.

answered Oct 2, 2015 at 11:20

alixrx's user avatar

1

Based on the Telegram Bots FAQ for sending messages, you should consider this:

If you’re sending bulk notifications to multiple users, the API will not allow more than 30 messages per second or so. Consider spreading out notifications over large intervals of 8—12 hours for best results.

Pang's user avatar

Pang

9,481146 gold badges81 silver badges122 bronze badges

answered Apr 14, 2020 at 8:22

Hossein's user avatar

HosseinHossein

8181 gold badge9 silver badges31 bronze badges

1

I had similar problems with messages, the pause between which was 0.5 seconds (this is much less than 30 messages per second!). The problem was only associated with messages, the content of which I tried to change. So when you try to use «edit_message_text» or «edit_message_media» take more pause between messages.

answered Jul 1, 2021 at 16:03

Александр Щербаков's user avatar

It can happen also if a Telegram group is in the slow mode and the bot tries to send more that one message at once to that group. I fixed this by adding a delay to the bot trigger mechanism.

answered Nov 24, 2022 at 7:41

Saeed Mohtasham's user avatar

hey_umbrella, питон не знаю, потому чисто алгоритмически распишу.

организация очереди:
1. создается своя библиотека/модуль/пакет содержащий:
— в самом простом случае пустой массив
— экспортируемую функцию отправки сообщения, например sendMessage, принимающую в качестве параметров ID группы/канала/пользователя которому необходимо отправить сообщение и само сообщение. Данная функция просто добавляет в массив объект содержащий эти 2 параметра
— внутри библиотеки средствами python (Timer) организуется бесконечный асинхронный цикл, срабатывающий раз в секунду который делает следующее
— проверяет массив на наличие в нем записей
— если записи есть то вынимает (достает удаляя из массива) 30 записей и в цикле обрабатывает каждую, отправляя сообщение адресату

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

Это очень примитивный пример, но для понимания механизмов самое то. А как справитесь — замените массив на БД, добавте в таймер проверку на то были ли фактически отправлены предыдущие 30 сообщений и получил ли их сервер и многое другое. Там вы уже сами начнете видеть ситуацию и возможные пути решения возникающих проблем.

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 human-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.
  • bot_only — A list of methods that can only be used by bots, not users.

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"
    ],
    "bot_only": [
        "messages.setInlineBotResults"
    ]
}

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 was 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.

Вопрос:

У нас бот телеграмм, у него около 1,2 миллиона подписчиков.

Теперь возникла проблема с отправкой сообщения этим количеством подписчиков.

API Telegram bot API не предоставляет никаких функций пакетного сообщения, и мы должны отправлять отдельные запросы в телеграмму. Проблема состоит в том, что после нескольких тысяч сообщений, телеграмма начинает отвечать с ошибкой 429: слишком много запросов и не принимает никаких запросов какое-то время.

Как мы можем эффективно сообщать нашим подписчикам?

Ответ №1

Я владелец Ramona Bot.
Существует ограничение на отправку сообщений пользователям. как они сказали ~ 30 сообщений в секунду. В противном случае вы получите ошибку 429.

Ответ №2

Вы должны просто реализовать глобальный ограничитель скорости, чтобы ни один пользователь не превышал фиксированное количество сообщений в секунду. чтобы быть в безопасности, установите ограничитель ниже 30, может быть, даже до 5 msgs в секунду.

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

приветствий.

@karb0f0s I just tested, but I’m still unable to catch ApiRequestException. It’s still throwing an HttpRequestException with the message «Response status code does not indicate success: 429 (Too Many Requests).»

For testing, I did the following:

while (true)
    await Bot.SendTextMessageAsync(e.Message.Chat.Id, "Echo!");

And that method does the following:

public static async Task<Message> SendTextMessageAsync(ChatId chatId, string text, ParseMode parseMode = ParseMode.Default, bool disableWebPagePreview = false, bool disableNotification = false, int replyToMessageId = 0, IReplyMarkup replyMarkup = null, CancellationToken cancellationToken = default)
{
    try
    {
        return await Client.SendTextMessageAsync(chatId, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, replyMarkup, cancellationToken);
    }
    catch (ApiRequestException e)
    {
        await Task.Delay(e.Parameters.RetryAfter);
        return await Client.SendTextMessageAsync(chatId, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, replyMarkup, cancellationToken);
    }
    catch (HttpRequestException)
    {
        await Task.Delay(10000);
    }

    return new Message();
}

After 21 successful sent messages, an HttpRequestException is thrown.

Понравилась статья? Поделить с друзьями:
  • Telegram ошибка 400
  • Telegram ошибка 0xc0000005
  • Telegram внутренняя ошибка сервера
  • Telegram org dl ошибка
  • Telegram api коды ошибок