import os from telethon import TelegramClient from config import settings class SessionManager: def __init__(self): self.client = TelegramClient(settings.SESSION_NAME, settings.API_ID, settings.API_HASH) self.is_connected = False def connect(self): """Connects to Telegram, handling session loading or new login.""" print("Attempting to connect to Telegram...") try: # Attempt to start the client. If the session file exists, it loads. self.client.start() self.is_connected = True print("✅ Session connected successfully.") return True except FileNotFoundError: print("Session file not found. Starting new session login...") # First run: prompts for phone, code, and 2FA password self.client.start(phone=input("Enter your phone number (e.g., +1234567890): "), api_id=settings.API_ID, api_hash=settings.API_HASH) self.is_connected = True print("✅ Session established for the first time.") return True except Exception as e: print(f"❌ Connection Error: {e}") self.is_connected = False return False def disconnect(self): """Gracefully disconnects the client.""" if self.is_connected: self.client.disconnect() self.is_connected = False print("🔌 Session disconnected.") def get_client(self): """Returns the active Telethon client.""" if self.is_connected: return self.client else: print("⚠️ Session is not active. Reconnecting...") self.connect() return self.client def save_session(self): """Saves the active session state (optional, mainly for confirmation).""" if self.is_connected: self.client.disconnect() # In a real app, you might save client parameters, but Telethon handles session file saving automatically. print("Session explicitly disconnected and ready to be reconnected.") return True return False def delete_session(self): """Deletes the session file, forcing a fresh login next time.""" if os.path.exists(settings.SESSION_FILE): os.remove(settings.SESSION_FILE) print(f"🗑️ Session file '{settings.SESSION_FILE}' deleted. Next run requires re-authentication.") return True print("Session file does not exist to delete.") return False