77
88from telethon import TelegramClient , events
99from telethon .errors import FloodWaitError , PasswordHashInvalidError , PhoneCodeInvalidError , SessionPasswordNeededError
10+ from telethon .network .connection import ConnectionTcpMTProxyRandomizedIntermediate
1011from telethon .tl .types import User
1112
1213from app .config import settings
@@ -22,6 +23,13 @@ class TelegramService:
2223 def __init__ (self ):
2324 self .clients : Dict [str , TelegramClient ] = {}
2425 self ._ensure_session_directory ()
26+ self ._proxy = self ._build_proxy ()
27+
28+ def _build_proxy (self ):
29+ """Return proxy config tuple for MTProto if enabled."""
30+ if settings .use_mtproto_proxy and settings .mtproto_host and settings .mtproto_port and settings .mtproto_secret :
31+ return (settings .mtproto_host , int (settings .mtproto_port ), settings .mtproto_secret )
32+ return None
2533
2634 def _ensure_session_directory (self ):
2735 """Ensure the session directory exists."""
@@ -34,7 +42,19 @@ def _get_session_file_path(self, session_id: str) -> str:
3442 async def create_client (self , session_id : str ) -> TelegramClient :
3543 """Create a new Telegram client for a session."""
3644 session_file = self ._get_session_file_path (session_id )
37- client = TelegramClient (session_file , settings .telegram_api_id , settings .telegram_api_hash )
45+ client_kwargs = {}
46+ if self ._proxy :
47+ client_kwargs .update (
48+ connection = ConnectionTcpMTProxyRandomizedIntermediate ,
49+ proxy = self ._proxy ,
50+ )
51+
52+ client = TelegramClient (
53+ session_file ,
54+ settings .telegram_api_id ,
55+ settings .telegram_api_hash ,
56+ ** client_kwargs ,
57+ )
3858 self .clients [session_id ] = client
3959 logger .info (f"Created Telegram client for session: { session_id } " )
4060 return client
0 commit comments