Download telegram_uploader.py from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/telegram_uploader.py
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/telegram_uploader.py
-
curl -L -o telegram_uploader.py https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/telegram_uploader.py
12.1 kB
| #!/usr/bin/env python3 | |
| """ | |
| Telegram Video Uploader for MedMembers OFT 2026 | |
| Uploads video files from secure_media/ to a Telegram channel via MTProto, | |
| then registers them in the SQLite database with telegram_message_id for streaming. | |
| Usage: | |
| # Upload a single file | |
| python telegram_uploader.py --file "secure_media/VID_1068_c592ea8e.mp4" | |
| # Upload all videos from secure_media/ | |
| python telegram_uploader.py --folder "../secure_media" --type video | |
| # Upload all images | |
| python telegram_uploader.py --folder "../secure_media" --type image | |
| # List uploaded files | |
| python telegram_uploader.py --list | |
| # Export media index to JSON | |
| python telegram_uploader.py --export media_files.json | |
| Requires environment variables: | |
| TELEGRAM_BOT_TOKEN, TELEGRAM_CHANNEL_ID, TELEGRAM_API_ID, TELEGRAM_API_HASH | |
| """ | |
| import os | |
| import sys | |
| import json | |
| import time | |
| import sqlite3 | |
| import argparse | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, BASE_DIR) | |
| from config import Config | |
| DB_PATH = Config.DB_PATH | |
| VIDEO_EXTENSIONS = {'.mp4', '.mkv', '.avi', '.mov'} | |
| IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp'} | |
| def get_db(): | |
| db = sqlite3.connect(DB_PATH) | |
| db.row_factory = sqlite3.Row | |
| return db | |
| def ensure_media_table(db): | |
| """Create media_files table if it doesn't exist.""" | |
| db.execute(""" | |
| CREATE TABLE IF NOT EXISTS media_files ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| file_id TEXT NOT NULL, | |
| file_unique_id TEXT, | |
| file_type TEXT NOT NULL DEFAULT 'document', | |
| filename TEXT NOT NULL, | |
| original_path TEXT, | |
| category TEXT NOT NULL DEFAULT 'Geral', | |
| subcategory TEXT, | |
| title TEXT, | |
| description TEXT, | |
| size_bytes INTEGER DEFAULT 0, | |
| duration_seconds INTEGER, | |
| telegram_message_id INTEGER, | |
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP | |
| ) | |
| """) | |
| db.execute("CREATE INDEX IF NOT EXISTS idx_media_filename ON media_files(filename)") | |
| db.execute("CREATE INDEX IF NOT EXISTS idx_media_category ON media_files(category)") | |
| db.execute("CREATE INDEX IF NOT EXISTS idx_media_file_type ON media_files(file_type)") | |
| db.commit() | |
| def is_already_uploaded(db, filename, size_bytes): | |
| """Check if a file with the same name and size is already in the database.""" | |
| row = db.execute( | |
| "SELECT id FROM media_files WHERE filename = ? AND size_bytes = ?", | |
| (filename, size_bytes) | |
| ).fetchone() | |
| return row is not None | |
| def register_upload(db, result, filepath, category): | |
| """Register an uploaded file in the database.""" | |
| filename = os.path.basename(filepath) | |
| ext = os.path.splitext(filename)[1].lower() | |
| if ext in VIDEO_EXTENSIONS: | |
| file_type = 'video' | |
| elif ext in IMAGE_EXTENSIONS: | |
| file_type = 'photo' | |
| else: | |
| file_type = 'document' | |
| db.execute(""" | |
| INSERT INTO media_files | |
| (file_id, file_unique_id, file_type, filename, original_path, category, | |
| title, size_bytes, telegram_message_id) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| """, ( | |
| result.get('file_id', ''), | |
| result.get('file_unique_id', ''), | |
| file_type, | |
| filename, | |
| os.path.abspath(filepath), | |
| category, | |
| filename, | |
| result.get('size', os.path.getsize(filepath)), | |
| result.get('message_id', 0), | |
| )) | |
| db.commit() | |
| def reset_streamer(): | |
| """Force-reset the TelegramStreamer singleton for reconnection.""" | |
| from telegram_client import TelegramStreamer | |
| with TelegramStreamer._lock: | |
| old = TelegramStreamer._instance | |
| if old and old._loop: | |
| try: | |
| old._loop.call_soon_threadsafe(old._loop.stop) | |
| except Exception: | |
| pass | |
| TelegramStreamer._instance = None | |
| time.sleep(2) | |
| return TelegramStreamer.get_instance() | |
| def upload_file(filepath, category='MedMembers', max_retries=3): | |
| """Upload a single file to Telegram via MTProto with retry logic.""" | |
| from telegram_client import TelegramStreamer | |
| filename = os.path.basename(filepath) | |
| size = os.path.getsize(filepath) | |
| size_mb = size / (1024 * 1024) | |
| for attempt in range(1, max_retries + 1): | |
| streamer = TelegramStreamer.get_instance() | |
| if not streamer or not streamer.is_ready(): | |
| if attempt < max_retries: | |
| print(f" Reconnecting Telegram client (attempt {attempt})...") | |
| streamer = reset_streamer() | |
| if not streamer or not streamer.is_ready(): | |
| print(" ERROR: Could not reconnect. Retrying in 10s...") | |
| time.sleep(10) | |
| continue | |
| else: | |
| print("ERROR: Telegram MTProto client not ready after retries.") | |
| return None | |
| print(f" Uploading: {filename} ({size_mb:.1f} MB)..." + (f" [retry {attempt}]" if attempt > 1 else "")) | |
| start = time.time() | |
| result = streamer.upload_file_sync(filepath, category, caption=f"{category} | {filename}") | |
| if result: | |
| elapsed = time.time() - start | |
| speed = size_mb / elapsed if elapsed > 0 else 0 | |
| print(f" OK: msg_id={result['message_id']}, {elapsed:.1f}s ({speed:.1f} MB/s)") | |
| return result | |
| else: | |
| print(f" FAILED (attempt {attempt}/{max_retries})") | |
| if attempt < max_retries: | |
| print(f" Resetting connection and retrying in 5s...") | |
| streamer = reset_streamer() | |
| time.sleep(5) | |
| print(f" FAILED after {max_retries} attempts: {filename}") | |
| return None | |
| def upload_folder(folder_path, file_type='video', category='MedMembers'): | |
| """Upload all files of a type from a folder.""" | |
| if file_type == 'video': | |
| extensions = VIDEO_EXTENSIONS | |
| elif file_type == 'image': | |
| extensions = IMAGE_EXTENSIONS | |
| else: | |
| extensions = VIDEO_EXTENSIONS | IMAGE_EXTENSIONS | |
| files = [] | |
| for f in sorted(os.listdir(folder_path)): | |
| ext = os.path.splitext(f)[1].lower() | |
| if ext in extensions: | |
| files.append(os.path.join(folder_path, f)) | |
| if not files: | |
| print(f"No {file_type} files found in {folder_path}") | |
| return | |
| db = get_db() | |
| ensure_media_table(db) | |
| total = len(files) | |
| uploaded = 0 | |
| skipped = 0 | |
| failed = 0 | |
| print(f"\nFound {total} {file_type} files to upload") | |
| print("=" * 60) | |
| consecutive_failures = 0 | |
| max_consecutive_failures = 5 | |
| for i, filepath in enumerate(files, 1): | |
| filename = os.path.basename(filepath) | |
| size = os.path.getsize(filepath) | |
| print(f"\n[{i}/{total}] {filename}") | |
| if is_already_uploaded(db, filename, size): | |
| print(f" SKIP: Already uploaded") | |
| skipped += 1 | |
| continue | |
| result = upload_file(filepath, category) | |
| if result: | |
| register_upload(db, result, filepath, category) | |
| uploaded += 1 | |
| consecutive_failures = 0 | |
| else: | |
| failed += 1 | |
| consecutive_failures += 1 | |
| if consecutive_failures >= max_consecutive_failures: | |
| print(f"\n {max_consecutive_failures} consecutive failures. Resetting connection...") | |
| reset_streamer() | |
| time.sleep(10) | |
| consecutive_failures = 0 | |
| # Small delay to avoid Telegram rate limits | |
| if i < total: | |
| time.sleep(1) | |
| db.close() | |
| print(f"\n{'=' * 60}") | |
| print(f"Upload complete: {uploaded} uploaded, {skipped} skipped, {failed} failed") | |
| def list_uploads(): | |
| """List all uploaded media files.""" | |
| db = get_db() | |
| ensure_media_table(db) | |
| rows = db.execute(""" | |
| SELECT filename, file_type, category, size_bytes, telegram_message_id, created_at | |
| FROM media_files ORDER BY category, filename | |
| """).fetchall() | |
| if not rows: | |
| print("No media files in database.") | |
| return | |
| print(f"\n{'Filename':<45} {'Type':<8} {'Size':>10} {'MsgID':>8} {'Category':<20}") | |
| print("-" * 100) | |
| for r in rows: | |
| size = f"{(r['size_bytes'] or 0) / 1024 / 1024:.1f}MB" | |
| print(f"{r['filename']:<45} {r['file_type']:<8} {size:>10} {r['telegram_message_id'] or 0:>8} {r['category']:<20}") | |
| total = len(rows) | |
| total_size = sum(r['size_bytes'] or 0 for r in rows) / (1024 * 1024 * 1024) | |
| print(f"\nTotal: {total} files, {total_size:.2f} GB") | |
| db.close() | |
| def export_index(output_path): | |
| """Export media_files table to JSON for Docker deployment.""" | |
| db = get_db() | |
| ensure_media_table(db) | |
| rows = db.execute("SELECT * FROM media_files ORDER BY id").fetchall() | |
| data = [dict(r) for r in rows] | |
| with open(output_path, 'w', encoding='utf-8') as f: | |
| json.dump(data, f, ensure_ascii=False, indent=2) | |
| print(f"Exported {len(data)} records to {output_path}") | |
| db.close() | |
| def import_index(input_path): | |
| """Import media_files from JSON (for Docker deployment).""" | |
| db = get_db() | |
| ensure_media_table(db) | |
| with open(input_path, 'r', encoding='utf-8') as f: | |
| data = json.load(f) | |
| count = 0 | |
| for item in data: | |
| existing = db.execute( | |
| "SELECT id FROM media_files WHERE filename = ? AND telegram_message_id = ?", | |
| (item['filename'], item.get('telegram_message_id', 0)) | |
| ).fetchone() | |
| if existing: | |
| continue | |
| db.execute(""" | |
| INSERT INTO media_files | |
| (file_id, file_unique_id, file_type, filename, original_path, category, | |
| subcategory, title, description, size_bytes, duration_seconds, | |
| telegram_message_id, created_at) | |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| """, ( | |
| item.get('file_id', ''), | |
| item.get('file_unique_id', ''), | |
| item.get('file_type', 'document'), | |
| item['filename'], | |
| item.get('original_path', ''), | |
| item.get('category', 'Geral'), | |
| item.get('subcategory'), | |
| item.get('title'), | |
| item.get('description'), | |
| item.get('size_bytes', 0), | |
| item.get('duration_seconds'), | |
| item.get('telegram_message_id', 0), | |
| item.get('created_at'), | |
| )) | |
| count += 1 | |
| db.commit() | |
| print(f"Imported {count} new records from {input_path}") | |
| db.close() | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser(description='MedMembers Telegram Media Uploader') | |
| parser.add_argument('--file', help='Upload a single file') | |
| parser.add_argument('--folder', help='Upload all files from a folder') | |
| parser.add_argument('--type', default='video', choices=['video', 'image', 'all'], | |
| help='File type filter for --folder') | |
| parser.add_argument('--category', default='MedMembers', help='Category name') | |
| parser.add_argument('--list', action='store_true', help='List uploaded files') | |
| parser.add_argument('--export', help='Export index to JSON file') | |
| parser.add_argument('--import-json', dest='import_json', help='Import index from JSON file') | |
| args = parser.parse_args() | |
| if args.list: | |
| list_uploads() | |
| elif args.export: | |
| export_index(args.export) | |
| elif args.import_json: | |
| import_index(args.import_json) | |
| elif args.file: | |
| if not os.path.exists(args.file): | |
| print(f"File not found: {args.file}") | |
| sys.exit(1) | |
| db = get_db() | |
| ensure_media_table(db) | |
| result = upload_file(args.file, args.category) | |
| if result: | |
| register_upload(db, result, args.file, args.category) | |
| print("Upload registered in database.") | |
| db.close() | |
| elif args.folder: | |
| if not os.path.isdir(args.folder): | |
| print(f"Folder not found: {args.folder}") | |
| sys.exit(1) | |
| upload_folder(args.folder, args.type, args.category) | |
| else: | |
| parser.print_help() | |