Spaces:
Paused
Paused
File size: 11,792 Bytes
5321464 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | """
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}`")
|