#!/usr/bin/env python3 """ Interactive script to authorize a Telethon session. Run LOCALLY before deploying: python scripts/authorize_session.py Then upload the generated .session file to your HF Dataset repo: data/sessions/default.session → HF: sessions/default.session Or set HF_TOKEN and HF_DATASET_REPO and it will upload automatically. """ import asyncio import os import sys from pathlib import Path # Allow importing from project root sys.path.insert(0, str(Path(__file__).parent.parent)) from dotenv import load_dotenv load_dotenv() async def main(): api_id = int(os.getenv("TG_API_ID", "0")) api_hash = os.getenv("TG_API_HASH", "") if not api_id or not api_hash: print("āŒ TG_API_ID and TG_API_HASH must be set in .env") sys.exit(1) session_name = input("Session name (default: 'default'): ").strip() or "default" sessions_dir = Path(__file__).parent.parent / "data" / "sessions" sessions_dir.mkdir(parents=True, exist_ok=True) session_path = sessions_dir / session_name from telethon import TelegramClient from telethon.errors import SessionPasswordNeededError client = TelegramClient(str(session_path), api_id, api_hash) await client.connect() if await client.is_user_authorized(): me = await client.get_me() print(f"āœ… Already authorized as {me.first_name} (@{me.username})") else: phone = input("Phone number (with country code, e.g. +1234567890): ").strip() await client.send_code_request(phone) code = input("Enter the code from Telegram: ").strip() try: await client.sign_in(phone, code) except SessionPasswordNeededError: password = input("Two-factor authentication password: ").strip() await client.sign_in(password=password) me = await client.get_me() print(f"āœ… Authorized as {me.first_name} (@{me.username})") await client.disconnect() session_file = Path(str(session_path) + ".session") print(f"\nšŸ“ Session saved: {session_file}") # Optional: upload to HF hf_token = os.getenv("HF_TOKEN", "") hf_repo = os.getenv("HF_DATASET_REPO", "") if hf_token and hf_repo: upload = input("\nUpload session to HuggingFace Dataset? (y/N): ").strip().lower() if upload == "y": from huggingface_hub import HfApi, CommitOperationAdd api = HfApi(token=hf_token) try: api.create_repo(hf_repo, repo_type="dataset", exist_ok=True, private=True) api.upload_file( path_or_fileobj=str(session_file), path_in_repo=f"sessions/{session_file.name}", repo_id=hf_repo, repo_type="dataset", token=hf_token, commit_message=f"Add session: {session_file.name}", ) print(f"āœ… Session uploaded to {hf_repo}/sessions/{session_file.name}") except Exception as e: print(f"āŒ Upload failed: {e}") else: print("\nšŸ’” To deploy: upload this session file to your HF Dataset repo") print(f" Path in repo: sessions/{session_file.name}") if __name__ == "__main__": asyncio.run(main())