Files
overub/scripts/generate-session-string.py

76 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""
Generate a Telethon StringSession for OverUB.
"""
import argparse
import asyncio
import os
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.sessions import StringSession
async def generate(args: argparse.Namespace) -> None:
if os.path.exists(".env"):
with open(".env", "r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
api_id = os.getenv("OVERUB_API_ID") or os.getenv("API_ID")
api_hash = os.getenv("OVERUB_API_HASH") or os.getenv("API_HASH")
if not api_id or not api_hash:
print("API_ID/API_HASH required (set OVERUB_API_ID/OVERUB_API_HASH or API_ID/API_HASH).")
return
try:
api_id = int(api_id)
except ValueError:
print("API_ID must be an integer")
return
print("Starting session generation. You will be prompted to log in.")
client = TelegramClient(StringSession(), api_id, api_hash)
await client.connect()
if await client.is_user_authorized():
session_string = client.session.save()
await client.disconnect()
print("\nSession string:")
print(session_string)
print("\nAdd to .env as OVERUB_SESSION_STRING=" + session_string)
return
phone = args.phone or os.getenv("OVERUB_PHONE") or os.getenv("PHONE")
if not phone:
phone = input("Phone number (+123456789): ").strip()
sent = await client.send_code_request(phone, force_sms=args.sms)
code_type = getattr(sent, "type", None)
print(f"Code delivery type: {type(code_type).__name__ if code_type else 'unknown'}")
code = input("Enter the code you received: ").strip()
try:
await client.sign_in(phone=phone, code=code, phone_code_hash=sent.phone_code_hash)
except SessionPasswordNeededError:
password = input("Two-step verification password: ").strip()
await client.sign_in(password=password)
session_string = client.session.save()
await client.disconnect()
print("\nSession string:")
print(session_string)
print("\nAdd to .env as OVERUB_SESSION_STRING=" + session_string)
def main() -> None:
parser = argparse.ArgumentParser(description="Generate Telethon StringSession for OverUB")
parser.add_argument("--phone", default="")
parser.add_argument("--sms", action="store_true", help="Force SMS delivery")
args = parser.parse_args()
asyncio.run(generate(args))
if __name__ == "__main__":
main()