Connection issues with Telethon library - getting TimeoutError

I’m trying to build a basic Telegram bot using the Telethon library but keep running into connection problems. Here’s my code:

from telethon import TelegramClient, events
from settings import *

bot_client = TelegramClient('my_bot_session', app_id=app_id, app_hash=app_hash)

@bot_client.on(events.NewMessage(pattern=r'/hello'))
async def hello_handler(msg):
    await bot_client.send_message(entity=msg.chat_id, message='Hello there!')

bot_client.start()
bot_client.run_until_disconnected()

Every time I run this code, I get multiple timeout errors and the bot fails to connect. The error shows several connection attempts failing with TimeoutError, and finally throws a ConnectionError saying “Connection to Telegram failed 5 time(s)”. I’ve tried using different VPN services and proxy settings but nothing seems to work. Has anyone faced similar connection issues with Telethon? What could be causing these timeout problems and how can I fix them?

Same thing happened to me on a corporate network. Wasn’t just timeouts - they were blocking Telegram’s connection protocol entirely. Try switching connection types by adding connection=ConnectionTcpMTProxyRandomizedIntermediate() to your TelegramClient parameters (you’ll need to import it first). Some ISPs also throttle Telegram during peak hours. My bot would die around 6-8 PM but worked fine in the morning. Test it at different times to see if that’s the issue. Setting the DC manually helped too - Telethon sometimes picks a distant data center by default.

i had this issue too, try increasing the timeout in your TelegramClient - like set connection_retries=10 and retry_delay=3. also check ur firewall, it might be blocking telethon. that worked for me!

The Problem: Your Telegram bot is experiencing connection timeouts and ConnectionError exceptions using the Telethon library, preventing it from connecting to Telegram. The error message indicates multiple failed connection attempts. You’ve tried using VPNs and proxies without success.

:thinking: Understanding the “Why” (The Root Cause):

The ConnectionError with multiple timeout attempts suggests a problem with your network connection to Telegram’s servers, not necessarily a code flaw in your bot. This could be due to several factors, including network restrictions, firewall issues, or temporary problems with Telegram’s infrastructure. The failure to resolve the issue with VPNs and proxies indicates the problem likely isn’t simply a blocked IP address.

:gear: Step-by-Step Guide:

  1. Increase Connection Retries and Delay: Modify your Telethon client initialization to increase the number of connection retries and the delay between retries. This gives the connection more chances to succeed despite temporary network hiccups. Add the following parameters to your TelegramClient instantiation:
from telethon import TelegramClient, events, ConnectionTcpMTProxyRandomizedIntermediate
from settings import *

bot_client = TelegramClient('my_bot_session', app_id=app_id, app_hash=app_hash, connection_retries=10, retry_delay=3)

# ... rest of your code ...
  1. Check Firewall and Network Restrictions: Ensure your firewall or network administrator isn’t blocking Telegram’s connection attempts. Telegram uses specific ports and protocols; temporarily disable your firewall to see if it resolves the issue. If it does, consult your network administrator to allow the necessary ports and protocols.

  2. Verify app_id and app_hash: Double-check that the app_id and app_hash values in your settings.py file are correct. Incorrect credentials will often manifest as connection errors rather than authentication failures.

  3. Test at Different Times: Some ISPs throttle or block Telegram connections during peak hours. Test your bot’s connection at various times of the day to see if connection issues are time-dependent.

  4. Try a Different Connection Type: Telethon supports different connection types. Try adding connection=ConnectionTcpMTProxyRandomizedIntermediate() to your TelegramClient parameters. This might help bypass network restrictions:

from telethon import TelegramClient, events, ConnectionTcpMTProxyRandomizedIntermediate
from settings import *

bot_client = TelegramClient('my_bot_session', app_id=app_id, app_hash=app_hash, connection=ConnectionTcpMTProxyRandomizedIntermediate())

# ... rest of your code ...

  1. Manually Set Data Center (DC): Telethon automatically selects a data center. Sometimes, this selection might be suboptimal due to network conditions. Find a closer data center and add connection_retries=10, retry_delay=3 and dc_id=<your_dc_id> to your TelegramClient:
bot_client = TelegramClient('my_bot_session', app_id=app_id, app_hash=app_hash, dc_id=143, connection_retries=10, retry_delay=3)

:mag: Common Pitfalls & What to Check Next:

  • Multiple Bot Instances: Avoid running multiple instances of your bot simultaneously with the same session file (my_bot_session in this case). Telegram might reject connections from multiple instances using the same session.
  • Flood Limits: If you’re making many requests, you might be hitting Telegram’s flood limits. Adding flood_sleep_threshold=60 to your TelegramClient parameters might help:
bot_client = TelegramClient('my_bot_session', app_id=app_id, app_hash=app_hash, flood_sleep_threshold=60)
  • Proxy Settings (Revisit): While you’ve tried proxies, ensure your proxy settings are correctly configured and that the proxy server itself is functioning properly.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.