Connection timeout issues when creating Telethon Telegram bot

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 handle_hello(msg):
    await bot_client.send_message(entity=msg.chat_id, message='Hello there!')

bot_client.start()
bot_client.run_until_disconnected()

Whenever I try to run this code, I get multiple timeout errors and the bot fails to connect to Telegram servers. I’ve already tried using different VPN services and proxy configurations but nothing seems to work. The error shows that all connection attempts are failing with TimeoutError messages, and eventually it gives up after 5 attempts with a ConnectionError saying ‘Connection to Telegram failed 5 time(s)’. Has anyone encountered similar connection issues with Telethon? What could be causing these repeated timeouts?

Hit this same issue 6 months back with Telethon. It’s usually a DC (data center) problem - Telethon gets stuck trying to connect to a specific DC that’s either having issues or too far from you. Delete your session file completely and let Telethon make a fresh one. That file stores connection preferences that cause these timeouts. Also double-check you’re hitting production servers, not test endpoints by mistake. And verify your app_id and app_hash are right - make sure the API application is set up correctly in your Telegram account.

sounds like u might have a firewall blocking it. i had similar probs when my antivirus stopped telethon from connecting. maybe try turning off windows defender or any security stuff temporarily. also, check if ur isp is blocking telegram traffic.

I’ve dealt with this same issue multiple times over the past two years using Telethon. It’s usually a network config problem, not your code. Add explicit timeout parameters when you initialize TelegramClient: connection_retries=3 and retry_delay=2. Also try switching connection types with connection=ConnectionTcpFull() (import from telethon.network). The default connection method breaks with some network setups. If you’re on a server or VPS, check your hosting provider’s outbound connection policies - they sometimes block Telegram’s API endpoints.