File size: 3,299 Bytes
301c4bf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | #!/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())
|