From 5a00e161e63fe7a0a5a960cfce9ca12dd7b8f323 Mon Sep 17 00:00:00 2001 From: "Andrew K. Choi" Date: Sun, 21 Dec 2025 12:12:22 +0900 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=90=20Add=20Telethon=20session=20initi?= =?UTF-8?q?alization=20tools=20and=20authorization=20guide?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- TELETHON_AUTHORIZATION_GUIDE.md | 283 ++++++++++++++++++++++++++ USERBOT_AUTHORIZATION_README.md | 156 ++++++++++++++ app/sessions/telethon_session.session | Bin 28672 -> 28672 bytes init_telethon_session.py | 226 ++++++++++++++++++++ init_telethon_session.sh | 147 +++++++++++++ sessions/userbot_session.session | Bin 28672 -> 28672 bytes 6 files changed, 812 insertions(+) create mode 100644 TELETHON_AUTHORIZATION_GUIDE.md create mode 100644 USERBOT_AUTHORIZATION_README.md create mode 100644 init_telethon_session.py create mode 100755 init_telethon_session.sh diff --git a/TELETHON_AUTHORIZATION_GUIDE.md b/TELETHON_AUTHORIZATION_GUIDE.md new file mode 100644 index 0000000..f6cbcd5 --- /dev/null +++ b/TELETHON_AUTHORIZATION_GUIDE.md @@ -0,0 +1,283 @@ +# 🔐 Telethon UserBot Authorization Guide + +## Проблема + +При запуске UserBot контейнера видите ошибку: +``` +❌ UserBot не авторизован. Требуется повторный вход. +📲 Необходимо авторизироваться вручную через интерфейс. +``` + +Это нормально! Telethon требует двухфакторной авторизации при первом запуске. + +--- + +## ✅ Решение: Авторизация на локальной машине + +### Шаг 1: Инициализировать сессию локально + +```bash +# Перейти в директорию проекта +cd /home/trevor/dev/TG_autoposter + +# Запустить скрипт инициализации +python3 init_telethon_session.py +``` + +### Шаг 2: Следовать указаниям скрипта + +Скрипт попросит: +``` +📝 Enter the SMS code: [введите код из SMS] +``` + +1. Вы получите SMS с кодом подтверждения на номер `+821056936103` +2. Введите полученный код +3. Если включена 2FA, введите пароль двухфакторной аутентификации + +### Шаг 3: Проверить авторизацию + +```bash +# Проверить, что сессия корректна +python3 init_telethon_session.py --verify +``` + +Должно вывести: +``` +✅ Session is valid! + User: Your Name (@username) + ID: 123456789 +``` + +### Шаг 4: Перезагрузить контейнер + +```bash +# Перезагрузить UserBot контейнер +docker-compose restart userbot + +# Проверить логи +docker-compose logs userbot -f +``` + +Теперь должны увидеть: +``` +✅ UserBot инициализирован: Your Name (@username) +🔄 UserBot готов к обработке задач +``` + +--- + +## 📁 Файлы сессии + +После авторизации появятся файлы: +``` +app/sessions/ +├── userbot_session.session (основной файл сессии) +└── telethon_string_session.txt (резервная копия) +``` + +**⚠️ Важно**: Никогда не выкладывайте эти файлы в публичные репозитории! + +### Добавить в .gitignore + +```bash +# Убедитесь, что файлы сессии в .gitignore: +echo "app/sessions/" >> .gitignore +echo "sessions/" >> .gitignore +``` + +--- + +## 🐳 Использование в Docker + +### Вариант 1: Копировать сессию в контейнер + +```bash +# После авторизации, скопировать файлы в контейнер +docker cp app/sessions/ tg_autoposter_userbot:/app/ + +# Перезагрузить +docker-compose restart userbot +``` + +### Вариант 2: Монтировать том + +Отредактировать `docker-compose.yml`: + +```yaml +services: + userbot: + # ... остальная конфигурация ... + volumes: + - ./app/sessions:/app/app/sessions + - ./app:/app/app +``` + +Затем: +```bash +docker-compose up -d userbot +``` + +### Вариант 3: Авторизовать внутри контейнера + +```bash +# Запустить контейнер в интерактивном режиме +docker-compose run --rm userbot python3 init_telethon_session.py + +# Введите SMS код и пароль 2FA при запросе +``` + +--- + +## ⚠️ Решение проблем + +### Проблема: "Invalid API credentials" + +``` +❌ Invalid API credentials (400): SESSION_PASSWORD_NEEDED +``` + +**Решение**: Проверьте `TELETHON_API_ID` и `TELETHON_API_HASH` в `.env` +- Получите их на https://my.telegram.org +- Убедитесь что используете правильное сочетание + +### Проблема: "Flood Wait" ошибка + +``` +❌ Flood Wait X seconds +``` + +**Решение**: Подождите X секунд перед попыткой снова + +### Проблема: "PHONE_NUMBER_UNOCCUPIED" + +``` +❌ PHONE_NUMBER_UNOCCUPIED +``` + +**Решение**: Номер телефона не связан с аккаунтом Telegram. Проверьте номер в `.env` + +### Проблема: "Session not found" + +``` +❌ Session file not found +``` + +**Решение**: Запустите скрипт инициализации снова + +--- + +## 🔄 Автоматизация при развёртывании + +Для CI/CD пайплайна можно создать скрипт: + +```bash +#!/bin/bash +# deploy.sh + +# Проверить наличие сессии +if [ ! -f "app/sessions/userbot_session.session" ]; then + echo "⚠️ Telethon session not found!" + echo "📋 Run: python3 init_telethon_session.py" + exit 1 +fi + +# Запустить контейнеры +docker-compose up -d + +echo "✅ Deployment complete!" +``` + +--- + +## 📊 Проверка статуса + +### Проверить авторизацию в контейнере + +```bash +# Запустить проверку в контейнере +docker-compose exec userbot python3 init_telethon_session.py --verify +``` + +### Просмотреть логи инициализации + +```bash +# Логи UserBot +docker-compose logs userbot -f + +# Логи основного бота (использует UserBot) +docker-compose logs bot -f +``` + +### Проверить файлы сессии + +```bash +# Список файлов +ls -la app/sessions/ + +# Размер файла (должен быть > 100 bytes) +stat app/sessions/userbot_session.session +``` + +--- + +## 🎯 Следующие шаги + +После успешной авторизации: + +1. ✅ UserBot контейнер будет работать без ошибок +2. ✅ Нажмите "🤖 UserBot" в меню бота +3. ✅ Используйте "📥 Собрать группы" для сбора информации +4. ✅ Используйте "👥 Собрать участников" для парсинга членов группы + +--- + +## 💡 Дополнительно + +### Просмотр информации о сессии + +```bash +python3 -c " +import json +from telethon.sessions import SQLiteSession + +session = SQLiteSession('app/sessions/userbot_session') +print(f'Session ID: {session.id}') +print(f'Auth Key Available: {bool(session.auth_key)}') +" +``` + +### Удалить старую сессию + +```bash +rm -rf app/sessions/ +mkdir -p app/sessions + +# Затем повторить инициализацию +python3 init_telethon_session.py +``` + +--- + +## 🆘 Техническая поддержка + +Если возникают проблемы: + +1. Проверьте файл `.env`: + ```bash + grep -E "TELETHON|TELEGRAM_BOT" .env + ``` + +2. Проверьте логи скрипта: + ```bash + python3 init_telethon_session.py 2>&1 | tee init.log + ``` + +3. Проверьте интернет-соединение и доступ к Telegram + +4. Убедитесь что используется правильный номер телефона + +--- + +**Статус**: ✅ Руководство готово +**Последнее обновление**: 2025-12-21 diff --git a/USERBOT_AUTHORIZATION_README.md b/USERBOT_AUTHORIZATION_README.md new file mode 100644 index 0000000..13cab9d --- /dev/null +++ b/USERBOT_AUTHORIZATION_README.md @@ -0,0 +1,156 @@ +# ⚠️ UserBot Authorization Required - IMPORTANT + +## 🔐 What's Happening + +You're seeing this message in UserBot logs: +``` +❌ UserBot не авторизован. Требуется повторный вход. +``` + +This is **normal and expected** ✅ + +--- + +## ✅ Quick Fix (3 minutes) + +### Step 1: Open a terminal and run + +```bash +cd /home/trevor/dev/TG_autoposter + +# Make the script executable +chmod +x init_telethon_session.sh + +# Run the interactive authorization +./init_telethon_session.sh +``` + +### Step 2: Follow the prompts + +1. You'll see a message asking for SMS code: +``` +📝 Enter the SMS code: [wait for SMS] +``` + +2. **You'll receive an SMS** with a code to `+821056936103` + +3. Enter the code and press Enter + +4. If 2FA is enabled, enter your password + +5. Done! ✅ + +--- + +## 📋 Alternative: Manual Authorization + +If the script doesn't work, try this: + +```bash +# Run the Python script directly +python3 init_telethon_session.py +``` + +Or inside Docker: +```bash +docker-compose exec -it userbot python3 init_telethon_session.py +``` + +--- + +## 🎯 What's Happening Behind the Scenes + +1. **Telethon** (Telegram library) needs to authenticate with your user account +2. Telegram sends an SMS code for verification +3. The script saves this authentication session to `app/sessions/` +4. Docker container uses this saved session to work as your UserBot +5. No interaction needed after authorization - fully automated + +--- + +## ✅ How to Know It Worked + +After authorization, you'll see in logs: +``` +✅ UserBot инициализирован: Your Name (@username) +🔄 UserBot готов к обработке задач +``` + +And the bot will show "🤖 UserBot" button in the menu. + +--- + +## 🐛 Troubleshooting + +### "SMS code not received" +- Wait 30 seconds +- Check spam folder +- Make sure `TELETHON_PHONE` in `.env` is correct + +### "Invalid API credentials" +- Verify `TELETHON_API_ID` and `TELETHON_API_HASH` in `.env` +- Get them from https://my.telegram.org + +### "Session file already exists" +- Delete old session: `rm -rf app/sessions/` +- Run authorization again + +### Script timeout +- Re-run the script +- Make sure you're connected to internet + +--- + +## 📁 Files Created After Authorization + +``` +app/sessions/ +├── userbot_session.session ← Main session file +└── telethon_string_session.txt ← Backup +``` + +These files are **encrypted** and contain your session data. + +--- + +## 🚀 What to Do Next + +After successful authorization: + +1. ✅ Restart the bot: `docker-compose restart bot` + +2. ✅ Test `/start` command to bot + +3. ✅ Click "🤖 UserBot" button + +4. ✅ Collect groups or members + +--- + +## ⏱️ Expected Timeline + +| Step | Time | +|------|------| +| Open terminal | 1 min | +| Run script | 1 min | +| Receive SMS | 0-2 min | +| Enter code | 1 min | +| Done | **~5 minutes** | + +--- + +## 📞 Still Having Issues? + +1. Check the [detailed guide](./TELETHON_AUTHORIZATION_GUIDE.md) +2. Review logs: `docker-compose logs userbot -f` +3. Verify `.env` has all TELETHON variables +4. Make sure internet connection is stable + +--- + +**Start authorization now:** +```bash +./init_telethon_session.sh +``` + +✨ **You got this!** diff --git a/app/sessions/telethon_session.session b/app/sessions/telethon_session.session index 0a2002e329f90e87ce96068616227fbc8fcc4b3a..5b916a898216349a5b926db6366755e3f98d939e 100644 GIT binary patch delta 19 bcmZp8z}WDBae_4Cs);hrjH@;#EXW4{PL2oE delta 19 bcmZp8z}WDBae_4C@`*CejLSDBEXW4{PGJYm diff --git a/init_telethon_session.py b/init_telethon_session.py new file mode 100644 index 0000000..87a2306 --- /dev/null +++ b/init_telethon_session.py @@ -0,0 +1,226 @@ +#!/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) diff --git a/init_telethon_session.sh b/init_telethon_session.sh new file mode 100755 index 0000000..c4dd957 --- /dev/null +++ b/init_telethon_session.sh @@ -0,0 +1,147 @@ +#!/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 diff --git a/sessions/userbot_session.session b/sessions/userbot_session.session index 5987c8328052dd13e356c1db78d1528306506d51..ed73a4ec79bc8df21f74866acb660c0c86830b2f 100644 GIT binary patch delta 19 acmZp8z}WDBae_3X_Cy(HM(vFW3-SR+9R}6_ delta 19 acmZp8z}WDBae_3X(nJ|&Mx~7j3-SR*mIlNC