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.
148 lines
4.5 KiB
Bash
Executable File
148 lines
4.5 KiB
Bash
Executable File
#!/bin/bash
|
||
# init_telethon_session.sh - Interactive Telethon session initialization
|
||
# This script helps authorize the Telethon UserBot by running it in the Docker container
|
||
|
||
set -e
|
||
|
||
CONTAINER_NAME="tg_autoposter_userbot"
|
||
SCRIPT_NAME="/app/init_telethon_session.py"
|
||
|
||
echo "=================================="
|
||
echo "🔐 Telethon Session Initialization"
|
||
echo "=================================="
|
||
echo ""
|
||
|
||
# Check if container is running
|
||
if ! docker-compose ps | grep -q "tg_autoposter_userbot.*Up"; then
|
||
echo "⚠️ UserBot container is not running"
|
||
echo "Starting containers..."
|
||
docker-compose up -d
|
||
sleep 5
|
||
fi
|
||
|
||
echo "🔗 Running initialization in Docker container..."
|
||
echo ""
|
||
echo "📱 Phone: $(grep TELETHON_PHONE .env | cut -d'=' -f2)"
|
||
echo ""
|
||
|
||
# Run the initialization script inside the container with interactive input
|
||
docker-compose exec -it userbot python3 <<'EOF'
|
||
import asyncio
|
||
import os
|
||
import sys
|
||
from pathlib import Path
|
||
from telethon import TelegramClient
|
||
from telethon.sessions import StringSession
|
||
|
||
# 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 paths
|
||
SESSION_FILE = '/app/app/sessions/userbot_session.session'
|
||
SESSION_STRING_FILE = '/app/app/sessions/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!")
|
||
return False
|
||
|
||
try:
|
||
# Create session directory
|
||
os.makedirs('/app/app/sessions', exist_ok=True)
|
||
|
||
# Create Telethon client
|
||
client = TelegramClient(
|
||
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("\nℹ️ Session already authorized!")
|
||
me = await client.get_me()
|
||
print(f"👤 User: {me.first_name} (@{me.username})")
|
||
await client.disconnect()
|
||
return True
|
||
|
||
# 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
|
||
code = input("\n📝 Enter the SMS code: ").strip()
|
||
|
||
try:
|
||
await client.sign_in(TELETHON_PHONE, code)
|
||
print("✅ Successfully signed in!")
|
||
except Exception as e:
|
||
if "PHONE_CODE_INVALID" in str(e):
|
||
print("❌ Invalid SMS code. Please try again.")
|
||
return False
|
||
# Might need 2FA
|
||
password = input("\n🔒 2FA Password (if enabled): ").strip()
|
||
if password:
|
||
await client.sign_in(password=password)
|
||
print("✅ Successfully signed in with 2FA!")
|
||
else:
|
||
print("❌ Failed to sign in")
|
||
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}")
|
||
|
||
# Save string session as backup
|
||
string_session = StringSession.save(client.session)
|
||
with open(SESSION_STRING_FILE, 'w') as f:
|
||
f.write(string_session)
|
||
|
||
print(f"\n💾 Session saved!")
|
||
print(f" {SESSION_FILE}")
|
||
|
||
# Disconnect
|
||
await client.disconnect()
|
||
print("\n✅ Session initialization completed successfully!")
|
||
return True
|
||
|
||
except Exception as e:
|
||
print(f"\n❌ Error: {e}")
|
||
return False
|
||
|
||
asyncio.run(initialize_session())
|
||
EOF
|
||
|
||
echo ""
|
||
echo "=================================="
|
||
echo "✅ Done!"
|
||
echo "=================================="
|
||
echo ""
|
||
echo "Restarting UserBot container..."
|
||
docker-compose restart userbot
|
||
|
||
echo ""
|
||
echo "Checking logs..."
|
||
sleep 3
|
||
docker-compose logs userbot --tail 20
|