""" plugins/dl_mega.py — Descargador de Mega.nz. Descarga archivos de mega.nz/file/... o mega.nz/folder/... y los sube a Telegram detectando automáticamente el tipo (video, audio, imagen, documento). Comandos: .mega <url> — Descarga archivo de Mega.nz .mcancel — Cancela descarga activa en este chat Requiere: pip install mega.py pycryptodome """ import asyncio import os import re import time from pathlib import Path import requests from pyrogram import filters from pyrogram.types import Message from bot import app from config import Config P = Config.CMD_PREFIX DL_DIR = Path("downloads"); DL_DIR.mkdir(exist_ok=True) _active: dict = {} VIDEO_EXT = {".mp4", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".webm"} AUDIO_EXT = {".mp3", ".m4a", ".wav", ".flac", ".aac", ".ogg"} PHOTO_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"} # ── Helpers ─────────────────────────────────────────────────────────────────── def _format_size(b: int) -> str: for u in ("B", "KB", "MB", "GB"): if b < 1024: return f"{b:.1f} {u}" b /= 1024 return f"{b:.1f} TB" def _extract_url(text: str) -> str | None: for pat in [r"https?://mega\.nz/file/[^\s]+", r"https?://mega\.nz/folder/[^\s]+"]: found = re.findall(pat, text) if found: return found[0] return None def _thumb(path: str) -> str | None: try: import subprocess out = path + ".jpg" subprocess.run(["ffmpeg", "-y", "-i", path, "-ss", "00:00:01", "-vframes", "1", out], capture_output=True, timeout=15) return out if Path(out).exists() else None except Exception: return None # ── .mega ───────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("mega", prefixes=P)) async def cmd_mega(client, msg: Message): await msg.delete() args = msg.text.split(None, 1) text = "" if len(args) > 1: text = args[1].strip() elif msg.reply_to_message: text = msg.reply_to_message.text or msg.reply_to_message.caption or "" url = _extract_url(text) if not url: m = await client.send_message(msg.chat.id, f"❓ **Uso:** `{P}mega `\n" f"Soporta: `mega.nz/file/...` y `mega.nz/folder/...`") await asyncio.sleep(8); await m.delete(); return chat_id = msg.chat.id if chat_id in _active and not _active[chat_id].get("cancelled"): m = await client.send_message(msg.chat.id, f"⚠️ Descarga activa. Usa `{P}mcancel` para cancelar.") await asyncio.sleep(8); await m.delete(); return status = await client.send_message(msg.chat.id, "🔗 **Procesando enlace de Mega...**") ev = asyncio.Event() _active[chat_id] = {"cancelled": False, "cancel_event": ev} async def _run(): try: await _process(client, msg, url, status, ev) except Exception as e: try: await status.edit(f"❌ `{e}`") except Exception: pass finally: _active.pop(chat_id, None) _active[chat_id]["task"] = asyncio.create_task(_run()) async def _process(client, msg: Message, url: str, status, ev: asyncio.Event): if ev.is_set(): await status.edit("❌ Cancelada."); await asyncio.sleep(5); await status.delete(); return await status.edit("🔍 **Obteniendo información del archivo...**") try: import mega as mega_lib except ImportError: await status.edit("❌ **mega.py** no instalado.\nAñade `mega.py` a requirements.txt.") await asyncio.sleep(8); await status.delete(); return try: m = mega_lib.Mega() m.login_anonymous() file_info = m.get_public_url_info(url) except Exception as e: await status.edit(f"❌ Error obteniendo info de Mega: `{e}`") await asyncio.sleep(8); await status.delete(); return if not file_info: await status.edit("❌ No se pudo obtener información del archivo.") await asyncio.sleep(8); await status.delete(); return filename = file_info.get("name", "mega_file") filesize = file_info.get("size", 0) await status.edit( f"📄 **Archivo encontrado:**\n" f"**Nombre:** `{filename}`\n" f"**Tamaño:** `{_format_size(filesize)}`\n\n" f"⬇️ **Descargando...**" ) if ev.is_set(): await status.edit("❌ Cancelada."); await asyncio.sleep(5); await status.delete(); return loop = asyncio.get_event_loop() safe_name = "".join(c for c in filename if c.isalnum() or c in "._- ") dest_path = str(DL_DIR / safe_name) try: def _dl(): m.download_url(url, dest_path=str(DL_DIR), dest_filename=safe_name) await loop.run_in_executor(None, _dl) except Exception as e: await status.edit(f"❌ Error descargando: `{e}`") await asyncio.sleep(8); await status.delete(); return if not Path(dest_path).exists(): await status.edit("❌ El archivo no se descargó correctamente.") await asyncio.sleep(8); await status.delete(); return await status.edit("📤 **Subiendo a Telegram...**") ext = Path(filename).suffix.lower() stem = Path(filename).stem try: if ext in VIDEO_EXT: thumb = _thumb(dest_path) await client.send_video( msg.chat.id, dest_path, caption=f"`{stem}`", thumb=thumb, ) if thumb: Path(thumb).unlink(missing_ok=True) elif ext in AUDIO_EXT: await client.send_audio(msg.chat.id, dest_path, caption=f"`{stem}`") elif ext in PHOTO_EXT: await client.send_photo(msg.chat.id, dest_path, caption=f"`{stem}`") else: await client.send_document(msg.chat.id, dest_path, caption=f"`{stem}`") except Exception as e: await client.send_message(msg.chat.id, f"❌ Error al subir: `{e}`") Path(dest_path).unlink(missing_ok=True) await status.delete() m2 = await client.send_message(msg.chat.id, f"✅ **Descargado:** `{filename}`") await asyncio.sleep(5); await m2.delete() # ── .mcancel ────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("mcancel", prefixes=P)) async def cmd_mcancel(client, msg: Message): await msg.delete() chat_id = msg.chat.id entry = _active.get(chat_id) if entry and not entry.get("cancelled"): entry["cancelled"] = True ev = entry.get("cancel_event") if ev: ev.set() t = entry.get("task") if t and not t.done(): t.cancel() m = await client.send_message(chat_id, "⛔ **Descarga de Mega cancelada.**") else: m = await client.send_message(chat_id, "ℹ️ No hay descarga activa de Mega.") await asyncio.sleep(6); await m.delete()