Forums

Telethon ConnectionError

Hi. I am testing a small script that works with telegram api through python module 'Telethon'. Here is the code:

from telethon import TelegramClient, events, sync
import socks
import os


def main():
    TELEGRAM_API_ID = os.environ['API_ID']
    TELEGRAM_API_HASH = os.environ['API_HASH']
    if os.environ.get('PYTHONANYWHERE_DOMAIN'):
        pythonanywhere_proxy = (socks.HTTP, 'proxy.server', 3128)
        print('Connecting through proxy')
        telegram_client = TelegramClient('testing_session', TELEGRAM_API_ID, TELEGRAM_API_HASH, 
                                         proxy=pythonanywhere_proxy)
    else:
        telegram_client = TelegramClient('testing_session', TELEGRAM_API_ID, TELEGRAM_API_HASH)
    telegram_client.start(force_sms=True)


if __name__ == '__main__':
    main()

When i launch it on my PC it works correct, but when i try to run it on the Pythonanywhere server it fails with an error:

$ python3.8 test.py
Connecting through proxy
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    main()
  File "test.py", line 15, in main
    telegram_client.start(force_sms=True)
  File "/home/Maxu360/.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/Maxu360/.local/lib/python3.8/site-packages/telethon/client/auth.py", line 139, in _start
    await self.connect()
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/client/telegrambaseclient.py", line 439, in connect
    if not await self._sender.connect(self._connection(
  File "/home/Maxu360/.local/lib/python3.8/site-packages/telethon/network/mtprotosender.py", line 125, in connect
    await self._connect()
  File "/home/Maxu360/.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)

I got this error before, and then i found this article: http://help.pythonanywhere.com/pages/403ForbiddenError/ so I connected through proxy, but nothing changed. It is strange because I found this in the whitelist:

...
api.telegram.org
...
core.telegram.org
...

Hope you will help me to solve this problem. Thank you.

Are you sure that you are actually running the code that configures the connection to use the proxy?

As described here https://docs.telethon.dev/en/latest/modules/client.html#telethon-client If "connection" is not MTProxy, proxy argument for TelegramClient" meant to store function parameters for PySocks, like (type, 'hostname', port). And as also described there, by defaullt connection is "telethon.network.connection.tcpfull.ConnectionTcpFull.". Correct me if I am wrong.

P.S. I have just checked the same code from my PC using free http proxy from the internet. It connected.

I see that MTProtoSender can use a number of different transports. Make sure that it is using the HTTP transport and not one of the others.

Sadly, but I can not make it work with HTTP connection even from my local pc. I did not know that free accounts supports only HTTP connection, it was not mention on help page. Thank you for response.

by the way, perhaps try to follow some of the instructions from here to make it work from your local pc?

Thank you for reply, but this is instruction about how to create telegram bot using teletop, and i want to create telegram client with telethon.

In that case, you'll have to rely on the telethon documentation to get it working.

you should use something like python-telegram-bot, pytelegrambotapi etc which uses http api. telethon uses mtProto over tcp which might not be supported through pythonanywhere

Yeah i understand, but the problem is, that i want to create a little script, that will act as a user, not bot. Anyway thank you for reply, if I find the solution, i will share it here.

hi! Maxu360, what about your question? did you find solution? i have a problem like this..

hi! vikadashyan , Maxu360 , did you find out how to solve the problem with telethon ?

https://blog.pythonanywhere.com/148/

Update 2020-01-12 For some reason Telegram has stopped accepting wildcard HTTPS certificates for bots, so unfortunately this tutorial will no longer work on a PythonAnywhere free account. For the webhooks part of the tutorial to work, you will have to get a paying account with a custom domain. Thanks to fivechar for letting us know in the comments.

so it seems, there is no free way....

That only applies if you're using a webhook-based system for your bot -- if it's a script that connects outwards to Telegram, and runs in a console, then it should still work.

One caveat: consoles do get reset from time to time as part of system maintenance, so your bot would stop working when that happened and you would have to restart it. Paid accounts can set up bots as always-on tasks, which would allow you to avoid that.

thx for caveat, but I cant even connect to telegramm api. neither through 'proxy.server:3128 nor my proxy

Which library are you using?

[edit: I see you've posted on another forum thread, so I'll pick it up there]

as signed it tilte of topic - I am trying to set up Telethon library. thx for help

why doesn't the code come from telethon telegrams on your hosting?

@Adrianvorto What do you mean?