Api id api hash telegram error

How to handle API return errors correctly.

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.

When I run python3 try_telethon.py it all the time says

RPCError(…), ‘The api_id/api_hash combination is invalid.’

OS: MacOS, Ubuntu 12.04.

It even does not want to connect. The error occurs on the first self.connect call (Could not stabilise initial connection). What is worth, occasionally this call works. But all the time it fails on sending a code (SendCodeRequest). I use 2 different telegram accounts. The result is the same.

I do as it’s written in the readme:

  • Run the tl_generator.py
  • Create and edit the settings
  • python3 try_telethon.py

I get the same result in case of using an installed through the pip version.

Could you please tell, if I should do something else.

Update

When the connect call works, it returns the following

(config (ID: 0x3af6fb5f) = (phonecalls_enabled=None, date=2017-04-07 11:43:30, expires=1491558606, test_mode=False, this_dc=5, dc_options=[‘(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=1, ip_address=149.154.175.50, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=1, ip_address=2001:0b28:f23d:f001:0000:0000:0000:000a, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=2, ip_address=149.154.167.51, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=2, ip_address=2001:067c:04e8:f002:0000:0000:0000:000a, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=3, ip_address=149.154.175.100, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=3, ip_address=2001:0b28:f23d:f003:0000:0000:0000:000a, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=4, ip_address=149.154.167.91, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=4, ip_address=2001:067c:04e8:f004:0000:0000:0000:000a, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=True, tcpo_only=None, id=4, ip_address=149.154.165.120, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=None, media_only=None, tcpo_only=None, id=5, ip_address=91.108.56.165, port=443))’, ‘(dcOption (ID: 0x5d8c6cc) = (ipv6=True, media_only=None, tcpo_only=None, id=5, ip_address=2001:0b28:f23f:f005:0000:0000:0000:000a, port=443))’], chat_size_max=200, megagroup_size_max=5000, forwarded_count_max=100, online_update_period_ms=120000, offline_blur_timeout_ms=5000, offline_idle_timeout_ms=30000, online_cloud_timeout_ms=300000, notify_cloud_delay_ms=30000, notify_default_delay_ms=1500, chat_big_size=10, push_chat_period_ms=60000, push_chat_limit=2, saved_gifs_limit=200, edit_time_limit=172800, rating_e_decay=2419200, stickers_recent_limit=30, tmp_sessions=None, pinned_dialogs_count_max=5, call_receive_timeout_ms=20000, call_ring_timeout_ms=90000, call_connect_timeout_ms=30000, call_packet_timeout_ms=10000, disabled_features=None))

В данной статье собраны ошибки, возвращаемые 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 и рассматриваться как внутренняя ошибка сервера.

Данная инструкция  предназначена для первоначальной настройки программы Telegram-Spam-Master!

Зачем это нужно? Это действие необходимо по нескольким причинам: 1) Для того чтобы программа Telegram-Spam-Master могла работать; 2) Снизить вероятность банов Ваших аккаунтов в Telegram

Как получить API Id и API Hash?

Если при создании приложения у Вас постоянно возникает ошибка с текстом «ERROR», Вам поможет инструкция в самом конце данной статьи
> > > Ссылка < < <

  1. Сначала перейдите на my.telegram.org
  2. В поле Your Phone Number введите Ваш номер телефона (рекомендуется использовать номер телефона Вашего фейк-аккаунта во избежание блокировки основного номера) и нажмите Next. На этот номер будет отправлено сообщение в Телеграм, который нам понадобится в следующем пункте. Рисунок 1. Получение API id и API hash для программы спамера в телеграм.
  3. После этого у Вас появится поле Confirmation code. В это поле Вам необходимо вставить код, который Вы получите в приложении Telegram На телефоне или компьютере и нажать на кнопку Sign In. Рисунок 2. Получение API id и API hash для программы спамера в телеграм.
  4. Далее нажимем на ссылку «API development tools» Рисунок 3. Получение API id и API hash для программы спамера в телеграм.
  5. Вам предложат создать новое приложение.
    Заполняем поля по примеру:
    App title: Любое название на английском языке
    Shortname: Любая строчка на английском языке без пробелов! Длина от 5 до 32 символа
    Url: Ссылка на любой сайт, который не является популярным
    Platform: Desktop
    Description: Придумайте любое описание Рисунок 4. Получение API id и API hash для программы спамера в телеграм.
  6. Нажимаем «Create application»
    Если на этом этапе Вы увидите окно с надписью «ERROR«, попробуйте отключить в Вашем браузере плагины-блокировщики рекламы или блокировщики сторонних файлов Cookie
    Если все пройдет хорошо, то Вы увидите страницу похожую на скриншот ниже! Рисунок 5. Получение API id и API hash для программы спамера в телеграм.
  7. Поля App api_id и App api_hash копируем в программу Telegram-Spam-Master соответственно!

Если при создании приложения у Вас постоянно возникает ошибка с текстом «ERROR»

1) Открываем Телеграм клиент на своем компьютере!

2) Ищем в поиске @PyGetssApiBot (можете поискать любой другой по запросу «Telegram API ID HASH«)

3) Запускаем бота введя /start или нажав соответствующую кнопку

4) Бот может попросить Вас подписаться на какой-то паблик. Подписываемся! Когда мы закончим работу с ботом, можно будет отписаться!

5) Нажимаем кнопку «Get Api ID and Api Hash»

6) Вводим номер телефона купленного фейк-аккаунта

7) В телеграм-клиент этого фейк-аккаунта придет код. Копируем его и отправляем боту!

8) После отправки кода, бот выдаст Вам APP ID и API HASH! (смотри скриншот) Копируем их в соответствующие поля в программе Telegram-Spam-Master

ABOUT_TOO_LONG 400 The provided bio is too long ACCESS_TOKEN_EXPIRED 400 Bot token expired ACCESS_TOKEN_INVALID 400 The provided token is not valid ACTIVE_USER_REQUIRED 401 The method is only available to already activated users ADMINS_TOO_MUCH 400 Too many admins ADMIN_RANK_EMOJI_NOT_ALLOWED 400 Emoji are not allowed in admin titles or ranks ADMIN_RANK_INVALID 400 The given admin title or rank was invalid (possibly larger than 16 characters) API_ID_INVALID 400 The api_id/api_hash combination is invalid API_ID_PUBLISHED_FLOOD 400 This API id was published somewhere, you can’t use it now ARTICLE_TITLE_EMPTY 400 The title of the article is empty AUTH_BYTES_INVALID 400 The provided authorization is invalid AUTH_KEY_DUPLICATED 406 The authorization key (session file) was used under two different IP addresses simultaneously, and can no longer be used. Use the same session exclusively, or use different sessions AUTH_KEY_INVALID 401 The key is invalid AUTH_KEY_PERM_EMPTY 401 The method is unavailable for temporary authorization key, not bound to permanent AUTH_KEY_UNREGISTERED 401 The key is not registered in the system AUTH_RESTART 500 Restart the authorization process BANNED_RIGHTS_INVALID 400 You cannot use that set of permissions in this request, i.e. restricting view_messages as a default BOTS_TOO_MUCH 400 There are too many bots in this chat/channel BOT_CHANNELS_NA 400 Bots can’t edit admin privileges BOT_GROUPS_BLOCKED 400 This bot can’t be added to groups BOT_INLINE_DISABLED 400 This bot can’t be used in inline mode BOT_INVALID 400 This is not a valid bot BOT_METHOD_INVALID 400 The API access for bot users is restricted. The method you tried to invoke cannot be executed as a bot BOT_MISSING 400 This method can only be run by a bot BOT_PAYMENTS_DISABLED 400 This method can only be run by a bot BOT_POLLS_DISABLED 400 You cannot create polls under a bot account BROADCAST_ID_INVALID 400 The channel is invalid BROADCAST_PUBLIC_VOTERS_FORBIDDEN 400 You cannot broadcast polls where the voters are public BUTTON_DATA_INVALID 400 The provided button data is invalid BUTTON_TYPE_INVALID 400 The type of one of the buttons you provided is invalid BUTTON_URL_INVALID 400 Button URL invalid CALL_ALREADY_ACCEPTED 400 The call was already accepted CALL_ALREADY_DECLINED 400 The call was already declined CALL_OCCUPY_FAILED 500 The call failed because the user is already making another call CALL_PEER_INVALID 400 The provided call peer object is invalid CALL_PROTOCOL_FLAGS_INVALID 400 Call protocol flags invalid CDN_METHOD_INVALID 400 This method cannot be invoked on a CDN server. Refer to https://core.telegram.org/cdn#schema for available methods CHANNELS_ADMIN_PUBLIC_TOO_MUCH 400 You’re admin of too many public channels, make some channels private to change the username of this channel CHANNELS_TOO_MUCH 400 You have joined too many channels/supergroups CHANNEL_INVALID 400 Invalid channel object. Make sure to pass the right types, for instance making sure that the request is designed for channels or otherwise look for a different one more suited CHANNEL_PRIVATE 400 The channel specified is private and you lack permission to access it. Another reason may be that you were banned from it CHANNEL_PUBLIC_GROUP_NA 403 channel/supergroup not available CHAT_ABOUT_NOT_MODIFIED 400 About text has not changed CHAT_ABOUT_TOO_LONG 400 Chat about too long CHAT_ADMIN_INVITE_REQUIRED 403 You do not have the rights to do this CHAT_ADMIN_REQUIRED 400 403 Chat admin privileges are required to do that in the specified chat (for example, to send a message in a channel which is not yours), or invalid permissions used for the channel or group CHAT_FORBIDDEN You cannot write in this chat CHAT_ID_EMPTY 400 The provided chat ID is empty CHAT_ID_INVALID 400 Invalid object ID for a chat. Make sure to pass the right types, for instance making sure that the request is designed for chats (not channels/megagroups) or otherwise look for a different one more suitednAn example working with a megagroup and AddChatUserRequest, it will fail because megagroups are channels. Use InviteToChannelRequest instead CHAT_INVALID 400 The chat is invalid for this request CHAT_LINK_EXISTS 400 The chat is linked to a channel and cannot be used in that request CHAT_NOT_MODIFIED 400 The chat or channel wasn’t modified (title, invites, username, admins, etc. are the same) CHAT_RESTRICTED 400 The chat is restricted and cannot be used in that request CHAT_SEND_GIFS_FORBIDDEN 403 You can’t send gifs in this chat CHAT_SEND_INLINE_FORBIDDEN 400 You cannot send inline results in this chat CHAT_SEND_MEDIA_FORBIDDEN 403 You can’t send media in this chat CHAT_SEND_STICKERS_FORBIDDEN 403 You can’t send stickers in this chat CHAT_TITLE_EMPTY 400 No chat title provided CHAT_WRITE_FORBIDDEN 403 You can’t write in this chat CODE_EMPTY 400 The provided code is empty CODE_HASH_INVALID 400 Code hash invalid CODE_INVALID 400 Code invalid (i.e. from email) CONNECTION_API_ID_INVALID 400 The provided API id is invalid CONNECTION_DEVICE_MODEL_EMPTY 400 Device model empty CONNECTION_LANG_PACK_INVALID 400 The specified language pack is not valid. This is meant to be used by official applications only so far, leave it empty CONNECTION_LAYER_INVALID 400 The very first request must always be InvokeWithLayerRequest CONNECTION_NOT_INITED 400 Connection not initialized CONNECTION_SYSTEM_EMPTY 400 Connection system empty CONTACT_ID_INVALID 400 The provided contact ID is invalid DATA_INVALID 400 Encrypted data invalid DATA_JSON_INVALID 400 The provided JSON data is invalid DATE_EMPTY 400 Date empty DC_ID_INVALID 400 This occurs when an authorization is tried to be exported for the same data center one is currently connected to DH_G_A_INVALID 400 g_a invalid EMAIL_HASH_EXPIRED 400 The email hash expired and cannot be used to verify it EMAIL_INVALID 400 The given email is invalid EMAIL_UNCONFIRMED_{code_length} 400 Email unconfirmed, the length of the code must be {code_length} EMOTICON_EMPTY 400 The emoticon field cannot be empty ENCRYPTED_MESSAGE_INVALID 400 Encrypted message invalid ENCRYPTION_ALREADY_ACCEPTED 400 Secret chat already accepted ENCRYPTION_ALREADY_DECLINED 400 The secret chat was already declined ENCRYPTION_DECLINED 400 The secret chat was declined ENCRYPTION_ID_INVALID 400 The provided secret chat ID is invalid ENCRYPTION_OCCUPY_FAILED 500 TDLib developer claimed it is not an error while accepting secret chats and 500 is used instead of 420 ENTITIES_TOO_LONG 400 It is no longer possible to send such long data inside entity tags (for example inline text URLs) ENTITY_MENTION_USER_INVALID 400 You can’t use this entity ERROR_TEXT_EMPTY 400 The provided error message is empty EXPORT_CARD_INVALID 400 Provided card is invalid EXTERNAL_URL_INVALID 400 External URL invalid FIELD_NAME_EMPTY The field with the name FIELD_NAME is missing FIELD_NAME_INVALID The field with the name FIELD_NAME is invalid FILE_ID_INVALID 400 The provided file id is invalid FILE_MIGRATE_{new_dc} 303 The file to be accessed is currently stored in DC {new_dc} FILE_PARTS_INVALID 400 The number of file parts is invalid FILE_PART_EMPTY 400 The provided file part is empty FILE_PART_INVALID 400 The file part number is invalid FILE_PART_LENGTH_INVALID 400 The length of a file part is invalid FILE_PART_SIZE_CHANGED 400 The file part size (chunk size) cannot change during upload FILE_PART_SIZE_INVALID 400 The provided file part size is invalid FILE_PART_{which}_MISSING 400 Part {which} of the file is missing from storage FILEREF_UPGRADE_NEEDED 406 The file reference needs to be refreshed before being used again FIRSTNAME_INVALID 400 The first name is invalid FLOOD_TEST_PHONE_WAIT_{seconds} 420 A wait of {seconds} seconds is required in the test servers FLOOD_WAIT_{seconds} 420 A wait of {seconds} seconds is required FOLDER_ID_EMPTY 400 The folder you tried to delete was already empty FOLDER_ID_INVALID 400 The folder you tried to use was not valid FRESH_CHANGE_ADMINS_FORBIDDEN 400 Recently logged-in users cannot add or change admins FRESH_RESET_AUTHORISATION_FORBIDDEN 406 The current session is too new and cannot be used to reset other authorisations yet GAME_BOT_INVALID 400 You cannot send that game with the current bot GIF_ID_INVALID 400 The provided GIF ID is invalid GROUPED_MEDIA_INVALID 400 Invalid grouped media HASH_INVALID 400 The provided hash is invalid HISTORY_GET_FAILED 500 Fetching of history failed IMAGE_PROCESS_FAILED 400 Failure while processing image INLINE_RESULT_EXPIRED 400 The inline query expired INPUT_CONSTRUCTOR_INVALID 400 The provided constructor is invalid INPUT_FETCH_ERROR An error occurred while deserializing TL parameters INPUT_FETCH_FAIL 400 Failed deserializing TL payload INPUT_LAYER_INVALID 400 The provided layer is invalid INPUT_METHOD_INVALID The invoked method does not exist anymore or has never existed INPUT_REQUEST_TOO_LONG 400 The input request was too long. This may be a bug in the library as it can occur when serializing more bytes than it should (like appending the vector constructor code at the end of a message) INPUT_USER_DEACTIVATED 400 The specified user was deleted INTERDC_{dc}_CALL_ERROR An error occurred while communicating with DC {dc} INTERDC_{dc}_CALL_RICH_ERROR A rich error occurred while communicating with DC {dc} INVITE_HASH_EMPTY 400 The invite hash is empty INVITE_HASH_EXPIRED 400 The chat the user tried to join has expired and is not valid anymore INVITE_HASH_INVALID 400 The invite hash is invalid LANG_PACK_INVALID 400 The provided language pack is invalid LASTNAME_INVALID The last name is invalid LIMIT_INVALID 400 An invalid limit was provided. See https://core.telegram.org/api/files#downloading-files LINK_NOT_MODIFIED 400 The channel is already linked to this group LOCATION_INVALID 400 The location given for a file was invalid. See https://core.telegram.org/api/files#downloading-files MAX_ID_INVALID 400 The provided max ID is invalid MAX_QTS_INVALID 400 The provided QTS were invalid MD5_CHECKSUM_INVALID The MD5 check-sums do not match MEDIA_CAPTION_TOO_LONG 400 The caption is too long MEDIA_EMPTY 400 The provided media object is invalid or the current account may not be able to send it (such as games as users) MEDIA_INVALID 400 Media invalid MEDIA_NEW_INVALID 400 The new media to edit the message with is invalid (such as stickers or voice notes) MEDIA_PREV_INVALID 400 The old media cannot be edited with anything else (such as stickers or voice notes) MEGAGROUP_ID_INVALID 400 The group is invalid MEGAGROUP_PREHISTORY_HIDDEN 400 You can’t set this discussion group because it’s history is hidden MEMBER_NO_LOCATION 500 An internal failure occurred while fetching user info (couldn’t find location) MEMBER_OCCUPY_PRIMARY_LOC_FAILED 500 Occupation of primary member location failed MESSAGE_AUTHOR_REQUIRED 403 Message author required MESSAGE_DELETE_FORBIDDEN 403 You can’t delete one of the messages you tried to delete, most likely because it is a service message. MESSAGE_EDIT_TIME_EXPIRED 400 You can’t edit this message anymore, too much time has passed since its creation. MESSAGE_EMPTY 400 Empty or invalid UTF-8 message was sent MESSAGE_IDS_EMPTY 400 No message ids were provided MESSAGE_ID_INVALID 400 The specified message ID is invalid or you can’t do that operation on such message MESSAGE_NOT_MODIFIED 400 Content of the message was not modified MESSAGE_POLL_CLOSED 400 The poll was closed and can no longer be voted on MESSAGE_TOO_LONG 400 Message was too long. Current maximum length is 4096 UTF-8 characters MSG_ID_INVALID 400 The message ID used in the peer was invalid MSG_WAIT_FAILED 400 A waiting call returned an error MT_SEND_QUEUE_TOO_LONG 500 NEED_CHAT_INVALID 500 The provided chat is invalid NEED_MEMBER_INVALID 500 The provided member is invalid or does not exist (for example a thumb size) NETWORK_MIGRATE_{new_dc} 303 The source IP address is associated with DC {new_dc} NEW_SALT_INVALID 400 The new salt is invalid NEW_SETTINGS_INVALID 400 The new settings are invalid OFFSET_INVALID 400 The given offset was invalid, it must be divisible by 1KB. See https://core.telegram.org/api/files#downloading-files OFFSET_PEER_ID_INVALID 400 The provided offset peer is invalid OPTION_INVALID 400 The option specified is invalid and does not exist in the target poll OPTIONS_TOO_MUCH 400 You defined too many options for the poll PACK_SHORT_NAME_INVALID 400 Invalid sticker pack name. It must begin with a letter, can’t contain consecutive underscores and must end in «_by_<bot username>». PACK_SHORT_NAME_OCCUPIED 400 A stickerpack with this name already exists PARTICIPANTS_TOO_FEW 400 Not enough participants PARTICIPANT_CALL_FAILED 500 Failure while making call PARTICIPANT_VERSION_OUTDATED 400 The other participant does not use an up to date telegram client with support for calls PASSWORD_EMPTY 400 The provided password is empty PASSWORD_HASH_INVALID 400 The password (and thus its hash value) you entered is invalid PASSWORD_REQUIRED 400 The account must have 2-factor authentication enabled (a password) before this method can be used PAYMENT_PROVIDER_INVALID 400 The payment provider was not recognised or its token was invalid PEER_FLOOD Too many requests PEER_ID_INVALID 400 An invalid Peer was used. Make sure to pass the right peer type PEER_ID_NOT_SUPPORTED 400 The provided peer ID is not supported PERSISTENT_TIMESTAMP_EMPTY 400 Persistent timestamp empty PERSISTENT_TIMESTAMP_INVALID 400 Persistent timestamp invalid PERSISTENT_TIMESTAMP_OUTDATED 500 Persistent timestamp outdated PHONE_CODE_EMPTY 400 The phone code is missing PHONE_CODE_EXPIRED 400 The confirmation code has expired PHONE_CODE_HASH_EMPTY The phone code hash is missing PHONE_CODE_INVALID 400 The phone code entered was invalid PHONE_MIGRATE_{new_dc} 303 The phone number a user is trying to use for authorization is associated with DC {new_dc} PHONE_NUMBER_APP_SIGNUP_FORBIDDEN 400 PHONE_NUMBER_BANNED 400 The used phone number has been banned from Telegram and cannot be used anymore. Maybe check https://www.telegram.org/faq_spam PHONE_NUMBER_FLOOD 400 You asked for the code too many times. PHONE_NUMBER_INVALID 400 406 The phone number is invalid PHONE_NUMBER_OCCUPIED 400 The phone number is already in use PHONE_NUMBER_UNOCCUPIED 400 The phone number is not yet being used PHONE_PASSWORD_FLOOD 406 You have tried logging in too many times PHONE_PASSWORD_PROTECTED 400 This phone is password protected PHOTO_CONTENT_URL_EMPTY 400 The content from the URL used as a photo appears to be empty or has caused another HTTP error PHOTO_CROP_SIZE_SMALL 400 Photo is too small PHOTO_EXT_INVALID 400 The extension of the photo is invalid PHOTO_INVALID 400 Photo invalid PHOTO_INVALID_DIMENSIONS 400 The photo dimensions are invalid (hint: `pip install pillow` for `send_file` to resize images) PHOTO_SAVE_FILE_INVALID 400 The photo you tried to send cannot be saved by Telegram. A reason may be that it exceeds 10MB. Try resizing it locally PHOTO_THUMB_URL_EMPTY 400 The URL used as a thumbnail appears to be empty or has caused another HTTP error PIN_RESTRICTED 400 You can’t pin messages in private chats with other people POLL_ANSWERS_INVALID 400 The poll did not have enough answers or had too many POLL_OPTION_DUPLICATE 400 A duplicate option was sent in the same poll POLL_OPTION_INVALID 400 A poll option used invalid data (the data may be too long) POLL_QUESTION_INVALID 400 The poll question was either empty or too long POLL_UNSUPPORTED 400 This layer does not support polls in the issued method PRIVACY_KEY_INVALID 400 The privacy key is invalid PTS_CHANGE_EMPTY 500 No PTS change QUERY_ID_EMPTY 400 The query ID is empty QUERY_ID_INVALID 400 The query ID is invalid QUERY_TOO_SHORT 400 The query string is too short QUIZ_CORRECT_ANSWERS_EMPTY 400 A quiz must specify one correct answer QUIZ_CORRECT_ANSWERS_TOO_MUCH 400 There can only be one correct answer QUIZ_CORRECT_ANSWER_INVALID 400 The correct answer is not an existing answer QUIZ_MULTIPLE_INVALID 400 A poll cannot be both multiple choice and quiz RANDOM_ID_DUPLICATE 500 You provided a random ID that was already used RANDOM_ID_INVALID 400 A provided random ID is invalid RANDOM_LENGTH_INVALID 400 Random length invalid RANGES_INVALID 400 Invalid range provided REACTION_EMPTY 400 No reaction provided REACTION_INVALID 400 Invalid reaction provided (only emoji are allowed) REG_ID_GENERATE_FAILED 500 Failure while generating registration ID REPLY_MARKUP_INVALID 400 The provided reply markup is invalid REPLY_MARKUP_TOO_LONG 400 The data embedded in the reply markup buttons was too much RESULT_ID_DUPLICATE 400 Duplicated IDs on the sent results. Make sure to use unique IDs. RESULT_TYPE_INVALID 400 Result type invalid RESULTS_TOO_MUCH 400 You sent too many results. See https://core.telegram.org/bots/api#answerinlinequery for the current limit. RIGHT_FORBIDDEN 403 Either your admin rights do not allow you to do this or you passed the wrong rights combination (some rights only apply to channels and vice versa) RPC_CALL_FAIL Telegram is having internal issues, please try again later. RPC_MCGET_FAIL Telegram is having internal issues, please try again later. RSA_DECRYPT_FAILED 400 Internal RSA decryption failed SCHEDULE_BOT_NOT_ALLOWED 400 Bots are not allowed to schedule messages SCHEDULE_DATE_TOO_LATE 400 The date you tried to schedule is too far in the future (last known limit of 1 year and a few hours) SCHEDULE_TOO_MUCH 400 You cannot schedule more messages in this chat (last known limit of 100 per chat) SEARCH_QUERY_EMPTY 400 The search query is empty SECONDS_INVALID 400 Slow mode only supports certain values (e.g. 0, 10s, 30s, 1m, 5m, 15m and 1h) SEND_MESSAGE_MEDIA_INVALID 400 The message media was invalid or not specified SEND_MESSAGE_TYPE_INVALID 400 The message type is invalid SESSION_EXPIRED 401 The authorization has expired SESSION_PASSWORD_NEEDED 401 Two-steps verification is enabled and a password is required SESSION_REVOKED 401 The authorization has been invalidated, because of the user terminating all sessions SHA256_HASH_INVALID 400 The provided SHA256 hash is invalid SHORTNAME_OCCUPY_FAILED 400 An error occurred when trying to register the short-name used for the sticker pack. Try a different name SLOWMODE_WAIT_{seconds} 420 A wait of {seconds} seconds is required before sending another message in this chat START_PARAM_EMPTY 400 The start parameter is empty START_PARAM_INVALID 400 Start parameter invalid STICKERSET_INVALID 400 The provided sticker set is invalid STICKERS_EMPTY 400 No sticker provided STICKER_EMOJI_INVALID 400 Sticker emoji invalid STICKER_FILE_INVALID 400 Sticker file invalid STICKER_ID_INVALID 400 The provided sticker ID is invalid STICKER_INVALID 400 The provided sticker is invalid STICKER_PNG_DIMENSIONS 400 Sticker png dimensions invalid STICKER_PNG_NOPNG 400 Stickers must be a png file but the used image was not a png STORAGE_CHECK_FAILED 500 Server storage check failed STORE_INVALID_SCALAR_TYPE 500 TAKEOUT_INIT_DELAY_{seconds} 420 A wait of {seconds} seconds is required before being able to initiate the takeout TAKEOUT_INVALID 400 The takeout session has been invalidated by another data export session TAKEOUT_REQUIRED 400 You must initialize a takeout request first TEMP_AUTH_KEY_EMPTY 400 No temporary auth key provided Timeout -503 A timeout occurred while fetching data from the worker TMP_PASSWORD_DISABLED 400 The temporary password is disabled TOKEN_INVALID 400 The provided token is invalid TTL_DAYS_INVALID 400 The provided TTL is invalid TYPES_EMPTY 400 The types field is empty TYPE_CONSTRUCTOR_INVALID The type constructor is invalid UNKNOWN_METHOD 500 The method you tried to call cannot be called on non-CDN DCs UNTIL_DATE_INVALID 400 That date cannot be specified in this request (try using None) URL_INVALID 400 The URL used was invalid (e.g. when answering a callback with an URL that’s not t.me/yourbot or your game’s URL) USERNAME_INVALID 400 Nobody is using this username, or the username is unacceptable. If the latter, it must match r»[a-zA-Z][wd]{3,30}[a-zA-Zd]» USERNAME_NOT_MODIFIED 400 The username is not different from the current username USERNAME_NOT_OCCUPIED 400 The username is not in use by anyone else yet USERNAME_OCCUPIED 400 The username is already taken USERS_TOO_FEW 400 Not enough users (to create a chat, for example) USERS_TOO_MUCH 400 The maximum number of users has been exceeded (to create a chat, for example) USER_ADMIN_INVALID 400 Either you’re not an admin or you tried to ban an admin that you didn’t promote USER_ALREADY_PARTICIPANT 400 The authenticated user is already a participant of the chat USER_BANNED_IN_CHANNEL 400 You’re banned from sending messages in supergroups/channels USER_BLOCKED 400 User blocked USER_BOT 400 Bots can only be admins in channels. USER_BOT_INVALID 400 403 This method can only be called by a bot USER_BOT_REQUIRED 400 This method can only be called by a bot USER_CHANNELS_TOO_MUCH 403 One of the users you tried to add is already in too many channels/supergroups USER_CREATOR 400 You can’t leave this channel, because you’re its creator USER_DEACTIVATED 401 The user has been deleted/deactivated USER_DEACTIVATED_BAN 401 The user has been deleted/deactivated USER_ID_INVALID 400 Invalid object ID for a user. Make sure to pass the right types, for instance making sure that the request is designed for users or otherwise look for a different one more suited USER_INVALID 400 The given user was invalid USER_IS_BLOCKED 400 403 User is blocked USER_IS_BOT 400 Bots can’t send messages to other bots USER_KICKED 400 This user was kicked from this supergroup/channel USER_MIGRATE_{new_dc} 303 The user whose identity is being used to execute queries is associated with DC {new_dc} USER_NOT_MUTUAL_CONTACT 400 403 The provided user is not a mutual contact USER_NOT_PARTICIPANT 400 The target user is not a member of the specified megagroup or channel USER_PRIVACY_RESTRICTED 403 The user’s privacy settings do not allow you to do this USER_RESTRICTED 403 You’re spamreported, you can’t create channels or chats. VIDEO_CONTENT_TYPE_INVALID 400 The video content type is not supported with the given parameters (i.e. supports_streaming) WALLPAPER_FILE_INVALID 400 The given file cannot be used as a wallpaper WALLPAPER_INVALID 400 The input wallpaper was not valid WC_CONVERT_URL_INVALID 400 WC convert URL invalid WEBPAGE_CURL_FAILED 400 Failure while fetching the webpage with cURL WEBPAGE_MEDIA_EMPTY 400 Webpage media empty WORKER_BUSY_TOO_LONG_RETRY 500 Telegram workers are too busy to respond immediately YOU_BLOCKED_USER 400 You blocked this user

Telegram client using telethon

SORRY FOR MY ENGLISH!))

Trying to launch telegram client on pythonanywhere hosting using flask

Loaded all necessary libraries (see photo1)

On this site created an api-application, got it app_id and api_hash

Further, I made a flask application with this code (for test)

@app.route('/')
def hello_world():
    #------------------------If an error occurred during import------------
    try:
        from telethon import TelegramClient, sync
    except Exception as e:
        return 'IMPORT ERROR: ' + str(e)
    #------------------------we catch it-----------------------------------

    api_id = API_ID_FROM_MY_TELEGRAM_ORG #Тут подставляю свое
    api_hash = API_HASH_CODE_FROM_MY_TELEGRAM_ORG #Тут подставляю свое

    #----------If an error occurred while creating the object--------------
    try:
        client = TelegramClient('test_session', api_id, api_hash)
        return 'Succes!'
    except Exception as e:
        return 'OBJECT ERROR: ' + str(e)
    #------------------------we catch it-----------------------------------

When you start and open the application in the browser, the following error is displayed (in text form):

OBJECT ERROR: database is locked

This text corresponds to the last try/catch construction, so an error occurs when trying to create an object client = TelegramClient('test_session', api_id, api_hash)

What is this exception and how in my case to fight it?

deleted-user-5755348
|
6
posts
|



June 21, 2019, 7:24 p.m.

|
permalink

From your screenshot of the libraries that you loaded, it looks like you’ve just pulled down the source code — if you want to use a library, you should use pip3.7 (or similar) to install it. Check out this help page.

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



June 21, 2019, 7:49 p.m.

|
permalink

Ok
I’ve made forced-reinstall of telethon like that

pip3.6 install --user --upgrade --force-reinstall telethon

And this library and other required have appeared in ./.local/lib/python3.6/site-packages

But there is error

IMPORT ERROR: No module named ‘telethon’

What now?

deleted-user-5755348
|
6
posts
|



June 21, 2019, 8:22 p.m.

|
permalink

I’ve added that:

import sys
sys.path.insert(0, '.local/lib/python3.6/site-packages')

but there is this error again

OBJECT ERROR: database is locked

deleted-user-5755348
|
6
posts
|



June 21, 2019, 8:33 p.m.

|
permalink

Anonim
|
2
posts
|



June 21, 2019, 10:46 p.m.

|
permalink

But then an other error appears:

Errno Connection to Telegram failed 6 time(s)

Anonim
|
2
posts
|



June 21, 2019, 10:47 p.m.

|
permalink

You don’t need to add .local/lib/python3.6/site-packages to your sys.path if you’re using Python 3.6 — it’s added automatically. I suggest you remove the code that adds it, and use pip3.7 to install the packages, because your website is set up to use Python 3.7. I’m not sure that’s the cause of the problem, but it probably isn’t helping.

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



June 22, 2019, 12:54 p.m.

|
permalink

Ok, I’ve made that

pip3.7 install --user --upgrade --force-reinstall telethon

but there is an error, as in the post above

OBJECT ERROR: [Errno Connection to Telegram failed %d time(s)] 6

How to deal with this problem?

deleted-user-5755348
|
6
posts
|



June 23, 2019, 4:50 p.m.

|
permalink

Is it right to do like that?

proxy=(socks.SOCKS5, 'proxy.server', 3128)
client = TelegramClient('session_name', api_id, api_hash, proxy = proxy)

If yes, there is a problem with reloading my web app

deleted-user-5755348
|
6
posts
|



June 23, 2019, 6:34 p.m.

|
permalink

Yes, I think that’s the issue :-) It sounds like you need to configure telethon to use the proxy — the help page the person in that forum linked to has the details.

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



June 23, 2019, 6:58 p.m.

|
permalink

is there a solution for using telegramm proxy on pythonanywhere?

deleted-user-7862926
|
19
posts
|



June 14, 2020, 6:21 p.m.

|
permalink

It depends on which telegram library you are using. Which one do you want to use?

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



June 15, 2020, 10:49 a.m.

|
permalink

the topic is about ‘client using telethon’,
I am also trying to set up telethon through ‘proxy.server’,3128 or my own proxy

deleted-user-7862926
|
19
posts
|



June 15, 2020, 2:41 p.m.

|
permalink

What code are you using when using our default proxy server? And what error messages are you getting, if any?

Using your own proxy won’t work from a free PythonAnywhere account, as it would not be on our whitelist.

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



June 15, 2020, 5:39 p.m.

|
permalink

client = TelegramClient(‘session_name’, config.api_id, config.api_hash, proxy=(socks.SOCKS5, ‘proxy.server’,3128))

results

ConnectionError: Connection to Telegram failed 5 time(s)

deleted-user-7862926
|
19
posts
|



June 15, 2020, 8:49 p.m.

|
permalink

Could you share the full traceback of the error with us?

Staff

fjl
|
3651
posts
|

PythonAnywhere staff
|



June 16, 2020, 9:10 a.m.

|
permalink

I am sorry, of cource :

09:24 ~/bot $ python3 tele.py 
Traceback (most recent call last):
  File "tele.py", line 15, in <module>
    client.start()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 132, in start
    else self.loop.run_until_complete(coro)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
    return future.result()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 139, in _start
    await self.connect()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 472, in connect
    if not await self._sender.connect(self._connection(
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
    await self._connect()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 250, in _connect
    raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)

deleted-user-7862926
|
19
posts
|



June 16, 2020, 10:55 a.m.

|
permalink

You cannot use the mtproto connection type from a free account on PythonAnywhere. Free accounts can only connect out of PythonAnywhere using http(s). Check the documentation for telethon to see how to use an http-based connection instead.

Staff

glenn
|
8695
posts
|

PythonAnywhere staff
|



June 17, 2020, 9:51 a.m.

|
permalink

I tried

client = TelegramClient('session_name', config.api_id, config.api_hash, connection=connection.tcpfull.ConnectionTcpFull)

error still the same

[edit by admin: formatting]

deleted-user-7862926
|
19
posts
|



July 7, 2020, 12:11 p.m.

|
permalink

.

client = TelegramClient('session_name', config.api_id, config.api_hash, connection=connection.tcpfull.ConnectionTcpFull, proxy=(socks.HTTP, 'proxy.server',3128))
client = TelegramClient('session_name', config.api_id, config.api_hash, connection=connection.tcpfull.ConnectionTcpFull, proxy=(socks.SOCKS5, 'proxy.server',3128))

with same result

[edit by admin: formatting]

deleted-user-7862926
|
19
posts
|



July 7, 2020, 12:25 p.m.

|
permalink

This one should have worked:

client = TelegramClient('session_name', config.api_id, config.api_hash, connection=connection.tcpfull.ConnectionTcpFull, proxy=(socks.HTTP, 'proxy.server',3128))

Could you try it again and post the full error message that you get from it?

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



July 8, 2020, 10:08 a.m.

|
permalink

.

client.start()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 132, in start
    else self.loop.run_until_complete(coro)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 608, in run_until_complete
    return future.result()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 139, in _start
    await self.connect()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 472, in connect
    if not await self._sender.connect(self._connection(
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
    await self._connect()
  File "/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 250, in _connect
    raise ConnectionError('Connection to Telegram failed {} time(s)'.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)

deleted-user-7862926
|
19
posts
|



July 8, 2020, 10:13 a.m.

|
permalink

It looks to me like it is still trying to use mtproto rather than HTTP. What happens if you remove the connection=connection.tcpfull.ConnectionTcpFull parameter?

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



July 8, 2020, 11:14 a.m.

|
permalink

as I wrote above, all connection types give the same error traceback.
I tried 4 nonMtproto instructions:

client = TelegramClient('session_name', config.api_id,
        config.api_hash, connection=connection.tcpfull.ConnectionTcpFull,
        proxy=(socks.HTTP, 'proxy.server',3128))   
client =
        TelegramClient('session_name', config.api_id, config.api_hash,
        connection=connection.tcpfull.ConnectionTcpFull,
        proxy=(socks.SOCKS5, 'proxy.server',3128))   
client =
        TelegramClient('session_name', config.api_id, config.api_hash,
        connection=connection.tcpfull.ConnectionTcpFull)
client = TelegramClient('session_name', config.api_id, config.api_hash,  proxy=(socks.SOCKS5, 'proxy.server',3128))

deleted-user-7862926
|
19
posts
|



July 8, 2020, 11:35 a.m.

|
permalink

I suspect that TcpConnectionFull is using mtproto,. then. Try using telethon.network.connection.http.ConnectionHttp instead.

Staff

glenn
|
8695
posts
|

PythonAnywhere staff
|



July 8, 2020, 4:30 p.m.

|
permalink

client = TelegramClient(‘session_name’, config.api_id, config.api_hash, connection=connection.http.ConnectionHttp, proxy=(socks.SOCKS5, ‘proxy.server’,3128))

the same error

Traceback (most recent call last): File
«/home/codefather/bot/tele.py», line 15, in <module>
client.start() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py»,
line 132, in start
else self.loop.run_until_complete(coro) File «/usr/lib/python3.8/asyncio/base_events.py», line 608, in
run_until_complete
return future.result() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py»,
line 139, in _start
await self.connect() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py»,
line 472, in connect
if not await self._sender.connect(self._connection( File «/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py»,
line 125, in connect
await self._connect() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py»,
line 250, in _connect
raise ConnectionError(‘Connection to Telegram failed {} time(s)’.format(self._retries)) ConnectionError: Connection to
Telegram failed 5 time(s)

deleted-user-7862926
|
19
posts
|



July 9, 2020, 11:30 a.m.

|
permalink

Can we take a look at your code? We can see it from our admin interface, but we always ask for permission first.

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



July 9, 2020, 12:35 p.m.

|
permalink

yes. of course
script is at «/home/codefather/bot/tele.py»
thank you

deleted-user-7862926
|
19
posts
|



July 9, 2020, 12:55 p.m.

|
permalink

Could you try one more time with

client = TelegramClient('session_name', config.api_id, config.api_hash,
    proxy=(socks.HTTP, 'proxy.server',3128))

….?

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



July 9, 2020, 3:15 p.m.

|
permalink

Hi Giles,
I’m having the same issue… I tried your last recommendation:
client = TelegramClient(‘session_name’, config.api_id, config.api_hash,
proxy=(socks.HTTP, ‘proxy.server’,3128))

but didn’t work…

deleted-user-7999259
|
1
post
|



July 9, 2020, 9:01 p.m.

|
permalink

I tried

client = TelegramClient('session_name', config.api_id, config.api_hash,  proxy=(socks.HTTP, 'proxy.server',3128))

and

client = TelegramClient('session_name', config.api_id,connection=connection.ConnectionHttp, config.api_hash,  proxy=(socks.HTTP, 'proxy.server',3128))

but the error is the same :(

deleted-user-7862926
|
19
posts
|



July 10, 2020, 9:46 a.m.

|
permalink

Let’s see if we can get more information by increasing the logging level for Telethon; could you try adding this to the start of your script?

import logging
logging.basicConfig(level=logging.DEBUG)

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



July 10, 2020, 10:25 a.m.

|
permalink

done

DEBUG:asyncio:Using selector: EpollSelector
INFO:telethon.network.mtprotosender:Connecting to
149.154.167.51:443/TcpFull… DEBUG:telethon.network.mtprotosender:Connection attempt 1…
WARNING:telethon.network.mtprotosender:Attempt 1 at connecting failed:
GeneralProxyError: Socket error: 403: Forbidden

[*] Note: The HTTP proxy server may not be supported by PySocks (must
be a CONNECT tunnel proxy)
DEBUG:telethon.network.mtprotosender:Connection attempt 2…
WARNING:telethon.network.mtprotosender:Attempt 2 at connecting failed:
GeneralProxyError: Socket error: 403: Forbidden

[*] Note: The HTTP proxy server may not be supported by PySocks (must
be a CONNECT tunnel proxy)
DEBUG:telethon.network.mtprotosender:Connection attempt 3…
WARNING:telethon.network.mtprotosender:Attempt 3 at connecting failed:
GeneralProxyError: Socket error: 403: Forbidden

[*] Note: The HTTP proxy server may not be supported by PySocks (must
be a CONNECT tunnel proxy)
DEBUG:telethon.network.mtprotosender:Connection attempt 4…
WARNING:telethon.network.mtprotosender:Attempt 4 at connecting failed:
GeneralProxyError: Socket error: 403: Forbidden

[*] Note: The HTTP proxy server may not be supported by PySocks (must
be a CONNECT tunnel proxy)
DEBUG:telethon.network.mtprotosender:Connection attempt 5…
WARNING:telethon.network.mtprotosender:Attempt 5 at connecting failed:
GeneralProxyError: Socket error: 403: Forbidden

[*] Note: The HTTP proxy server may not be supported by PySocks (must
be a CONNECT tunnel proxy)
DEBUG:telethon.network.mtprotosender:Connection attempt 6…
WARNING:telethon.network.mtprotosender:Attempt 6 at connecting failed:
GeneralProxyError: Socket error: 403: Forbidden

[*] Note: The HTTP proxy server may not be supported by PySocks (must
be a CONNECT tunnel proxy) Traceback (most recent call last): File
«/home/codefather/bot/tele.py», line 17, in <module>
client.start() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py»,
line 132, in start
else self.loop.run_until_complete(coro) File «/usr/lib/python3.8/asyncio/base_events.py», line 608, in
run_until_complete
return future.result() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/client/auth.py»,
line 139, in _start
await self.connect() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py»,
line 472, in connect
if not await self._sender.connect(self._connection( File «/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py»,
line 125, in connect
await self._connect() File «/home/codefather/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py»,
line 250, in _connect
raise ConnectionError(‘Connection to Telegram failed {} time(s)’.format(self._retries)) ConnectionError: Connection to
Telegram failed 5 time(s)

deleted-user-7862926
|
19
posts
|



July 11, 2020, 9:50 a.m.

|
permalink

Which code are you using to construct the client when you get that error?

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



July 11, 2020, 5:21 p.m.

|
permalink

as you recomended above:

client = TelegramClient('session_name', config.api_id, config.api_hash,  proxy=(socks.HTTP, 'proxy.server',3128))

deleted-user-7862926
|
19
posts
|



July 13, 2020, 10:28 a.m.

|
permalink

That will not work because it is still using mtproto. Use the version that has the HttpConnection specified.

Staff

glenn
|
8695
posts
|

PythonAnywhere staff
|



July 13, 2020, 12:12 p.m.

|
permalink

as you an see in the posts before, i used many configurations as

connection=connection.ConnectionHttp

deleted-user-7862926
|
19
posts
|



July 13, 2020, 12:50 p.m.

|
permalink

Ok. The last time you posted a traceback that was clearly using the HTTP connection type, you said you’d used this code:

client = TelegramClient('session_name', config.api_id, config.api_hash, connection=connection.http.ConnectionHttp, proxy=(socks.SOCKS5, 'proxy.server',3128))

try

client = TelegramClient('session_name', config.api_id, config.api_hash, connection=connection.http.ConnectionHttp, proxy=(socks.HTTP, 'proxy.server',3128))

Staff

glenn
|
8695
posts
|

PythonAnywhere staff
|



July 13, 2020, 3:03 p.m.

|
permalink

as I told early, I tried and socks.HTTP and SOCKS5 — no changes

deleted-user-7862926
|
19
posts
|



July 14, 2020, 9:28 p.m.

|
permalink

hello,
Telethon uses MTProto under the hood, so there is no way of using it in free pythonanywhere account.

amirfj
|
22
posts
|



July 15, 2020, 7:42 a.m.

|
permalink

It has to be http connection using our proxy to work on free account.

Staff

fjl
|
3651
posts
|

PythonAnywhere staff
|



July 15, 2020, 10:17 a.m.

|
permalink

from telethon.sync import TelegramClient

api_id = id api_hash = hash

client = TelegramClient(‘session_name’, api_id, api_hash)

client.connect()

Почему видеть это ошибка?

enter image description here

deleted-user-8143660
|
1
post
|



Aug. 7, 2020, 9:50 p.m.

|
permalink

The library that you are using has created an SQLite database — it looks like it uses this to store sessions — and the database is locked. If you’re running two instances of your code at the same time, then that might happen if they both try to access the database at the same time. Alternatively, it might have locked the database and then crashed at some time in the past, leaving a lock file on disk. If you don’t care about the library’s session cache, then you can probably just find the database file and delete it.

Staff

giles
|
11190
posts
|

PythonAnywhere staff
|



Aug. 8, 2020, 3:47 p.m.

|
permalink

Hi, I am getting a telegram error can anybody help..?
Below is error:

Attempt 1 at connecting failed: ConnectionRefusedError: [Errno 111] Connect call failed (‘149.154.167.51’, 443)
Attempt 2 at connecting failed: ConnectionRefusedError: [Errno 111] Connect call failed (‘149.154.167.51’, 443)
Attempt 3 at connecting failed: ConnectionRefusedError: [Errno 111] Connect call failed (‘149.154.167.51’, 443)
Attempt 4 at connecting failed: ConnectionRefusedError: [Errno 111] Connect call failed (‘149.154.167.51’, 443)
Attempt 5 at connecting failed: ConnectionRefusedError: [Errno 111] Connect call failed (‘149.154.167.51’, 443)
Attempt 6 at connecting failed: ConnectionRefusedError: [Errno 111] Connect call failed (‘149.154.167.51’, 443)
Traceback (most recent call last):
File «/home/harkunwarkhera/tele.py», line 5, in <module>
with TelegramClient(‘eth_kunwar’, api_id, api_hash) as client:
File «/home/harkunwarkhera/.local/lib/python3.8/site-packages/telethon/helpers.py», line 184, in _sync_enter
return loop.run_until_complete(self.aenter())
File «/usr/lib/python3.8/asyncio/base_events.py», line 608, in run_until_complete
return future.result()
File «/home/harkunwarkhera/.local/lib/python3.8/site-packages/telethon/client/auth.py», line 713, in aenter
return await self.start()
File «/home/harkunwarkhera/.local/lib/python3.8/site-packages/telethon/client/auth.py», line 140, in _start
await self.connect()
File «/home/harkunwarkhera/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py», line 513, in connect
if not await self._sender.connect(self._connection(
File «/home/harkunwarkhera/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py», line 127, in connect
await self._connect()
File «/home/harkunwarkhera/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py», line 253, in _connect
raise ConnectionError(‘Connection to Telegram failed {} time(s)’.format(self._retries))
ConnectionError: Connection to Telegram failed 5 time(s)

deleted-user-10521730
|
3
posts
|



April 26, 2021, 6:55 a.m.

|
permalink

How is your bot configured? Are you sure that you are actually running the code that configures the connection to use the proxy?

Staff

fjl
|
3651
posts
|

PythonAnywhere staff
|



April 26, 2021, 10:11 a.m.

|
permalink

Hi I am using api_id and api_hash this is my code:

from telethon.sync import TelegramClient
import time
api_id = xx
api_hash = xxx
with TelegramClient(‘eth_kunwar’, api_id, api_hash) as client:
print(‘enter number’)
destination_user_username = ‘@xx’
entity = client.get_entity(destination_user_username)
while True:
try:
client.send_message(entity = entity,message=’hello’)
time.sleep(30)
except:
print(‘error’)
client.run_until_disconnected()
client.run_until_disconnected()

deleted-user-10521730
|
3
posts
|



April 26, 2021, 1:35 p.m.

|
permalink

telegram client line:

with TelegramClient(‘eth_kunwar’, api_id, api_hash) as client:

deleted-user-10521730
|
3
posts
|



April 26, 2021, 1:35 p.m.

|
permalink

Your client is using mtprotosender, which will not work on PythonAnywhere in a free account. Check the documentation of the client you’re using to see whether you can get it to use http instead and, if you can, then also make sure that you have configured it to use http through the PythonAnywhere proxy.

Staff

glenn
|
8695
posts
|

PythonAnywhere staff
|



April 26, 2021, 4:54 p.m.

|
permalink

Понравилась статья? Поделить с друзьями:
  • Apache php show error
  • Api error api unavailable
  • Apache php error reporting
  • Api error 422
  • Api error 35 expiration time overrun occurred