| 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: |
| |
| self.client.start() |
| self.is_connected = True |
| print("β
Session connected successfully.") |
| return True |
| except FileNotFoundError: |
| print("Session file not found. Starting new session login...") |
| |
| 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() |
| |
| 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 |
|
|