userbotenma / plugins /tools.py
saske560's picture
Upload 8 files
8506dd7 verified
Raw History Blame Contribute Delete
11.7 kB
"""
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 <idioma> [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>", "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"), 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}`")