""" plugins/tools.py — Herramientas varias. Comandos: .tr <lang> [texto] — Traduce texto o mensaje respondido .tts <lang> <texto> — Texto a voz (usa gTTS) .paste — Sube texto a paste.rs y devuelve URL .eval <código> — Evalúa Python (solo owner) .sh <comando> — Ejecuta comando de shell (solo owner) .time [zona] — Hora actual (UTC por defecto) .calc <expr> — Calculadora segura .ascii <texto> — Texto en arte ASCII (pyfiglet) .weather <ciudad> — Clima básico via wttr.in """ import asyncio import io import os import sys import time import traceback from contextlib import redirect_stdout from datetime import datetime, timezone import aiohttp from pyrogram import filters from pyrogram.types import Message from bot import app from config import Config from utils.helpers import run_cmd P = Config.CMD_PREFIX async def _respond(client, chat_id: int, text: str, delay: int = 8): m = await client.send_message(chat_id, text) await asyncio.sleep(delay) await m.delete() # ── .tr ─────────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("tr", prefixes=P)) async def cmd_tr(client, msg: Message): args = msg.text.split(None, 2) await msg.delete() if len(args) < 2: await _respond(client, msg.chat.id, f"❓ Uso: `{P}tr [texto]`\nEj: `.tr es Hello world`") return dest_lang = args[1].lower() if len(args) >= 3: text_to_tr = args[2] elif msg.reply_to_message: text_to_tr = msg.reply_to_message.text or msg.reply_to_message.caption or "" else: await _respond(client, msg.chat.id, "❓ Proporciona texto o responde a un mensaje.") return if not text_to_tr.strip(): await _respond(client, msg.chat.id, "❌ Texto vacío."); return status = await client.send_message(msg.chat.id, "🌐 Traduciendo...") try: from deep_translator import GoogleTranslator translated = GoogleTranslator(source="auto", target=dest_lang).translate(text_to_tr) await status.edit( f"🌐 **Traducción** → `{dest_lang}`\n\n" f"**Original:** {text_to_tr[:300]}\n\n" f"**Traducido:** {translated}" ) except ImportError: # Fallback: Google Translate via web try: url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl={dest_lang}&dt=t&q={aiohttp.helpers.requote_uri(text_to_tr)}" async with aiohttp.ClientSession() as session: async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as r: data = await r.json() result = "".join(item[0] for item in data[0] if item[0]) await status.edit(f"🌐 **→ {dest_lang}**\n\n{result}") except Exception as e: await status.edit(f"❌ Error al traducir: `{e}`\n\n_Instala `deep-translator` para mejor soporte._") except Exception as e: await status.edit(f"❌ `{e}`") # ── .tts ────────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("tts", prefixes=P)) async def cmd_tts(client, msg: Message): args = msg.text.split(None, 2) await msg.delete() if len(args) < 3 and not msg.reply_to_message: await _respond(client, msg.chat.id, f"❓ Uso: `{P}tts <lang> <texto>`") return lang = args[1] if len(args) >= 2 else "es" if len(args) >= 3: text = args[2] elif msg.reply_to_message: text = msg.reply_to_message.text or msg.reply_to_message.caption or "" lang = args[1] if len(args) >= 2 else "es" else: await _respond(client, msg.chat.id, "❌ Texto vacío."); return status = await client.send_message(msg.chat.id, "🎙️ Generando voz...") try: from gtts import gTTS tts = gTTS(text=text, lang=lang) audio_path = f"temp/tts_{msg.id}.mp3" os.makedirs("temp", exist_ok=True) tts.save(audio_path) await status.delete() await client.send_voice(msg.chat.id, audio_path, caption=f"🎙️ TTS `{lang}`") os.remove(audio_path) except ImportError: await status.edit("❌ Instala `gTTS`: `pip install gTTS`") except Exception as e: await status.edit(f"❌ `{e}`") # ── .paste ──────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("paste", prefixes=P)) async def cmd_paste(client, msg: Message): await msg.delete() if msg.reply_to_message: text = msg.reply_to_message.text or msg.reply_to_message.caption or "" else: args = msg.text.split(None, 1) text = args[1] if len(args) > 1 else "" if not text.strip(): await _respond(client, msg.chat.id, "❌ No hay texto que subir."); return status = await client.send_message(msg.chat.id, "📤 Subiendo a paste.rs...") try: async with aiohttp.ClientSession() as session: async with session.post( "https://paste.rs", data=text.encode(), timeout=aiohttp.ClientTimeout(total=10) ) as r: url = (await r.text()).strip() await status.edit(f"📋 **Paste creado:**\n{url}") except Exception as e: await status.edit(f"❌ `{e}`") # ── .eval ───────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("eval", prefixes=P)) async def cmd_eval(client, msg: Message): args = msg.text.split(None, 1) if len(args) < 2: await msg.delete(); return code = args[1].strip().strip("`") # strip ```python or ``` fences if code.startswith("python"): code = code[6:].strip() status = await msg.edit(f"⚙️ Evaluando...\n```\n{code}\n```") t0 = time.time() stdout_buf = io.StringIO() result = None error = None try: # Try expression first try: result = eval(compile(code, "", "eval"), {"client": client, "msg": msg, "app": app}) if asyncio.iscoroutine(result): result = await result except SyntaxError: # Fall back to exec (multi-line) with redirect_stdout(stdout_buf): exec_globals = {"client": client, "msg": msg, "app": app, "asyncio": asyncio} exec(compile(code, "", "exec"), exec_globals) result = stdout_buf.getvalue() except Exception: error = traceback.format_exc() elapsed = (time.time() - t0) * 1000 out = str(result) if result is not None else (stdout_buf.getvalue() or "") out = out[:1500] or "(sin salida)" if error: text = ( f"❌ **Error** en `{elapsed:.1f} ms`\n\n" f"**Input:**\n```python\n{code[:300]}\n```\n\n" f"**Traceback:**\n```\n{error[:800]}\n```" ) else: text = ( f"✅ **Eval** en `{elapsed:.1f} ms`\n\n" f"**Input:**\n```python\n{code[:300]}\n```\n\n" f"**Output:**\n```\n{out}\n```" ) await status.edit(text) # ── .sh ─────────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("sh", prefixes=P)) async def cmd_sh(client, msg: Message): args = msg.text.split(None, 1) if len(args) < 2: await msg.delete(); return cmd = args[1] status = await msg.edit(f"💻 Ejecutando...\n```sh\n{cmd}\n```") t0 = time.time() try: out = await asyncio.wait_for(run_cmd(cmd), timeout=30) except asyncio.TimeoutError: out = "❌ Tiempo agotado (30s)" elapsed = (time.time() - t0) * 1000 out = out[:2000] or "(sin salida)" await status.edit( f"💻 **Shell** `{elapsed:.0f} ms`\n\n" f"```sh\n{cmd}\n```\n\n" f"```\n{out}\n```" ) # ── .time ───────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("time", prefixes=P)) async def cmd_time(client, msg: Message): await msg.delete() args = msg.text.split(None, 1) tz_name = args[1].strip() if len(args) > 1 else "UTC" try: import zoneinfo tz = zoneinfo.ZoneInfo(tz_name) now = datetime.now(tz) label = tz_name except Exception: now = datetime.now(timezone.utc) label = "UTC" note = await client.send_message( msg.chat.id, f"🕐 **{label}:** `{now.strftime('%Y-%m-%d %H:%M:%S')}`" ) await asyncio.sleep(8) await note.delete() # ── .calc ───────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("calc", prefixes=P)) async def cmd_calc(client, msg: Message): args = msg.text.split(None, 1) await msg.delete() if len(args) < 2: await _respond(client, msg.chat.id, f"❓ Uso: `{P}calc 2+2*3`"); return expr = args[1].strip() try: # Safe eval: only allow math operations allowed = set("0123456789+-*/%()., **e ") if not all(c in allowed for c in expr.lower()): raise ValueError("Caracteres no permitidos") result = eval(expr, {"__builtins__": {}}) note = await client.send_message( msg.chat.id, f"🧮 `{expr}` = **{result}**" ) except Exception as e: note = await client.send_message(msg.chat.id, f"❌ `{e}`") await asyncio.sleep(8) await note.delete() # ── .weather ────────────────────────────────────────────────────────────────── @app.on_message(filters.me & filters.command("weather", prefixes=P)) async def cmd_weather(client, msg: Message): args = msg.text.split(None, 1) await msg.delete() if len(args) < 2: await _respond(client, msg.chat.id, f"❓ Uso: `{P}weather <ciudad>`"); return city = args[1].strip().replace(" ", "+") status = await client.send_message(msg.chat.id, "🌤️ Consultando clima...") try: async with aiohttp.ClientSession() as session: url = f"https://wttr.in/{city}?format=4" async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as r: data = await r.text() await status.edit(f"🌤️ **Clima:** `{data.strip()}`") except Exception as e: await status.edit(f"❌ `{e}`")