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 inerrors
(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. Содержит информацию о типе возникшей ошибки: например, ошибка ввода данных, ошибка конфиденциальности или ошибка сервера.
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», Вам поможет инструкция в самом конце данной статьи
> > > Ссылка < < <
- Сначала перейдите на my.telegram.org
- В поле Your Phone Number введите Ваш номер телефона (рекомендуется использовать номер телефона Вашего фейк-аккаунта во избежание блокировки основного номера) и нажмите Next. На этот номер будет отправлено сообщение в Телеграм, который нам понадобится в следующем пункте.
- После этого у Вас появится поле Confirmation code. В это поле Вам необходимо вставить код, который Вы получите в приложении Telegram На телефоне или компьютере и нажать на кнопку Sign In.
- Далее нажимем на ссылку «API development tools»
- Вам предложат создать новое приложение.
Заполняем поля по примеру:
App title: Любое название на английском языке
Shortname: Любая строчка на английском языке без пробелов! Длина от 5 до 32 символа
Url: Ссылка на любой сайт, который не является популярным
Platform: Desktop
Description: Придумайте любое описание - Нажимаем «Create application»
Если на этом этапе Вы увидите окно с надписью «ERROR«, попробуйте отключить в Вашем браузере плагины-блокировщики рекламы или блокировщики сторонних файлов Cookie
Если все пройдет хорошо, то Вы увидите страницу похожую на скриншот ниже! - Поля 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) В телеграм-клиент этого фейк-аккаунта придет код. Копируем его и отправляем боту!
После отправки кода, бот выдаст Вам APP ID и API HASH! (смотри скриншот) Копируем их в соответствующие поля в программе Telegram-Spam-Master
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.
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.
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.
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?
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.
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?
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.
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?
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?
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.
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.
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))
….?
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)
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?
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.
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))
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.
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()
Почему видеть это ошибка?
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.
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?
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.
glenn
|
8695
posts
|
PythonAnywhere staff
|
April 26, 2021, 4:54 p.m.
|
permalink