""" plugins/extra_admin.py — Comandos administrativos extra. Comandos: .join <enlace> — Unirse a un canal/grupo via enlace .leave [chat_id] — Abandonar un chat (default: chat actual) .chatinfo [chat_id] — Info detallada del chat .server — CPU, RAM, disco + speedtest .clear — Limpia el directorio temp/downloads .dlmusic <url> — Descarga música de Spotify (requiere spotdl) .stopdl — Cancela la descarga de música en curso """ import asyncio import os import shutil from pathlib import Path import aiohttp from pyrogram import filters from pyrogram.errors import RPCError from pyrogram.types import Message from bot import app from config import Config P = Config.CMD_PREFIX # Tarea de descarga activa _dl_task: asyncio.Task | None = None async def _tmp(client, chat_id: int, text: str, delay: int = 8): m = await client.send_message(chat_id, text) await asyncio.sleep(delay) await m.delete() # ── .join ───────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("join", prefixes=P)) async def cmd_join(client, msg: Message): await msg.delete() args = msg.text.split(None, 1) if len(args) < 2: await _tmp(client, msg.chat.id, f"❓ **Uso:** `{P}join <enlace>`\nEj: `{P}join https://t.me/+ABC123`") return link = args[1].strip() status = await client.send_message(msg.chat.id, f"🔗 Uniéndome a `{link}`...") try: chat = await client.join_chat(link) await status.edit( f"✅ **¡Unido!**\n\n" f"📌 **Nombre:** {chat.title}\n" f"🆔 **ID:** `{chat.id}`\n" f"📂 **Tipo:** `{chat.type}`" ) except Exception as e: await status.edit(f"❌ **Error al unirse:** `{e}`") await asyncio.sleep(8) await status.delete() # ── .leave ──────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("leave", prefixes=P)) async def cmd_leave(client, msg: Message): await msg.delete() args = msg.text.split(None, 1) chat_id = int(args[1].strip()) if len(args) > 1 else msg.chat.id try: await client.leave_chat(chat_id) await _tmp(client, msg.chat.id, f"👋 **Abandonado el chat** `{chat_id}`.") except Exception as e: await _tmp(client, msg.chat.id, f"❌ `{e}`") # ── .chatinfo ───────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("chatinfo", prefixes=P)) async def cmd_chatinfo(client, msg: Message): await msg.delete() args = msg.text.split(None, 1) chat_id = int(args[1].strip()) if len(args) > 1 else msg.chat.id try: chat = await client.get_chat(chat_id) members = getattr(chat, "members_count", "?") desc = getattr(chat, "description", "") or "" uname = f"@{chat.username}" if getattr(chat, "username", None) else "sin username" text = ( f"💬 **Información del chat**\n\n" f"📌 **Nombre:** {chat.title or 'N/A'}\n" f"🆔 **ID:** `{chat.id}`\n" f"📂 **Tipo:** `{chat.type}`\n" f"🔗 **Username:** {uname}\n" f"👥 **Miembros:** `{members}`\n" ) if desc: text += f"\n📝 **Descripción:**\n_{desc[:300]}_" m = await client.send_message(msg.chat.id, text) await asyncio.sleep(12) await m.delete() except Exception as e: await _tmp(client, msg.chat.id, f"❌ `{e}`") # ── .server ─────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("server", prefixes=P)) async def cmd_server(client, msg: Message): await msg.delete() def bar(pct): filled = round(pct / 100 * 8) return "█" * filled + "░" * (8 - filled) # --- Info básica --- try: import psutil cpu = psutil.cpu_percent(interval=0.5) cores = psutil.cpu_count() ram = psutil.virtual_memory() disk = psutil.disk_usage("/") sysinfo = ( f"**🖥️ Servidor**\n\n" f"⚙️ **CPU:** `{cpu:.1f}%` `{bar(cpu)}` `{cores} núcleos`\n" f"🧠 **RAM:** `{ram.percent:.1f}%` `{bar(ram.percent)}`\n" f" └ `{ram.used/1024**3:.1f}` / `{ram.total/1024**3:.1f} GB`\n" f"💾 **Disco:** `{disk.percent:.1f}%` `{bar(disk.percent)}`\n" f" └ `{disk.used/1024**3:.1f}` / `{disk.total/1024**3:.1f} GB`\n\n" f"⚡ **Speedtest:** ejecutando..." ) except ImportError: import platform sysinfo = ( f"🐍 Python `{platform.python_version()}` | " f"🐧 `{platform.system()} {platform.release()}`\n\n" f"⚡ **Speedtest:** ejecutando..." ) status = await client.send_message(msg.chat.id, sysinfo) # --- Speedtest --- try: import speedtest as st_lib loop = asyncio.get_event_loop() def _run_speedtest(): s = st_lib.Speedtest() s.get_best_server() down = s.download() up = s.upload() srv = s.results.server return down, up, srv down, up, srv = await loop.run_in_executor(None, _run_speedtest) server_name = srv.get("sponsor", "?") if srv else "?" country = srv.get("country", "?") if srv else "?" speed_text = ( f"\n📥 **Bajada:** `{down/1e6:.1f} Mbps`\n" f"📤 **Subida:** `{up/1e6:.1f} Mbps`\n" f"🌍 **Servidor:** `{server_name}` ({country})" ) await status.edit(sysinfo.replace("⚡ **Speedtest:** ejecutando...", "⚡ **Speedtest:**" + speed_text)) except Exception as e: await status.edit(sysinfo.replace("ejecutando...", f"error: `{e}`")) await asyncio.sleep(60) await status.delete() # ── .clear ──────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("clear", prefixes=P)) async def cmd_clear(client, msg: Message): await msg.delete() count = 0 for d in ("temp", "downloads"): p = Path(d) if p.exists(): for f in p.iterdir(): try: if f.is_file(): f.unlink(); count += 1 elif f.is_dir(): shutil.rmtree(f); count += 1 except Exception: pass await _tmp(client, msg.chat.id, f"🗑️ **{count}** archivo(s) eliminados de temp/downloads.") # ── .dlmusic ────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("dlmusic", prefixes=P)) async def cmd_dlmusic(client, msg: Message): global _dl_task await msg.delete() args = msg.text.split(None, 1) if len(args) < 2: await _tmp(client, msg.chat.id, f"❓ **Uso:** `{P}dlmusic `\n" "Acepta: canción, playlist, álbum, artista") return url = args[1].strip() status = await client.send_message(msg.chat.id, f"🎵 **Iniciando descarga de Spotify...**\n`{url}`") try: from spotdl import Spotdl from spotdl.utils.spotify import SpotifyClient cid = Config.SPOTIFY_CLIENT_ID cs = Config.SPOTIFY_CLIENT_SECRET if not cid or not cs: await status.edit( "❌ **SPOTIFY_CLIENT_ID** y **SPOTIFY_CLIENT_SECRET** no configurados.\n" "Crea tu app en developer.spotify.com/dashboard" ) return out_dir = Path("downloads/spotify") out_dir.mkdir(parents=True, exist_ok=True) async def _download(): loop = asyncio.get_event_loop() def _sync(): spot = Spotdl(client_id=cid, client_secret=cs, downloader_settings={"output": str(out_dir)}) songs = spot.search([url]) results = spot.download_songs(songs) return results return await loop.run_in_executor(None, _sync) _dl_task = asyncio.create_task(_download()) await status.edit("⬇️ **Descargando...** usa `.stopdl` para cancelar.") results = await _dl_task _dl_task = None sent = 0 for song, path in results: if path: await client.send_audio( msg.chat.id, str(path), title=getattr(song, "name", None), performer=", ".join(getattr(song, "artists", [])), ) sent += 1 await status.edit(f"✅ **{sent}** canción(es) descargadas y enviadas.") await asyncio.sleep(6) await status.delete() except asyncio.CancelledError: await status.edit("⛔ **Descarga cancelada.**") await asyncio.sleep(5) await status.delete() except ImportError: await status.edit( "❌ **spotdl** no instalado.\n" "Añade `spotdl` a requirements.txt." ) except Exception as e: await status.edit(f"❌ **Error:** `{e}`") await asyncio.sleep(8) await status.delete() # ── .stopdl ─────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("stopdl", prefixes=P)) async def cmd_stopdl(client, msg: Message): global _dl_task await msg.delete() if _dl_task and not _dl_task.done(): _dl_task.cancel() await _tmp(client, msg.chat.id, "⛔ **Descarga de música cancelada.**") else: await _tmp(client, msg.chat.id, "ℹ️ No hay ninguna descarga activa.")