Telegram error 403 forbidden bot was blocked by the user

Error handling There will be errors when working with the API, and they must be correctly handled on the client. An error is characterized by several

Error handling

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:

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.

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.

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.

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:

The request must be repeated, but directed to a different data center.

  • 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 »

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.

  • 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

There was an unauthorized attempt to use functionality available only to authorized users.

  • 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

Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user.

An attempt to invoke a non-existent object, such as a method.

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.

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.

  • FLOOD_WAIT_X: A wait of X seconds is required (where X is a number)

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.

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.

Источник

Telegram error 403 forbidden bot was blocked by the user

Here is a collection of frequently asked questions regarding common errors and Deno things.

If this FAQ does not answer your question, you should also have a look at the Bot FAQ

open in new window written by the Telegram team.

# Why Am I Getting This Error?

# 400 Bad Request: Cannot parse entities

You are sending a message with formatting, i.e. you’re setting parse _mode when sending a message. However, your formatting is broken, so Telegram does not know how to parse it. You should re-read the section about formatting

open in new window in the Telegram docs. The byte offset that is mentioned in the error message will tell you where exactly the error is in your string.

Passing entities instead of formatting

You can pre-parse the entities for Telegram if you want, and specify entities when sending your message. Your message text could then be a regular string. That way, you don’t have to worry about escaping weird characters. This may look like it needs more code, but in fact it is the far more reliable and fool-proof solution to this problem. Most importantly, this is greatly simplified by our parse -mode plugin.

# 401 Unauthorized

Your bot token is wrong. Maybe you think it’s right. It is not. Talk to @Bot Father

open in new window to see what your token is.

# 403 Forbidden: bot was blocked by the user

You probably tried to send a message to a user and then you ran into this issue.

When a user blocks your bot, you are no able to send messages to them or interact with them in any other way (except if your bot was invited to a group chat where the user is a member). Telegram does this to protect their users. You cannot do anything about it.

  • Handle the error and for example delete the user’s data from your database.
  • Ignore the error.
  • Listen for my _chat _member updates via bot .on(«my _chat _member») in order to be notified when the user blocks your bot. Hint: Compare the status fields of the old and the new chat member.

# 404 Not found

If this happens while starting your bot, then your bot token is wrong. Talk to @Bot Father

open in new window to see what your token is.

If your bot works fine most of the time, but then suddenly you’re getting a 404, then you’re doing something very funky. You can come ask us in the group chat

# 409 Conflict: terminated by other getUpdates request

You are accidentally running your bot twice on long polling. You can only run one instance of your bot.

If you think that you only run your bot once, you can just revoke the bot token. That will stop all other instances. Talk to @Bot Father

# 429: Too Many Requests: retry after X

Congratulations! You ran into an error that is among the most difficult ones to fix.

There are two possible scenarios:

One: Your bot does not have many users. In that case, you are just spamming the Telegram servers by sending too many requests. Solution: don’t do that! You should seriously think about how to reduce the number of API calls substantially.

Two: Your bot is getting very popular and it has a lot of users (hundreds of thousands). You have already made sure to use the minimum number of API calls for the most common operations of your bot, and still you’re running into these errors (called flood wait).

There are a few things you can do:

  1. Read this article in the docs to gain a basic understanding of the situation.
  2. Use the transformer -throttler plugin.
  3. Use the auto -retry plugin.
  4. Come ask us in the group chat

open in new window for help. We have experienced people there.

  • It is possible to ask Telegram to increase the limits, but this is very unlikely to happen if you did not do steps 1-3 first.
  • # Cannot find type definition file for ‘node-fetch’

    This is the result of some missing type declarations.

    The recommended way to fix this is to set skip Lib Check to true in your TypeScript compile options.

    If you are sure that you need this option to be kept to false , you can instead install the missing type definitions by running npm i -D @types /node -fetch@2 .

    # Questions About Deno

    # Why do you support Deno?

    Some important reasons why we like Deno more than Node.js:

    • It’s simpler and faster to get started.
    • The tooling is substantially better.
    • It natively executes TypeScript.
    • No need to maintain package .json or node _modules .
    • It has a reviewed standard library.

    Источник

    Error Handling #77

    Comments

    amastaneh commented Jan 26, 2016

    We have some errors result on SendTextMessage which make throw error exceptions and make slow processes. Is there any solution we safe receive these errors.
    https://core.telegram.org/method/messages.sendMessage#return-errors

    We have 403 FORBIDDEN exception when we SendTextMessage to user which blocked the bot.
    https://core.telegram.org/api/errors

    The text was updated successfully, but these errors were encountered:

    MrRoundRobin commented Jan 26, 2016

    the links are specific to the normal telegram api, not the bot api.
    I’ll need to test the case when a bot is blocked, stay tuned.

    amastaneh commented Jan 27, 2016

    Scenario 1
    We SendTextMessage from a bot to a group, right after removing from group.

    amastaneh commented Jan 27, 2016

    Scenario 2
    We SendTextMessage from a bot to a unknown channel

    amastaneh commented Jan 27, 2016

    Scenario 3
    We SendTextMessage from a bot to a user, right after stop and blocking bot by this user

    MrRoundRobin commented Jan 27, 2016

    These errors should be thrown as an ApiException.

    Can you catch these?

    amastaneh commented Jan 27, 2016

    Exception Handling is a heavy and expensive operation as far as performance is concerned [ref]

    We need receive these errors normally (not with an exception) and make decision based on these received messages. Anyway you can find out more respectful documents about error handling with Condition Checking is so better than Exception Handling

    I think SendTextMessage need an output from ResultMessage class like

    MrRoundRobin commented Jan 28, 2016

    ok, i need to think about this

    Bouki6 commented Jan 30, 2016

    These errors should be thrown as an ApiException.

    Can you catch these?

    i also test it. i cant catch any exemptions with ApiException. if there was a exception we catch it like this:

    funny thing is in previous releases you return the error description but in new version you just return the error code. i hope you can fix it soon. thank you.

    ghost commented Mar 4, 2016

    bot.sendMessage(‘@medve_dev’, ‘test BOt’);
    send to username response

    Unhandled rejection Error: 400

    mhverbakel commented Jul 6, 2016 •

    I think that the implementation without throwing exceptions would result in a silent fail for most users. As this is undesirable, I am against changing to condition checking instead of exception handling.

    It could be implemented in a manner where the two can gracefully live together, by providing a TryXxx method for every method that returns Task , and then reusing that internally.

    On the other hand, it would be a good idea to include the error description in the ApiException class.

    a-a-k commented Sep 2, 2016

    When async methods like SendTextMessageAsync() are used standalone (without user request) then bot will be frozen if he was stopped or blocked by user. Sync methods like SendTextMessage() works correct in this case.
    How can I resolve this?

    mhverbakel commented Sep 2, 2016

    First of all, for a new issue, open a new issue.

    Secondly, the two functions you are referring to are literally the same. The non Async methods call the Async methods without doing anything. This is probably an issue in your own code.

    If you make a new issue and share your code there, we might be able to help you.

    Kind regards,
    Martijn Verbakel

    a-a-k commented Sep 2, 2016

    Dear Matijn, thank you for your response, but what does it mean?

    The non Async methods call the Async methods without doing anything.

    And I think that this is not new issue conversely this is exactly not handled error problem. Do you not think so? I’m really don’t understand what you meant.

    Olfi01 commented Jul 2, 2017

    @a-a-k this might be a bit late, but the normal method just looks like this:
    `public void SendTextMessage(params)
    <
    SendTextMessageAsync(params);
    >

    so its not a difference at all.
    and the difference is, if you don’t wait for the async method to finish with .Wait(), the exception won’t be thrown, so i assume you probably DO wait for them and thus get the errors they fire.

    Olfi01 commented Jul 2, 2017

    And @amastaneh : i don’t think changing the errors to statuses that have to be checked first is an option. After all, this is just a c# implementation for the API and not like a whole control panel for a bot that takes over everything for you.

    amastaneh commented Jul 2, 2017

    Dear @Olfi01 & @mhverbakel
    Thank you for your attention and try to help. The issue is about Condition Checking versus Exception Handling

    1- I think logic and performance come with condition checking.
    2- Also, In sending mass messages in a loop (or in other similar scenarios) exception after a simple SendMessage make stop the routine process. But return a simple result when the bot is blocked from some users (or groups) is better than throw. Some of programs need continue to sending without exception interrupts.
    3- The blocking result or any other situations are simple conditions. Did you think we need throw exception when we face with some conditions or some situations at all?

    Olfi01 commented Jul 2, 2017

    @amastaneh i think we should indeed throw exeptions. if you really want conditions, just catch those by yourself. Making it conditions would, as @mhverbakel said, result in a silent fail for those user who arent capable of bulding themselves a workaround. Don’t you think it would be better to leave them able to determine the cause of whats happening than you not having to code a single try-catch-loop? if youre sending mass messages, just do it like for example
    while(condition) < try < //send Message >catch < //handle Exception >>
    Since I myself used this library even back since I was a little noob, I prefer simplicity before logical correctness.

    Footer

    © 2023 GitHub, Inc.

    You can’t perform that action at this time.

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

    Источник

    Собственно проблема, как научить бота проверять заблокирован ли юзер:

    [2018-04-04 06:49:09,913] ERROR in app: Exception on / [POST]
    2018-04-04 06:49:09,924: Traceback (most recent call last):
    2018-04-04 06:49:09,924: File «/home/Mlpprv/venv/lib/python3.6/site-packages/flask/app.py», line 1982, in wsgi_app
    2018-04-04 06:49:09,924: response = self.full_dispatch_request()
    2018-04-04 06:49:09,924: File «/home/Mlpprv/venv/lib/python3.6/site-packages/flask/app.py», line 1614, in full_dispatch_request
    2018-04-04 06:49:09,924: rv = self.handle_user_exception(e)
    2018-04-04 06:49:09,924: File «/home/Mlpprv/venv/lib/python3.6/site-packages/flask/app.py», line 1517, in handle_user_exception
    2018-04-04 06:49:09,924: reraise(exc_type, exc_value, tb)
    2018-04-04 06:49:09,924: File «/home/Mlpprv/venv/lib/python3.6/site-packages/flask/_compat.py», line 33, in reraise
    2018-04-04 06:49:09,924: raise value
    2018-04-04 06:49:09,925: File «/home/Mlpprv/venv/lib/python3.6/site-packages/flask/app.py», line 1612, in full_dispatch_request
    2018-04-04 06:49:09,925: rv = self.dispatch_request()
    2018-04-04 06:49:09,925: File «/home/Mlpprv/venv/lib/python3.6/site-packages/flask/app.py», line 1598, in dispatch_request
    2018-04-04 06:49:09,925: return self.view_functions[rule.endpoint](**req.view_args)
    2018-04-04 06:49:09,925: File «/home/Mlpprv/bot/main.py», line 2345, in index
    2018-04-04 06:49:09,925: reply_markup=user_markup)
    2018-04-04 06:49:09,925: File «/home/Mlpprv/venv/lib/python3.6/site-packages/telebot/__init__.py», line 470, in send_message
    2018-04-04 06:49:09,925: reply_markup, parse_mode, disable_notification))
    2018-04-04 06:49:09,925: File «/home/Mlpprv/venv/lib/python3.6/site-packages/telebot/apihelper.py», line 135, in send_message
    2018-04-04 06:49:09,925: return _make_request(token, method_url, params=payload, method=’post’)
    2018-04-04 06:49:09,926: File «/home/Mlpprv/venv/lib/python3.6/site-packages/telebot/apihelper.py», line 56, in _make_request
    2018-04-04 06:49:09,926: return _check_result(method_name, result)[‘result’]
    2018-04-04 06:49:09,926: File «/home/Mlpprv/venv/lib/python3.6/site-packages/telebot/apihelper.py», line 75, in _check_result
    2018-04-04 06:49:09,926: raise ApiException(msg, method_name, result)
    2018-04-04 06:49:09,926: telebot.apihelper.ApiException: A request to the Telegram API was unsuccessful. The server returned HTTP 403 Forbidden. Response body:
    2018-04-04 06:49:09,926: [b'{«ok»:false,»error_code»:403,»description»:»Forbidden: bot was blocked by the user»}’]

    Есть мысль, что через try-except
    Не понимаю, что именно писать в except для обхода ошибки
    Бот начинает зацикливаться и, как следствие, падает и перестает вообще отвечать.

    New issue

    Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

    By clicking “Sign up for GitHub”, you agree to our terms of service and
    privacy statement. We’ll occasionally send you account related emails.

    Already on GitHub?
    Sign in
    to your account


    Closed

    kultpro opened this issue

    May 19, 2021

    · 17 comments

    Assignees

    @bostrot

    Comments

    @kultpro

    I encountered the following errors

    • The bot only works with nodejs v10. 24. 1 (npm v6. 14. 12)

    • If the user deletes the bot and checks «stop bot», the bot crashes with errors:

      Error:
      Failed to process updates. Error: Telegraf: "reply" isn't available for "undefined::"
          at TelegrafContext.assert (/root/telegram-support-bot/node_modules/telegraf/context.js:172:13)
          at TelegrafContext.reply (/root/telegram-support-bot/node_modules/telegraf/context.js:314:10)
          at Telegraf.bot.catch [as handleError] (/root/telegram-support-bot/src/index.ts:94:7)
          at middleware.catch (/root/telegram-support-bot/node_modules/telegraf/telegraf.js:171:55)
          at process._tickCallback (internal/process/next_tick.js:68:7)
      

    @bostrot

    Just experienced something similar with this addition:

    bot002    | === UNHANDLED REJECTION ===
    bot002    | 'Sat May 15 2021 21:04:25 GMT+0000 (Coordinated Universal Time): Error: 403: Forbidden: bot was blocked by the usern' +
    bot002    |   '    at /bot/node_modules/telegraf/core/network/client.js:281:17n' +
    bot002    |   '    at processTicksAndRejections (node:internal/process/task_queues:94:5)'
    

    It continues after restarting the bot so it probably hangs with the telegram polling and crashes before marking it as read..

    I guess we need some checks whether the bot can actually write the user and still mark the message.

    EDIT:

    I could not reproduce that the bot works only with nodejs v10.24.1. Are you missing some dependencies? What is your log? (I tested including v12.22.1, v14.16.1, v16.2, also some others in earlier stages so I guess you are missing something..)

    @bostrot
    bostrot

    changed the title
    Errors

    Error: 403: Forbidden: bot was blocked by the user

    May 20, 2021

    @kultpro

    This started happening after the previous update. Before that, it was put without problems. I install NVM, and then go through the node js versions. In all cases, except for version 10, errors appeared. Perhaps you are right and it’s about dependencies.

    Thank you for your help and quick response!

    @kultpro

    It continues after restarting the bot so it probably hangs with the telegram polling and crashes before marking it as read..

    I guess we need some checks whether the bot can actually write the user and still mark the message.

    If you just delete the bot, then when you reply to the user, the message comes without problems. If the «stop bot» checkbox is checked when deleting a bot,then this is the error.

    @bostrot

    In all cases, except for version 10, errors appeared

    Could you share some logs or the error messages?

    when deleting a bot,then this is the error

    I will try to create a check if the bot is blocked and see if it still does the same.

    @kultpro

    Could you share some logs or the error messages?

    Okay, I’ll do it soon

    @kultpro

    Sometimes your application throws an error of the «Error» type, after which it can continue to work, or it can «hang», and in this case, until I restart, new messages from users do not come. Today there was an error: «b4Error». In debug.log, they are usually not present, or they are also referred to simply as «Error». If I run the app in dev mode, will I collect the errors in a more detailed format?

    @bostrot

    If it shows only «Error» then the actual error message is empty which makes it very hard to debug. Do you know what happened before it showed the message?

    Running in dev mode could give you more details but I can’t say for sure that it shows the actual error message then.

    @bostrot

    Looked into it a bit closer and it seems that commit 9f44bd6 (from issue #52) is the reason:

    ctx.reply('Message is not sent due to an error.');
    

    The bot tries to send an error message to the user but as it is blocked it gets into a loop..

    bostrot

    added a commit
    that referenced
    this issue

    May 25, 2021

    @bostrot

    @bostrot

    Commit 27a707f should be a hotfix for now (for Forbidden: bot was blocked by the user) which catches any error that is thrown by sending an error message to a user that has blocked the bot. Could you try it?

    Also regarding the error messages: npm run dev should give you a little more detail about where they come from.

    @kultpro

    Commit 27a707f should be a hotfix for now (for Forbidden: bot was blocked by the user) which catches any error that is thrown by sending an error message to a user that has blocked the bot. Could you try it?

    Also regarding the error messages: npm run dev should give you a little more detail about where they come from.

    Thanks! I will test it.

    @kultpro

    Updated normally, when the bot is blocked, the app no longer crashes

    @kultpro

    @bostrot

    Thanks for testing and providing the log.

    This seems rather like a better-sqlite3 error. Could you try installing it seperately?

    npm install better-sqlite3 --save

    in your working directory.

    @kultpro

    This seems rather like a better-sqlite3 error. Could you try installing it seperately?

    npm install better-sqlite3 --save

    in your working directory.

    Similar errors again
    https://xpaste.pro/en/p/HvKHfyWp

    @bostrot

    This is a better-sqlite3 build error. Try installing build tools sudo apt-get install build-essential and if that doesn’t work check out their github to find a solution.

    @CodeQuit

    @bostrot

    need fix

    @CodeQuit This is already fixed.

    You get the message when the users blocks/stops the bot. There is nothing you can do once that happened.

    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.

    Here is a collection of frequently asked questions regarding common errors and Deno things.

    If this FAQ does not answer your question, you should also have a look at the Bot FAQopen in new window written by the Telegram team.

    Why Am I Getting This Error?

    400 Bad Request: Cannot parse entities

    You are sending a message with formatting, i.e. you’re setting parse_mode when sending a message. However, your formatting is broken, so Telegram does not know how to parse it. You should re-read the section about formattingopen in new window in the Telegram docs. The byte offset that is mentioned in the error message will tell you where exactly the error is in your string.

    Passing entities instead of formatting

    You can pre-parse the entities for Telegram if you want, and specify entities when sending your message. Your message text could then be a regular string. That way, you don’t have to worry about escaping weird characters. This may look like it needs more code, but in fact it is the far more reliable and fool-proof solution to this problem. Most importantly, this is greatly simplified by our parse-mode plugin.

    Your bot token is wrong. Maybe you think it’s right. It is not. Talk to @BotFatheropen in new window to see what your token is.

    403 Forbidden: bot was blocked by the user

    You probably tried to send a message to a user and then you ran into this issue.

    When a user blocks your bot, you are no able to send messages to them or interact with them in any other way (except if your bot was invited to a group chat where the user is a member). Telegram does this to protect their users. You cannot do anything about it.

    You can either:

    • Handle the error and for example delete the user’s data from your database.
    • Ignore the error.
    • Listen for my_chat_member updates via bot.on("my_chat_member") in order to be notified when the user blocks your bot. Hint: Compare the status fields of the old and the new chat member.

    404 Not found

    If this happens while starting your bot, then your bot token is wrong. Talk to @BotFatheropen in new window to see what your token is.

    If your bot works fine most of the time, but then suddenly you’re getting a 404, then you’re doing something very funky. You can come ask us in the group chatopen in new window (or the Russian-speaking group chatopen in new window).

    409 Conflict: terminated by other getUpdates request

    You are accidentally running your bot twice on long polling. You can only run one instance of your bot.

    If you think that you only run your bot once, you can just revoke the bot token. That will stop all other instances. Talk to @BotFatheropen in new window to do this.

    429: Too Many Requests: retry after X

    Congratulations! You ran into an error that is among the most difficult ones to fix.

    There are two possible scenarios:

    One: Your bot does not have many users. In that case, you are just spamming the Telegram servers by sending too many requests. Solution: don’t do that! You should seriously think about how to reduce the number of API calls substantially.

    Two: Your bot is getting very popular and it has a lot of users (hundreds of thousands). You have already made sure to use the minimum number of API calls for the most common operations of your bot, and still you’re running into these errors (called flood wait).

    There are a few things you can do:

    1. Read this article in the docs to gain a basic understanding of the situation.
    2. Use the transformer-throttler plugin.
    3. Use the auto-retry plugin.
    4. Come ask us in the group chatopen in new window for help. We have experienced people there.
    5. It is possible to ask Telegram to increase the limits, but this is very unlikely to happen if you did not do steps 1-3 first.

    Cannot find type definition file for ‘node-fetch’

    This is the result of some missing type declarations.

    The recommended way to fix this is to set skipLibCheck to true in your TypeScript compile options.

    If you are sure that you need this option to be kept to false, you can instead install the missing type definitions by running npm i -D @types/node-fetch@2.

    Questions About Deno

    Why do you support Deno?

    Some important reasons why we like Deno more than Node.js:

    • It’s simpler and faster to get started.
    • The tooling is substantially better.
    • It natively executes TypeScript.
    • No need to maintain package.json or node_modules.
    • It has a reviewed standard library.

    Deno was founded by Ryan Dahl—the same person that invented Node.js. He summarized his 10 regrets about Node.js in this videoopen in new window.

    grammY itself is Deno-first, and it is backported to support Node.js equally well.

    Добрый день.

    Мы посмотрели, как найти этих «хороших людей».

    Нужно немного модифицировать скрипт отправки офлайн сообщений в телеграм (OfflineMsg2Telegram):

    Код: Выделить всё

    // -----------------------------------------------------------------------------------
    // ver 1.1 / Sep 22, 2017, (c) Alexey Pikurov, [email protected]
    // -----------------------------------------------------------------------------------
    function OnPrivateMessage(iCID, iUIN, iUINTo, iMsgType: integer; sMsg: string): boolean;
    var
      sID, sOutMsg, sNameFrom, s: string;
      bResult: boolean;
    begin
      SetScriptTimeOut(10000);

        result := true;

        if not mIsUINOnline(iUINTo) then begin
          // get sender's Telegram ID
          sID := mIntegrationTelegramGetUserIDByUIN(iUINTo);

            if sID[1] <> '-' then begin // no errors
              // get MyChat sender's display name
              sNameFrom := mGetUserFullNameByPreset(iUIN, 0);

              // convert MyChat message to plaint text
              sOutMsg := mConvertMsgToPlainText(sMsg, iMsgType);

              // add WEB support link and user display name to message
              sOutMsg := '<a href="' +
                         mGetServerExternalAddress(0) +
                         '/support/?uin=' +
                         IntToStr(iUIN) +
                         '&silent">' +
                         sNameFrom +
                         '</a>:' +
                         CRLF +
                         CRLF +
                         sOutMsg;

              // send message to Telegram
              s := mIntegrationTelegramSendMessage(sID, sOutMsg, 5000);
              bResult := true;

                if JSONGetBoolean(s, 'ok', bResult) <> 0 then bResult := false;

                // if any error occured - log result to server's system scripts protocol
                if not bResult then begin
                  s := 'From: ' + IntToStr(iUIN) + ', to: ' + IntToStr(iUINTo) + CRLF + s;
                  mLogScriptToDisk(s);
                end; 
            end;
        end;
    end;

    begin

    end.

    После этого в логе скриптов у вас появится информация, кто кому отправлял и оно не дошло:

    chrome_86PZbx8iBm.png

    chrome_86PZbx8iBm.png (4.06 КБ) Просмотров: 3237

    chrome_EUbX23iFtj.png

    chrome_EUbX23iFtj.png (6.44 КБ) Просмотров: 3237

    Live Chat со мной

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

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

    400 Bad Request (32 error type)

    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: BOT_SCORE_NOT_MODIFIED"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: CHAT_ADMIN_REQUIRED"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: ENTITY_MENTION_USER_INVALID"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: MESSAGE_ID_INVALID"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: QUERY_ID_INVALID"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: RESULT_TYPE_INVALID"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: USER_ID_INVALID"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't demote chat creator"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Can't find end of the entity starting at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Can't found end tag corresponding to start tag at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Expected end tag at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Expected equal sign in declaration of attribute of the tag "foo" at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Unclosed end tag at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Unclosed start tag at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Unexpected end of name token at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Unexpected end tag at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Unmatched end tag at byte offset X, expected "", found"""
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: can't parse entities in message text: Unsupported start tag foo at byte offset X"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: channel members are unavailable"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: chat not found"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: failed to get HTTP URL content"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: have no rights to send a message"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message can't be edited"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message can't be forwarded"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message is not modified"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message must be non-empty"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message text is empty"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message to delete not found"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: message to forward not found"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: reply message not found"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: wrong file identifier/HTTP URL specified"
    }
    
    {
      "ok": false,
      "error_code": 400,
      "description": "Bad Request: wrong persistent file_id specified: can't unserialize it. Wrong last symbol"
    }
    
    Others (9 error type)

    {
      "ok": false,
      "error_code": 401,
      "description": "Unauthorized"
    }
    
    {
      "ok": false,
      "error_code": 403,
      "description": "Forbidden: bot can't initiate conversation with a user"
    }
    
    {
      "ok": false,
      "error_code": 403,
      "description": "Forbidden: bot can't send messages to bots"
    }
    
    {
      "ok": false,
      "error_code": 403,
      "description": "Forbidden: bot is not a member of the supergroup chat"
    }
    
    {
      "ok": false,
      "error_code": 403,
      "description": "Forbidden: bot was blocked by the user"
    }
    
    {
      "ok": false,
      "error_code": 403,
      "description": "Forbidden: bot was kicked from the group chat"
    }
    
    {
      "ok": false,
      "error_code": 403,
      "description": "Forbidden: bot was kicked from the supergroup chat"
    }
    
    {
      "ok": false,
      "error_code": 409,
      "description": "Conflict: can't use getUpdates method while webhook is active"
    }
    
    {
      "ok": false,
      "error_code": 429,
      "description": "Too Many Requests: retry after X",
      "parameters": {
        "retry_after": "X"
      }
    }
    

    Понравилась статья? Поделить с друзьями:
  • Telegram bot webhook wrong response from the webhook 500 internal server error
  • Telegram bot ssl error
  • Telegram api ssl error
  • Telegram api bot error code
  • Tele2 ошибка при загрузке приложения