userbotsaskeds / plugins /extra_admin.py
saske560's picture
Upload 18 files
5321464 verified
Raw History Blame Contribute Delete
10.9 kB
"""
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 &lt;enlace&gt;`\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 <url_spotify>`\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.")