"""
One-shot Telethon auth script (non-interactive).
Usage:
python auth.py +17789561333
It sends the code, then reads it from a file.
Drop the code into .auth_code file and it picks it up.
"""
import asyncio
import os
import sys
import time
from telethon import TelegramClient
from config import TELEGRAM_API_ID, TELEGRAM_API_HASH
SESSION_DIR = os.path.dirname(os.path.abspath(__file__))
SESSION_FILE = os.path.join(SESSION_DIR, "trading_session")
CODE_FILE = os.path.join(SESSION_DIR, ".auth_code")
async def authorize(phone: str):
client = TelegramClient(
SESSION_FILE,
TELEGRAM_API_ID,
TELEGRAM_API_HASH,
device_model="MacBook Pro",
system_version="macOS 14.3",
app_version="1.0.0",
lang_code="en",
system_lang_code="en-US",
)
await client.connect()
if await client.is_user_authorized():
me = await client.get_me()
print(f"โ Already authorized as {me.first_name} (ID: {me.id})")
await client.disconnect()
return
# Send code
result = await client.send_code_request(phone)
print(f"๐ฑ Code sent to {phone}")
print(f"Waiting for code in file: {CODE_FILE}")
print(f"Write it: echo 12345 > {CODE_FILE}")
# Remove old code file
if os.path.exists(CODE_FILE):
os.remove(CODE_FILE)
# Poll for code file (up to 120 seconds)
code = None
for i in range(120):
if os.path.exists(CODE_FILE):
with open(CODE_FILE) as f:
code = f.read().strip()
if code:
print(f"Got code: {code}")
break
await asyncio.sleep(1)
if not code:
print("โ Timeout โ no code received in 120 seconds")
await client.disconnect()
return
# Sign in
try:
await client.sign_in(phone=phone, code=code, phone_code_hash=result.phone_code_hash)
except Exception as e:
if "2fa" in str(e).lower() or "password" in str(e).lower() or "Two-steps" in str(e):
print(f"๐ 2FA required. Put your 2FA password in {CODE_FILE} and wait...")
os.remove(CODE_FILE)
password = None
for i in range(120):
if os.path.exists(CODE_FILE):
with open(CODE_FILE) as f:
password = f.read().strip()
if password:
break
await asyncio.sleep(1)
if password:
await client.sign_in(password=password)
else:
print("โ Timeout waiting for 2FA password")
await client.disconnect()
return
else:
raise
me = await client.get_me()
print(f"โ Authorized as {me.first_name} (ID: {me.id})")
print(f"Session saved. Now run: python bot.py")
# Cleanup
if os.path.exists(CODE_FILE):
os.remove(CODE_FILE)
await client.disconnect()
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python auth.py +17789561333")
sys.exit(1)
asyncio.run(authorize(sys.argv[1]))