import asyncio import os import re import time from pathlib import Path from urllib.parse import parse_qs, urlparse import qbittorrentapi from pyrogram import Client, filters from pyrogram.errors import FloodWait, MessageNotModified from pyrogram.types import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message import aria2 from app import ( DOWNLOAD_PATH, PIXELDRAIN_API_KEY, STATE_FILE, STATE_LOCK, get_client, get_task_state_entry, is_rclone_upload_available, is_aria2_task, load_monitor_state, rclone_remote_label, save_monitor_state, serialize_torrent, start_gofile_upload_background, start_pixeldrain_upload_background, start_rclone_upload_background, validate_magnet_link, ) API_ID = int(os.getenv("TELEGRAM_API_ID", "2589472") or "0") API_HASH = os.getenv("TELEGRAM_API_HASH", "5243628014db9798d6775b330e542602") BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "6100847173:AAE1Ph_WWGEJhENvKKIzPhziO63cv3ruYKs") SESSION_NAME = os.getenv("TELEGRAM_BOT_SESSION", "torrent_web_bot") OWNER_IDS = { int(item.strip()) for item in os.getenv("TELEGRAM_OWNER_IDS", "1487943213").split(",") if item.strip().isdigit() } PROGRESS_INTERVAL_SECONDS = max(2, int(os.getenv("TELEGRAM_PROGRESS_INTERVAL_SECONDS", "3") or "3")) PROGRESS_TIMEOUT_SECONDS = max(60, int(os.getenv("TELEGRAM_PROGRESS_TIMEOUT_SECONDS", "86400") or "86400")) bot = Client(SESSION_NAME, api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN) def is_authorized(message_or_query) -> bool: if not OWNER_IDS: return True user = getattr(message_or_query, "from_user", None) return bool(user and user.id in OWNER_IDS) def command_argument(message: Message) -> str: text = message.text or message.caption or "" parts = text.split(maxsplit=1) return parts[1].strip() if len(parts) > 1 else "" def extract_btih(magnet: str) -> str: parsed = urlparse(magnet) for value in parse_qs(parsed.query).get("xt", []): if value.lower().startswith("urn:btih:"): return value[9:] return "" def progress_bar(progress: int, width: int = 12) -> str: value = max(0, min(int(progress or 0), 100)) filled = int((value / 100) * width) return "[" + "#" * filled + "-" * (width - filled) + "]" def task_snapshot(task_id: str) -> dict | None: state = load_monitor_state() if is_aria2_task(task_id): entry = state.get("aria2", {}).get(task_id) if not entry: return None item = aria2.serialize_task(entry) item["can_rclone_upload"] = bool(item.get("can_gofile_upload")) item["rclone_config_ready"] = is_rclone_upload_available() item["can_raw_rclone_upload"] = False return item client = get_client() torrents = client.torrents_info(torrent_hashes=task_id) if not torrents: return None return serialize_torrent(torrents[0], state.get("torrents", {}).get(task_id)) def all_task_snapshots(limit: int = 8) -> list[dict]: state = load_monitor_state() client = get_client() raw_torrents = list(client.torrents_info(sort="added_on", reverse=True)) torrent_items = [ serialize_torrent(torrent, state.get("torrents", {}).get(torrent.hash)) for torrent in raw_torrents ] rclone_available = is_rclone_upload_available() aria2_items = [] for task in state.get("aria2", {}).values(): item = aria2.serialize_task(task) item["can_rclone_upload"] = bool(item.get("can_gofile_upload")) item["rclone_config_ready"] = rclone_available item["can_raw_rclone_upload"] = False aria2_items.append(item) items = sorted(torrent_items + aria2_items, key=lambda item: int(item.get("added_at", 0) or 0), reverse=True) return items[:limit] def add_magnet_task(magnet: str) -> tuple[str, str]: is_valid, value = validate_magnet_link(magnet) if not is_valid: raise ValueError(value) client = get_client() before = {torrent.hash for torrent in client.torrents_info()} client.torrents_add(urls=value, savepath=DOWNLOAD_PATH) btih = extract_btih(value) hash_candidates = [] if re.fullmatch(r"[A-Fa-f0-9]{40}", btih or ""): hash_candidates = [btih.lower(), btih.upper()] deadline = time.time() + 20 while time.time() < deadline: torrents = list(client.torrents_info(sort="added_on", reverse=True)) by_hash = {torrent.hash: torrent for torrent in torrents} for candidate in hash_candidates: if candidate in by_hash: return candidate, by_hash[candidate].name new_hashes = [torrent.hash for torrent in torrents if torrent.hash not in before] if new_hashes: newest = by_hash[new_hashes[0]] return newest.hash, newest.name time.sleep(1) raise RuntimeError("Magnet ditambahkan, tetapi task belum muncul dari qBittorrent.") def add_aria2_task(url: str) -> tuple[str, str]: is_valid, value = aria2.validate_download_url(url) if not is_valid: raise ValueError(value) return aria2.start_download(value, DOWNLOAD_PATH, STATE_FILE, STATE_LOCK) def set_upload_state(task_id: str, provider: str, endpoint: str = "") -> dict: state = load_monitor_state() entry = get_task_state_entry(state, task_id) if entry.get("gofile_uploading"): raise RuntimeError("Upload file eksternal masih berjalan.") entry["gofile_uploading"] = True entry["gofile_progress"] = 0 entry["gofile_speed"] = "" entry["gofile_eta_seconds"] = 0 entry["gofile_cancel_requested"] = False entry["gofile_pid"] = 0 entry["gofile_endpoint"] = endpoint entry["gofile_provider"] = provider entry["gofile_status"] = f"Sedang upload ke {provider}..." entry["status_message"] = "" save_monitor_state(state) return entry def start_remote_upload(task_id: str, provider: str, mode: str = "zip") -> str: if provider not in {"gofile", "pixeldrain", "rclone"}: raise ValueError("Provider upload tidak valid.") if mode not in {"zip", "raw"}: raise ValueError("Mode upload tidak valid.") provider_name = {"gofile": "GoFile", "pixeldrain": "PixelDrain", "rclone": "rclone"}[provider] if provider == "pixeldrain" and not PIXELDRAIN_API_KEY: raise RuntimeError("PIXELDRAIN_API_KEY belum diset.") if provider == "rclone" and not is_rclone_upload_available(): raise RuntimeError("rclone.conf belum tersedia atau tidak valid. Set RCLONE_CONFIG_URL dari env atau dashboard web.") if is_aria2_task(task_id): state = load_monitor_state() entry = state.get("aria2", {}).get(task_id) if not entry: raise RuntimeError("Tugas Aria2 tidak ditemukan.") file_path = Path(entry.get("file_path", "") or "") if not file_path.exists(): raise RuntimeError("File Aria2 tidak ditemukan di storage.") set_upload_state(task_id, provider_name, "pixeldrain" if provider == "pixeldrain" else rclone_remote_label() if provider == "rclone" else "") if provider == "gofile": start_gofile_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip") elif provider == "pixeldrain": start_pixeldrain_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip") else: start_rclone_upload_background(task_id, entry.get("name", file_path.name), file_path, mode="zip") return f"Upload Aria2 ke {provider_name} dimulai." client = get_client() torrents = client.torrents_info(torrent_hashes=task_id) if not torrents: raise RuntimeError("Torrent tidak ditemukan.") torrent = torrents[0] if float(getattr(torrent, "progress", 0) or 0) < 1: raise RuntimeError("Upload hanya tersedia setelah download selesai.") content_path = Path(getattr(torrent, "content_path", "") or "") if not content_path.exists(): raise RuntimeError("File hasil download tidak ditemukan di storage.") if mode == "raw" and not content_path.is_dir(): raise RuntimeError("Mode raw hanya tersedia untuk folder.") state = load_monitor_state() entry = get_task_state_entry(state, task_id) if entry.get("gofile_uploading"): raise RuntimeError("Upload file eksternal masih berjalan.") entry["gofile_uploading"] = True entry["gofile_progress"] = 0 entry["gofile_speed"] = "" entry["gofile_eta_seconds"] = 0 entry["gofile_cancel_requested"] = False entry["gofile_pid"] = 0 entry["gofile_endpoint"] = "pixeldrain" if provider == "pixeldrain" else rclone_remote_label() if provider == "rclone" else "" entry["gofile_provider"] = provider_name entry["gofile_status"] = f"Sedang upload ke {provider_name}..." entry["pre_upload_state"] = getattr(torrent, "state", "") or "" entry["pre_upload_force_start"] = bool(getattr(torrent, "force_start", False)) entry["status_message"] = "" save_monitor_state(state) if provider == "gofile": start_gofile_upload_background(task_id, torrent.name, content_path, mode=mode) elif provider == "pixeldrain": start_pixeldrain_upload_background(task_id, torrent.name, content_path, mode=mode) else: start_rclone_upload_background(task_id, torrent.name, content_path, mode=mode) return f"Upload ke {provider_name} dimulai." def pause_task(task_id: str) -> str: if is_aria2_task(task_id): ok, message = aria2.pause_task(task_id, STATE_FILE, STATE_LOCK) if not ok: raise RuntimeError(message) return message client = get_client() client.torrents_pause(torrent_hashes=task_id) return "Torrent dijeda." def resume_task(task_id: str) -> str: if is_aria2_task(task_id): ok, message = aria2.resume_task(task_id, STATE_FILE, STATE_LOCK) if not ok: raise RuntimeError(message) return message client = get_client() client.torrents_resume(torrent_hashes=task_id) return "Torrent dilanjutkan." def delete_task(task_id: str, delete_files: bool = False) -> str: if is_aria2_task(task_id): ok, message = aria2.delete_task(task_id, STATE_FILE, STATE_LOCK, delete_files) if not ok: raise RuntimeError(message) return message client = get_client() client.torrents_delete(delete_files=delete_files, torrent_hashes=task_id) state = load_monitor_state() state.setdefault("torrents", {}).pop(task_id, None) save_monitor_state(state) return "Torrent dan file hasil download dihapus." if delete_files else "Torrent dihapus dari daftar." def format_task_status(task: dict) -> str: progress = int(task.get("progress", 0) or 0) lines = [ f"Task: {task.get('name') or '-'}", f"ID: {task.get('hash') or '-'}", f"Type: {task.get('task_kind') or 'torrent'}", f"Status: {task.get('state_label') or '-'}", f"Progress: {progress_bar(progress)} {progress}%", f"Size: {task.get('downloaded') or '-'} / {task.get('total_size') or '-'}", f"Speed: Down {task.get('dlspeed') or '-'} | Up {task.get('upspeed') or '-'}", f"ETA: {task.get('eta') or '-'}", ] if task.get("gofile_uploading"): lines.extend( [ "", f"Remote: {task.get('upload_provider') or '-'}", f"Upload status: {task.get('gofile_status') or '-'}", f"Upload speed: {task.get('gofile_speed') or '-'}", f"Upload ETA: {task.get('gofile_eta') or '-'}", ] ) if task.get("gofile_link"): lines.extend(["", f"Remote link: {task.get('gofile_link')}"]) if task.get("status_message"): lines.extend(["", f"Info: {task.get('status_message')}"]) return "\n".join(lines) def task_keyboard(task: dict | None) -> InlineKeyboardMarkup | None: if not task: return None task_id = task.get("hash", "") rows = [] if task.get("can_pause"): rows.append([InlineKeyboardButton("Pause", callback_data=f"pause:{task_id}")]) if task.get("can_resume"): rows.append([InlineKeyboardButton("Resume", callback_data=f"resume:{task_id}")]) if task.get("can_gofile_upload") or task.get("can_pixeldrain_upload") or task.get("can_rclone_upload"): upload_row = [] if task.get("can_gofile_upload"): upload_row.append(InlineKeyboardButton("GoFile", callback_data=f"upload:gofile:zip:{task_id}")) if task.get("can_pixeldrain_upload"): upload_row.append(InlineKeyboardButton("PixelDrain", callback_data=f"upload:pixeldrain:zip:{task_id}")) if task.get("can_rclone_upload"): upload_row.append(InlineKeyboardButton("rclone", callback_data=f"upload:rclone:zip:{task_id}")) rows.append(upload_row) if task.get("can_raw_gofile_upload") or task.get("can_raw_pixeldrain_upload") or task.get("can_raw_rclone_upload"): raw_row = [] if task.get("can_raw_gofile_upload"): raw_row.append(InlineKeyboardButton("GoFile Raw", callback_data=f"upload:gofile:raw:{task_id}")) if task.get("can_raw_pixeldrain_upload"): raw_row.append(InlineKeyboardButton("Pixel Raw", callback_data=f"upload:pixeldrain:raw:{task_id}")) if task.get("can_raw_rclone_upload"): raw_row.append(InlineKeyboardButton("rclone Raw", callback_data=f"upload:rclone:raw:{task_id}")) rows.append(raw_row) rows.append( [ InlineKeyboardButton("Refresh", callback_data=f"refresh:{task_id}"), InlineKeyboardButton("Delete", callback_data=f"delete:{task_id}"), InlineKeyboardButton("Delete Files", callback_data=f"delete_files:{task_id}"), ] ) return InlineKeyboardMarkup(rows) def should_stop_monitoring(task: dict | None) -> bool: if not task: return True if task.get("gofile_uploading"): return False state = str(task.get("state") or "") progress = int(task.get("progress", 0) or 0) return progress >= 100 or state in {"complete", "error", "cancelled"} async def safe_edit(message: Message, text: str, reply_markup=None) -> None: try: await message.edit_text(text, reply_markup=reply_markup, disable_web_page_preview=True) except MessageNotModified: return except FloodWait as exc: await asyncio.sleep(int(exc.value) + 1) async def monitor_task_message(message: Message, task_id: str) -> None: started = time.time() while True: try: task = await asyncio.to_thread(task_snapshot, task_id) text = format_task_status(task) if task else "Task tidak ditemukan atau sudah dihapus." await safe_edit(message, text, reply_markup=task_keyboard(task)) if should_stop_monitoring(task): return except Exception as exc: await safe_edit(message, f"Gagal membaca status task: {exc}") return if time.time() - started > PROGRESS_TIMEOUT_SECONDS: return await asyncio.sleep(PROGRESS_INTERVAL_SECONDS) async def require_access(message: Message) -> bool: if is_authorized(message): return True await message.reply_text("Akses ditolak.") return False @bot.on_message(filters.command(["start", "help"])) async def help_command(_, message: Message): if not await require_access(message): return await message.reply_text( "\n".join( [ "Torrent Web Bot siap.", "", "Command:", "/qm - tambah magnet link", "/qbdown - alias tambah magnet link", "/aria2 - direct download via Aria2", "/tasks - lihat task terbaru", "/status - pantau task tertentu", ] ) ) @bot.on_message(filters.command(["qm", "qbdown"])) async def magnet_command(_, message: Message): if not await require_access(message): return magnet = command_argument(message) if not magnet: await message.reply_text("Format: /qm magnet:?xt=urn:btih:...") return status_message = await message.reply_text("Menambahkan magnet ke qBittorrent...") try: task_id, name = await asyncio.to_thread(add_magnet_task, magnet) await safe_edit(status_message, f"Magnet ditambahkan: {name}\nMenunggu status download...") await monitor_task_message(status_message, task_id) except Exception as exc: await safe_edit(status_message, f"Gagal menambahkan magnet: {exc}") @bot.on_message(filters.command(["aria2", "direct"])) async def aria2_command(_, message: Message): if not await require_access(message): return url = command_argument(message) if not url: await message.reply_text("Format: /aria2 https://example.com/file.iso") return status_message = await message.reply_text("Memulai Aria2 download...") try: task_id, filename = await asyncio.to_thread(add_aria2_task, url) await safe_edit(status_message, f"Aria2 download dimulai: {filename}") await monitor_task_message(status_message, task_id) except Exception as exc: await safe_edit(status_message, f"Gagal memulai Aria2: {exc}") @bot.on_message(filters.command("tasks")) async def tasks_command(_, message: Message): if not await require_access(message): return try: tasks = await asyncio.to_thread(all_task_snapshots) except Exception as exc: await message.reply_text(f"Gagal membaca task: {exc}") return if not tasks: await message.reply_text("Belum ada task aktif.") return lines = ["Task terbaru:"] for task in tasks: lines.append(f"- {task.get('hash')}: {task.get('name')} ({task.get('progress')}%, {task.get('state_label')})") await message.reply_text("\n".join(lines)) @bot.on_message(filters.command("status")) async def status_command(_, message: Message): if not await require_access(message): return task_id = command_argument(message) if not task_id: await message.reply_text("Format: /status ") return reply = await message.reply_text("Membaca status task...") await monitor_task_message(reply, task_id) @bot.on_callback_query() async def callback_handler(_, query: CallbackQuery): if not is_authorized(query): await query.answer("Akses ditolak.", show_alert=True) return data = query.data or "" try: if data.startswith("upload:"): _, provider, mode, task_id = data.split(":", 3) message = await asyncio.to_thread(start_remote_upload, task_id, provider, mode) await query.answer(message) await monitor_task_message(query.message, task_id) return if data.startswith("pause:"): task_id = data.split(":", 1)[1] await query.answer(await asyncio.to_thread(pause_task, task_id)) await monitor_task_message(query.message, task_id) return if data.startswith("resume:"): task_id = data.split(":", 1)[1] await query.answer(await asyncio.to_thread(resume_task, task_id)) await monitor_task_message(query.message, task_id) return if data.startswith("delete_files:"): task_id = data.split(":", 1)[1] message = await asyncio.to_thread(delete_task, task_id, True) await query.answer(message) await safe_edit(query.message, message) return if data.startswith("delete:"): task_id = data.split(":", 1)[1] message = await asyncio.to_thread(delete_task, task_id, False) await query.answer(message) await safe_edit(query.message, message) return if data.startswith("refresh:"): task_id = data.split(":", 1)[1] task = await asyncio.to_thread(task_snapshot, task_id) await query.answer("Status diperbarui.") await safe_edit(query.message, format_task_status(task) if task else "Task tidak ditemukan.", task_keyboard(task)) return await query.answer("Aksi tidak dikenal.", show_alert=True) except Exception as exc: await query.answer(str(exc)[:200], show_alert=True) def main() -> None: missing = [] if not API_ID: missing.append("TELEGRAM_API_ID") if not API_HASH: missing.append("TELEGRAM_API_HASH") if not BOT_TOKEN: missing.append("TELEGRAM_BOT_TOKEN") if missing: raise RuntimeError(f"Env Telegram belum lengkap: {', '.join(missing)}") print("Starting Telegram bot...", flush=True) print(f"OWNER_IDS={OWNER_IDS}", flush=True) bot.run() if __name__ == "__main__": main()