import base64
import hashlib
import html
import json
import os
import urllib.parse
import uuid
def safe_eval_math(expr: str):
expr = expr.replace(",", ".").replace("^", "**")
allowed = set("0123456789+-*/%(). **")
if not set(expr) <= allowed:
raise ValueError("Solo se permiten números y operadores básicos.")
code = compile(expr, "", "eval")
if code.co_names:
raise ValueError("La expresión contiene nombres no permitidos.")
return eval(code, {"__builtins__": {}}, {})
def setup(registry):
async def calc_cmd(ctx):
text = await ctx.require_text("Escribe una operación. Ejemplo: .calc (10+5)*2")
if not text:
return
try:
result = safe_eval_math(text)
except Exception as exc:
await ctx.respond(f"❌ No pude calcular eso:\n{html.escape(str(exc))}")
return
await ctx.respond(
"🧮 Calculadora\n\n"
f"📥 Expresión: {html.escape(text)}\n"
f"📤 Resultado: {result}"
)
async def hash_cmd(ctx):
raw = await ctx.require_text("Pásame un texto o responde a un mensaje para generar hashes.")
if not raw:
return
data = raw.encode("utf-8")
await ctx.respond(
"🔐 Hashes\n\n"
f"MD5: {hashlib.md5(data).hexdigest()}\n"
f"SHA1: {hashlib.sha1(data).hexdigest()}\n"
f"SHA256: {hashlib.sha256(data).hexdigest()}"
)
async def b64e_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para codificar en Base64.")
if not raw:
return
encoded = base64.b64encode(raw.encode()).decode()
await ctx.respond(f"🧾 Base64 encode\n\n{encoded}")
async def b64d_cmd(ctx):
raw = await ctx.require_text("Pásame un texto en Base64 para decodificar.")
if not raw:
return
try:
decoded = base64.b64decode(raw.encode()).decode(errors="ignore")
except Exception as exc:
await ctx.respond(f"❌ Base64 inválido: {html.escape(str(exc))}")
return
await ctx.respond(f"📤 Base64 decode\n\n{html.escape(decoded)}")
async def urlencode_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para URL-encode.")
if not raw:
return
await ctx.respond(f"🌐 URL encode\n\n{urllib.parse.quote(raw)}")
async def urldecode_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para URL-decode.")
if not raw:
return
await ctx.respond(f"🌐 URL decode\n\n{html.escape(urllib.parse.unquote(raw))}")
async def reverse_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para darle la vuelta.")
if not raw:
return
await ctx.respond(f"🔁 Texto invertido\n\n{html.escape(raw[::-1])}")
async def upper_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para ponerlo en mayúsculas.")
if not raw:
return
await ctx.respond(f"🔠 Mayúsculas\n\n{html.escape(raw.upper())}")
async def lower_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para ponerlo en minúsculas.")
if not raw:
return
await ctx.respond(f"🔡 Minúsculas\n\n{html.escape(raw.lower())}")
async def title_cmd(ctx):
raw = await ctx.require_text("Pásame un texto para capitalizarlo.")
if not raw:
return
await ctx.respond(f"📝 Capitalizado\n\n{html.escape(raw.title())}")
async def uuid_cmd(ctx):
await ctx.respond(f"🆔 UUID\n\n{uuid.uuid4()}")
async def json_cmd(ctx):
raw = await ctx.require_text("Pásame JSON crudo o responde a un mensaje que lo tenga.")
if not raw:
return
try:
parsed = json.loads(raw)
except Exception as exc:
await ctx.respond(f"❌ JSON inválido: {html.escape(str(exc))}")
return
pretty = json.dumps(parsed, ensure_ascii=False, indent=2)
await ctx.respond(f"🧩 JSON bonito\n\n{html.escape(pretty[:3500])}")
async def pwd_cmd(ctx):
size = 16
if ctx.args.strip().isdigit():
size = max(8, min(64, int(ctx.args.strip())))
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_-"
token = "".join(alphabet[ord(os.urandom(1)) % len(alphabet)] for _ in range(size))
await ctx.respond(f"🔑 Contraseña aleatoria\n\n{token}")
registry.add("calc", calc_cmd, "Calculadora simple segura.", usage=".calc (10+5)*2", category="Herramientas")
registry.add("hash", hash_cmd, "Genera MD5, SHA1 y SHA256.", usage=".hash hola", category="Herramientas")
registry.add("b64e", b64e_cmd, "Codifica texto en Base64.", usage=".b64e hola", category="Herramientas")
registry.add("b64d", b64d_cmd, "Decodifica texto Base64.", usage=".b64d aG9sYQ==", category="Herramientas")
registry.add("urlencode", urlencode_cmd, "Codifica texto para URL.", usage=".urlencode hola mundo", category="Herramientas")
registry.add("urldecode", urldecode_cmd, "Decodifica texto URL.", usage=".urldecode hola%20mundo", aliases=["udecode"], category="Herramientas")
registry.add("reverse", reverse_cmd, "Invierte un texto.", usage=".reverse hola", category="Herramientas")
registry.add("upper", upper_cmd, "Convierte a mayúsculas.", usage=".upper hola", category="Herramientas")
registry.add("lower", lower_cmd, "Convierte a minúsculas.", usage=".lower HOLA", category="Herramientas")
registry.add("title", title_cmd, "Capitaliza un texto.", usage=".title hola mundo", category="Herramientas")
registry.add("uuid", uuid_cmd, "Genera un UUID aleatorio.", usage=".uuid", category="Herramientas")
registry.add("json", json_cmd, "Formatea JSON bonito.", usage=".json {\"ok\":true}", category="Herramientas")
registry.add("pwd", pwd_cmd, "Genera una contraseña aleatoria.", usage=".pwd 20", aliases=["pass"], category="Herramientas")