Files
TG_autoposter/init_telethon_session.py
Andrew K. Choi 5a00e161e6 🔐 Add Telethon session initialization tools and authorization guide
NEW FILES:
 init_telethon_session.py - Interactive Python script for session initialization
 init_telethon_session.sh - Bash wrapper for Docker-based authorization
 TELETHON_AUTHORIZATION_GUIDE.md - Comprehensive authorization guide
 USERBOT_AUTHORIZATION_README.md - Quick start guide for users

FEATURES:
 Interactive authorization flow with SMS code verification
 2FA password support
 Session persistence to app/sessions/
 Docker container integration
 Verification of existing sessions
 Clear error messages and troubleshooting

USAGE:
$ ./init_telethon_session.sh
Or:
$ python3 init_telethon_session.py

This solves the UserBot authorization issue where Telethon requires
interactive SMS code verification on first setup.
2025-12-21 12:12:22 +09:00

227 lines
6.9 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
Telethon Session Initialization Script
Инициализирует сессию Telethon с интерактивной авторизацией
Сохраняет сессию для использования в Docker контейнере
Использование:
python3 init_telethon_session.py
"""
import asyncio
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
from telethon import TelegramClient
from telethon.sessions import StringSession
import logging
# Configure logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Load environment variables
env_path = Path(__file__).parent / '.env'
load_dotenv(env_path)
# Get Telethon credentials
TELETHON_API_ID = os.getenv('TELETHON_API_ID')
TELETHON_API_HASH = os.getenv('TELETHON_API_HASH')
TELETHON_PHONE = os.getenv('TELETHON_PHONE')
# Session directory
SESSION_DIR = Path(__file__).parent / 'app' / 'sessions'
SESSION_FILE = SESSION_DIR / 'userbot_session.session'
SESSION_STRING_FILE = SESSION_DIR / 'telethon_string_session.txt'
async def initialize_session():
"""Initialize Telethon session with interactive authentication"""
print("\n" + "="*80)
print("🚀 Telethon Session Initialization")
print("="*80)
# Verify credentials
if not all([TELETHON_API_ID, TELETHON_API_HASH, TELETHON_PHONE]):
print("❌ Missing Telethon credentials in .env:")
print(f" TELETHON_API_ID: {bool(TELETHON_API_ID)}")
print(f" TELETHON_API_HASH: {bool(TELETHON_API_HASH)}")
print(f" TELETHON_PHONE: {bool(TELETHON_PHONE)}")
print("\nPlease set these variables in .env file")
return False
# Create session directory
SESSION_DIR.mkdir(parents=True, exist_ok=True)
try:
# Create Telethon client
client = TelegramClient(
str(SESSION_FILE),
api_id=int(TELETHON_API_ID),
api_hash=TELETHON_API_HASH
)
print(f"\n📱 Phone: {TELETHON_PHONE}")
print(f"🔐 API ID: {TELETHON_API_ID}")
# Connect to Telegram
print("\n🔗 Connecting to Telegram...")
await client.connect()
print("✅ Connected!")
# Check if already authorized
if await client.is_user_authorized():
print(" Session already authorized!")
me = await client.get_me()
print(f"👤 User: {me.first_name} (@{me.username})")
else:
# Start authorization flow
print("\n🔐 Starting authorization process...")
print(f"📲 You will receive an SMS code to {TELETHON_PHONE}")
# Send auth code request
await client.send_code_request(TELETHON_PHONE)
# Get code from user
try:
code = input("\n📝 Enter the SMS code: ").strip()
# Try to sign in
try:
await client.sign_in(TELETHON_PHONE, code)
print("✅ Successfully signed in!")
except Exception as e:
# Might need 2FA
print(f"⚠️ {str(e)}")
password = input("🔒 Enter 2FA password (if prompted): ").strip()
if password:
await client.sign_in(password=password)
print("✅ Successfully signed in with 2FA!")
else:
print("❌ Failed to sign in")
return False
except KeyboardInterrupt:
print("\n❌ Authorization cancelled by user")
return False
# Verify and save session
me = await client.get_me()
print(f"\n✅ Session initialized for: {me.first_name} (@{me.username})")
print(f" ID: {me.id}")
print(f" Username: @{me.username}")
# Get and save string session
string_session = StringSession.save(client.session)
with open(SESSION_STRING_FILE, 'w') as f:
f.write(string_session)
print(f"\n💾 Session saved to: {SESSION_FILE}")
print(f"💾 String session saved to: {SESSION_STRING_FILE}")
# Disconnect
await client.disconnect()
print("\n✅ Session initialization completed successfully!")
return True
except Exception as e:
print(f"\n❌ Error during session initialization: {e}")
logger.error(f"Error: {e}", exc_info=True)
return False
async def verify_session():
"""Verify existing session"""
print("\n" + "="*80)
print("🔍 Verifying existing session...")
print("="*80)
if not SESSION_FILE.exists():
print(f"❌ Session file not found: {SESSION_FILE}")
return False
try:
client = TelegramClient(
str(SESSION_FILE),
api_id=int(TELETHON_API_ID),
api_hash=TELETHON_API_HASH
)
print("🔗 Connecting with existing session...")
await client.connect()
if await client.is_user_authorized():
me = await client.get_me()
print(f"✅ Session is valid!")
print(f" User: {me.first_name} (@{me.username})")
print(f" ID: {me.id}")
await client.disconnect()
return True
else:
print("❌ Session is not authorized")
await client.disconnect()
return False
except Exception as e:
print(f"❌ Error verifying session: {e}")
return False
def print_instructions():
"""Print instructions for using the session in Docker"""
print("\n" + "="*80)
print("📋 Instructions for Docker")
print("="*80)
print("""
1. After session is created, the files will be at:
- app/sessions/userbot_session.session
- app/sessions/telethon_string_session.txt
2. Ensure these files are copied to Docker container:
docker cp app/sessions/ tg_autoposter_userbot:/app/
3. Or mount as volume in docker-compose.yml:
volumes:
- ./app/sessions:/app/app/sessions
4. Restart the UserBot container:
docker-compose restart userbot
5. Check logs:
docker-compose logs userbot -f
""")
async def main():
"""Main function"""
if len(sys.argv) > 1 and sys.argv[1] == '--verify':
# Verify existing session
result = await verify_session()
sys.exit(0 if result else 1)
# Initialize new session
result = await initialize_session()
if result:
print_instructions()
sys.exit(0)
else:
sys.exit(1)
if __name__ == '__main__':
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\n❌ Interrupted by user")
sys.exit(1)