maxenger 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maxenger/commands.py ADDED
@@ -0,0 +1,440 @@
1
+ """Comandos tipo "!bot comando argumentos": cogs, grupos, verificaciones, cooldowns y ayuda automática."""
2
+ import asyncio
3
+ import inspect
4
+ import logging
5
+ import re
6
+ import time
7
+ from collections import defaultdict
8
+
9
+ from .client import Client, DEFAULT_URL, User, Role, Member
10
+ from .embed import Embed
11
+ from .permissions import Permissions
12
+
13
+ log = logging.getLogger("maxenger")
14
+
15
+
16
+ # ---------- errores ----------
17
+ class CommandError(Exception):
18
+ pass
19
+
20
+
21
+ class MissingArgument(CommandError):
22
+ def __init__(self, name):
23
+ super().__init__(f"Falta el argumento: {name}")
24
+ self.name = name
25
+
26
+
27
+ class BadArgument(CommandError):
28
+ pass
29
+
30
+
31
+ class MissingSubcommand(CommandError):
32
+ pass
33
+
34
+
35
+ class CheckFailure(CommandError):
36
+ pass
37
+
38
+
39
+ class MissingPermissions(CheckFailure):
40
+ def __init__(self, missing):
41
+ super().__init__("Te faltan permisos: " + ", ".join(missing))
42
+ self.missing = missing
43
+
44
+
45
+ class BotMissingPermissions(CheckFailure):
46
+ def __init__(self, missing):
47
+ super().__init__("Al bot le faltan permisos: " + ", ".join(missing))
48
+ self.missing = missing
49
+
50
+
51
+ class CommandOnCooldown(CommandError):
52
+ def __init__(self, retry_after):
53
+ super().__init__(f"Espera {retry_after:.1f} s para volver a usarlo")
54
+ self.retry_after = retry_after
55
+
56
+
57
+ # ---------- verificaciones ----------
58
+ def check(predicate):
59
+ """Decorador: el comando solo corre si predicate(ctx) devuelve True (puede ser async)."""
60
+ def deco(fn):
61
+ fn.__dict__.setdefault("__checks__", []).append(predicate)
62
+ return fn
63
+ return deco
64
+
65
+
66
+ def has_permissions(**perms):
67
+ async def pred(ctx):
68
+ if not ctx.party:
69
+ raise CheckFailure("Solo funciona en canales de una fiesta")
70
+ info = await ctx.bot.get_party(ctx.party.id)
71
+ m = info.get_member(ctx.author.id)
72
+ have = m.permissions if m else Permissions(0)
73
+ miss = have.missing(**perms)
74
+ if miss:
75
+ raise MissingPermissions(miss)
76
+ return True
77
+ return check(pred)
78
+
79
+
80
+ def bot_has_permissions(**perms):
81
+ async def pred(ctx):
82
+ info = await ctx.bot.get_party(ctx.party.id)
83
+ miss = info.my_permissions.missing(**perms)
84
+ if miss:
85
+ raise BotMissingPermissions(miss)
86
+ return True
87
+ return check(pred)
88
+
89
+
90
+ def is_party_owner():
91
+ async def pred(ctx):
92
+ info = await ctx.bot.get_party(ctx.party.id)
93
+ if info.owner_id != ctx.author.id:
94
+ raise CheckFailure("Solo el dueño de la fiesta puede usarlo")
95
+ return True
96
+ return check(pred)
97
+
98
+
99
+ def cooldown(rate, per, type="user"):
100
+ """Máximo `rate` usos cada `per` segundos, por usuario, canal o fiesta (type='user'|'channel'|'party')."""
101
+ def deco(fn):
102
+ fn.__cooldown__ = (rate, per, type)
103
+ return fn
104
+ return deco
105
+
106
+
107
+ # ---------- comandos ----------
108
+ _MENTION = re.compile(r"^<@&?(\d+)>$")
109
+
110
+
111
+ class Command:
112
+ def __init__(self, fn, name=None, description=None, aliases=(), hidden=False):
113
+ self.callback = fn
114
+ self.name = (name or fn.__name__).lower()
115
+ self.description = description or (inspect.getdoc(fn) or "").split("\n")[0][:100]
116
+ self.aliases = [a.lower() for a in aliases]
117
+ self.hidden, self.cog, self.parent = hidden, None, None
118
+ self.checks = list(getattr(fn, "__checks__", []))
119
+ self.cooldown = getattr(fn, "__cooldown__", None)
120
+ self._uses = defaultdict(list)
121
+ self.params = list(inspect.signature(fn).parameters.values()) # (self,) ctx, argumentos...
122
+
123
+ @property
124
+ def qualified_name(self):
125
+ return (self.parent.qualified_name + " " if self.parent else "") + self.name
126
+
127
+ def _params(self):
128
+ return self.params[2 if self.cog is not None else 1:]
129
+
130
+ def usage(self):
131
+ return " ".join(f"<{p.name}>" if p.default is inspect.Parameter.empty else f"[{p.name}]" for p in self._params())
132
+
133
+ def schema(self):
134
+ return {"name": self.name, "description": self.description,
135
+ "args": [{"name": p.name, "required": p.default is inspect.Parameter.empty}
136
+ for p in self._params()][:5]}
137
+
138
+ async def _convert(self, ctx, p, raw):
139
+ t, w = p.annotation, raw.strip()
140
+ try:
141
+ if t is int:
142
+ return int(w)
143
+ if t is float:
144
+ return float(w.replace(",", "."))
145
+ if t is bool:
146
+ return w.lower() in ("1", "si", "sí", "true", "yes", "on")
147
+ if t in (User, Member, Role):
148
+ m = _MENTION.match(w)
149
+ ident = int(m.group(1)) if m else (int(w) if w.isdigit() else None)
150
+ if ident is None:
151
+ raise ValueError
152
+ if ctx.party and t is not User:
153
+ info = await ctx.bot.get_party(ctx.party.id)
154
+ found = info.get_role(ident) if t is Role else info.get_member(ident)
155
+ if found:
156
+ return found
157
+ raise BadArgument(f"No encontré «{w}» en esta fiesta")
158
+ return User({"id": ident})
159
+ except ValueError:
160
+ raise BadArgument(f"«{raw}» no es un valor válido para {p.name}")
161
+ return raw
162
+
163
+ async def parse(self, ctx, text):
164
+ args, kwargs, rest = [], {}, text.strip()
165
+ for p in self._params():
166
+ kw_only = p.kind is inspect.Parameter.KEYWORD_ONLY
167
+ if kw_only or p.kind is inspect.Parameter.VAR_POSITIONAL:
168
+ raw, rest = rest, ""
169
+ else:
170
+ head, _, tail = rest.partition(" ") if rest else ("", "", "")
171
+ raw, rest = head, tail.strip()
172
+ if not raw:
173
+ if p.default is inspect.Parameter.empty:
174
+ raise MissingArgument(p.name)
175
+ val = p.default
176
+ else:
177
+ val = await self._convert(ctx, p, raw)
178
+ if kw_only:
179
+ kwargs[p.name] = val
180
+ else:
181
+ args.append(val)
182
+ return args, kwargs
183
+
184
+ async def _run_checks(self, ctx):
185
+ for pred in list(ctx.bot._checks) + (self.parent.checks if self.parent else []) + self.checks:
186
+ ok = pred(ctx)
187
+ if inspect.isawaitable(ok):
188
+ ok = await ok
189
+ if not ok:
190
+ raise CheckFailure("No puedes usar este comando")
191
+
192
+ def _check_cooldown(self, ctx):
193
+ if not self.cooldown:
194
+ return
195
+ rate, per, kind = self.cooldown
196
+ key = {"user": ctx.author.id, "channel": ctx.channel.id, "party": ctx.party.id if ctx.party else 0}.get(kind, ctx.author.id)
197
+ now = time.monotonic()
198
+ uses = [t for t in self._uses[key] if now - t < per]
199
+ if len(uses) >= rate:
200
+ self._uses[key] = uses
201
+ raise CommandOnCooldown(per - (now - uses[0]))
202
+ uses.append(now)
203
+ self._uses[key] = uses
204
+
205
+ async def invoke(self, ctx, text):
206
+ await self._run_checks(ctx)
207
+ args, kwargs = await self.parse(ctx, text)
208
+ self._check_cooldown(ctx)
209
+ ctx.command = self
210
+ if self.cog is not None:
211
+ return await self.callback(self.cog, ctx, *args, **kwargs)
212
+ return await self.callback(ctx, *args, **kwargs)
213
+
214
+
215
+ class Group(Command):
216
+ """Comando con subcomandos: `!bot config prefijo ...`."""
217
+
218
+ def __init__(self, fn, invoke_without_command=False, **kw):
219
+ super().__init__(fn, **kw)
220
+ self.subcommands, self.invoke_without_command = {}, invoke_without_command
221
+ self.params = self.params[:1] if not self.cog else self.params
222
+
223
+ def command(self, name=None, *, description=None, aliases=()):
224
+ def deco(fn):
225
+ c = Command(fn, name, description, aliases)
226
+ c.parent = self
227
+ self.add_subcommand(c)
228
+ return fn
229
+ return deco
230
+
231
+ def add_subcommand(self, c):
232
+ c.parent = self
233
+ self.subcommands[c.name] = c
234
+ for a in c.aliases:
235
+ self.subcommands[a] = c
236
+
237
+ def usage(self):
238
+ return "<" + "|".join(sorted({c.name for c in self.subcommands.values()})) + ">"
239
+
240
+ def schema(self):
241
+ return {"name": self.name, "description": self.description,
242
+ "args": [{"name": "subcomando", "required": not self.invoke_without_command}]}
243
+
244
+ async def invoke(self, ctx, text):
245
+ head, _, tail = text.strip().partition(" ")
246
+ sub = self.subcommands.get(head.lower()) if head else None
247
+ if sub is not None:
248
+ await self._run_checks(ctx)
249
+ if self.cog is not None and sub.cog is None:
250
+ sub.cog = self.cog
251
+ return await sub.invoke(ctx, tail)
252
+ if self.invoke_without_command:
253
+ await self._run_checks(ctx)
254
+ ctx.command = self
255
+ self._check_cooldown(ctx)
256
+ return await (self.callback(self.cog, ctx) if self.cog is not None else self.callback(ctx))
257
+ raise MissingSubcommand("Subcomandos: " + ", ".join(sorted({c.name for c in self.subcommands.values()})))
258
+
259
+
260
+ def command(name=None, *, description=None, aliases=(), hidden=False):
261
+ def deco(fn):
262
+ fn.__command__ = dict(name=name, description=description, aliases=aliases, hidden=hidden)
263
+ return fn
264
+ return deco
265
+
266
+
267
+ def group(name=None, *, description=None, aliases=(), invoke_without_command=False):
268
+ def deco(fn):
269
+ fn.__group__ = dict(name=name, description=description, aliases=aliases, invoke_without_command=invoke_without_command)
270
+ return fn
271
+ return deco
272
+
273
+
274
+ class Cog:
275
+ """Agrupa comandos y eventos en una clase."""
276
+
277
+ @staticmethod
278
+ def listener(name=None):
279
+ def deco(fn):
280
+ fn.__listener__ = name or fn.__name__
281
+ return fn
282
+ return deco
283
+
284
+ async def cog_load(self):
285
+ pass
286
+
287
+
288
+ class Context:
289
+ def __init__(self, bot, message, command, invoked):
290
+ self.bot, self.message, self.command = bot, message, command
291
+ self.channel, self.author, self.party = message.channel, message.author, message.party
292
+ self.prefix, self.args = bot.prefix, invoked.get("args", "")
293
+ self.invoked_with = invoked.get("command")
294
+ self.voice_conversation_id = getattr(message, "voice_conversation_id", None)
295
+
296
+ async def send(self, content=None, **kw):
297
+ return await self.channel.send(content, **kw)
298
+
299
+ async def reply(self, content=None, **kw):
300
+ return await self.message.reply(content, **kw)
301
+
302
+ def typing(self):
303
+ return self.channel.typing()
304
+
305
+ async def fetch_party(self):
306
+ return await self.bot.get_party(self.party.id) if self.party else None
307
+
308
+ async def author_permissions(self):
309
+ info = await self.fetch_party()
310
+ m = info.get_member(self.author.id) if info else None
311
+ return m.permissions if m else Permissions(0)
312
+
313
+
314
+ class Bot(Client):
315
+ def __init__(self, token, url=DEFAULT_URL, *, help_command=True):
316
+ super().__init__(token, url)
317
+ self.commands, self.cogs, self._checks = {}, {}, []
318
+ self.add_listener(self._sync_on_ready, "ready")
319
+ self.add_listener(self._process, "message")
320
+ if help_command:
321
+ self.add_command(Command(_ayuda, "ayuda", "Muestra los comandos disponibles", ("help",)))
322
+
323
+ # ---------- registro ----------
324
+ def command(self, name=None, *, description=None, aliases=(), hidden=False):
325
+ def deco(fn):
326
+ self.add_command(Command(fn, name, description, aliases, hidden))
327
+ return fn
328
+ return deco
329
+
330
+ def group(self, name=None, *, description=None, aliases=(), invoke_without_command=False):
331
+ def deco(fn):
332
+ g = Group(fn, invoke_without_command, name=name, description=description, aliases=aliases)
333
+ self.add_command(g)
334
+ return g
335
+ return deco
336
+
337
+ def check(self, fn):
338
+ """Verificación global: se aplica a todos los comandos."""
339
+ self._checks.append(fn)
340
+ return fn
341
+
342
+ def add_command(self, cmd):
343
+ self.commands[cmd.name] = cmd
344
+ for a in cmd.aliases:
345
+ self.commands[a] = cmd
346
+
347
+ async def add_cog(self, cog):
348
+ self.cogs[type(cog).__name__] = cog
349
+ for attr in dir(type(cog)):
350
+ fn = getattr(type(cog), attr, None)
351
+ g, meta = getattr(fn, "__group__", None), getattr(fn, "__command__", None)
352
+ if g:
353
+ c = Group(fn, g.pop("invoke_without_command"), **g)
354
+ c.cog = cog
355
+ self.add_command(c)
356
+ setattr(type(cog), attr, c)
357
+ elif meta:
358
+ c = Command(fn, **meta)
359
+ c.cog = cog
360
+ self.add_command(c)
361
+ lst = getattr(fn, "__listener__", None)
362
+ if lst:
363
+ self.add_listener(getattr(cog, attr), lst)
364
+ for c in list(self.commands.values()): # subcomandos declarados con @grupo.command() dentro de una Cog
365
+ if isinstance(c, Group) and c.cog is cog:
366
+ for s in c.subcommands.values():
367
+ s.cog = cog
368
+ await cog.cog_load()
369
+ if self.user:
370
+ await self._sync_commands()
371
+
372
+ async def _sync_on_ready(self):
373
+ await self._sync_commands()
374
+
375
+ async def _sync_commands(self):
376
+ seen, out = set(), []
377
+ for c in self.commands.values():
378
+ if c.name not in seen and not c.hidden:
379
+ seen.add(c.name)
380
+ out.append(c.schema())
381
+ try:
382
+ await self.register_commands(out)
383
+ except Exception as e:
384
+ log.warning("No se pudieron publicar los comandos: %s", e)
385
+
386
+ # ---------- ejecución ----------
387
+ async def _process(self, message):
388
+ inv = getattr(message, "invoked", None)
389
+ if not inv or not inv.get("command"):
390
+ return
391
+ cmd = self.commands.get(inv["command"])
392
+ if cmd is None:
393
+ self.dispatch("command_not_found", message, inv["command"])
394
+ return
395
+ ctx = Context(self, message, cmd, inv)
396
+ try:
397
+ self.dispatch("command", ctx)
398
+ await cmd.invoke(ctx, inv.get("args", ""))
399
+ self.dispatch("command_completion", ctx)
400
+ except Exception as e:
401
+ if self._handlers.get("command_error"):
402
+ self.dispatch("command_error", ctx, e)
403
+ return
404
+ await self._default_error(ctx, cmd, e)
405
+
406
+ async def _default_error(self, ctx, cmd, e):
407
+ name = ctx.command.qualified_name if ctx.command else cmd.name
408
+ if isinstance(e, CommandOnCooldown):
409
+ await ctx.reply(f"⏳ {e}")
410
+ elif isinstance(e, CheckFailure):
411
+ await ctx.reply(f"🚫 {e}")
412
+ elif isinstance(e, (MissingArgument, BadArgument)):
413
+ await ctx.reply(f"⚠️ {e}. Uso: !{self.prefix or ''} {name} {(ctx.command or cmd).usage()}".replace("! ", "!"))
414
+ elif isinstance(e, MissingSubcommand):
415
+ await ctx.reply(f"⚠️ {e}")
416
+ else:
417
+ log.exception("Error en el comando %s", name)
418
+ await ctx.send("❌ Ocurrió un error con ese comando.")
419
+
420
+
421
+ async def _ayuda(ctx, comando=None):
422
+ """Muestra los comandos disponibles"""
423
+ bot = ctx.bot
424
+ if comando:
425
+ c = bot.commands.get(comando.lower())
426
+ if not c or c.hidden:
427
+ return await ctx.reply(f"No existe el comando «{comando}».")
428
+ e = Embed(title=f"{c.name} {c.usage()}".strip(), description=c.description or "Sin descripción")
429
+ if c.aliases:
430
+ e.add_field("Alias", ", ".join(c.aliases))
431
+ if isinstance(c, Group):
432
+ e.add_field("Subcomandos", ", ".join(sorted({s.name for s in c.subcommands.values()})))
433
+ return await ctx.reply(embed=e)
434
+ vistos, lineas = set(), []
435
+ for c in bot.commands.values():
436
+ if c.name in vistos or c.hidden:
437
+ continue
438
+ vistos.add(c.name)
439
+ lineas.append(f"**{c.name}** {c.usage()} — {c.description}".replace(" ", " "))
440
+ await ctx.reply(embed=Embed(title="Comandos", description="\n".join(sorted(lineas)) or "Sin comandos"))
maxenger/embed.py ADDED
@@ -0,0 +1,40 @@
1
+ """Tarjetas (embeds) para los mensajes del bot."""
2
+ from datetime import datetime
3
+
4
+
5
+ class Embed:
6
+ def __init__(self, title=None, description=None, url=None, color=None, timestamp=None):
7
+ self.title, self.description, self.url = title, description, url
8
+ self.color, self.timestamp = color, timestamp
9
+ self._fields, self._author, self._footer = [], None, None
10
+ self._thumbnail, self._image = None, None
11
+
12
+ def add_field(self, name, value, inline=False):
13
+ self._fields.append({"name": str(name), "value": str(value), "inline": bool(inline)})
14
+ return self
15
+
16
+ def set_author(self, name, url=None, icon_url=None):
17
+ self._author = {"name": name, "url": url, "icon_url": icon_url}
18
+ return self
19
+
20
+ def set_footer(self, text, icon_url=None):
21
+ self._footer = {"text": text, "icon_url": icon_url}
22
+ return self
23
+
24
+ def set_thumbnail(self, url):
25
+ self._thumbnail = {"url": url}
26
+ return self
27
+
28
+ def set_image(self, url):
29
+ self._image = {"url": url}
30
+ return self
31
+
32
+ def to_dict(self):
33
+ d = {"title": self.title, "description": self.description, "url": self.url,
34
+ "color": self.color, "fields": self._fields or None, "author": self._author,
35
+ "footer": self._footer, "thumbnail": self._thumbnail, "image": self._image}
36
+ if isinstance(self.timestamp, datetime):
37
+ d["timestamp"] = self.timestamp.isoformat()
38
+ elif self.timestamp:
39
+ d["timestamp"] = str(self.timestamp)
40
+ return {k: v for k, v in d.items() if v is not None}
@@ -0,0 +1,39 @@
1
+ """Permisos de una fiesta (los mismos que ves en los roles)."""
2
+
3
+ FLAGS = {
4
+ "send_messages": 1, "manage_messages": 2, "manage_channels": 4, "manage_roles": 8,
5
+ "create_invites": 16, "kick_members": 32, "manage_party": 64, "administrator": 128,
6
+ "manage_nicknames": 256, "view_audit_log": 512, "ban_members": 1024, "manage_invites": 2048,
7
+ }
8
+ ALL = sum(FLAGS.values())
9
+
10
+
11
+ class Permissions:
12
+ def __init__(self, value=0, **flags):
13
+ self.value = int(value)
14
+ for k, on in flags.items():
15
+ if k not in FLAGS:
16
+ raise TypeError(f"permiso desconocido: {k}")
17
+ self.value = (self.value | FLAGS[k]) if on else (self.value & ~FLAGS[k])
18
+
19
+ def __getattr__(self, name):
20
+ if name in FLAGS:
21
+ return bool(self.value & FLAGS[name]) or bool(self.value & FLAGS["administrator"])
22
+ raise AttributeError(name)
23
+
24
+ def has(self, **flags):
25
+ """True si tiene todos los permisos pedidos: has(kick_members=True)."""
26
+ return all(getattr(self, k) for k, want in flags.items() if want)
27
+
28
+ def missing(self, **flags):
29
+ return [k for k, want in flags.items() if want and not getattr(self, k)]
30
+
31
+ @classmethod
32
+ def all(cls):
33
+ return cls(ALL)
34
+
35
+ def __int__(self):
36
+ return self.value
37
+
38
+ def __repr__(self):
39
+ return "<Permissions " + ", ".join(k for k in FLAGS if getattr(self, k)) + ">"
maxenger/tasks.py ADDED
@@ -0,0 +1,81 @@
1
+ """Tareas que se repiten cada cierto tiempo."""
2
+ import asyncio
3
+ import logging
4
+
5
+ log = logging.getLogger("maxenger")
6
+
7
+
8
+ class Loop:
9
+ def __init__(self, fn, seconds=0, minutes=0, hours=0, count=None, instance=None):
10
+ self.fn, self.instance, self.count = fn, instance, count
11
+ self.interval = seconds + minutes * 60 + hours * 3600
12
+ if self.interval <= 0:
13
+ raise ValueError("el intervalo debe ser mayor que 0")
14
+ self._task = None
15
+ self._before = self._after = None
16
+ self.current_loop = 0
17
+ self._bound = {}
18
+
19
+ def __get__(self, obj, owner=None): # permite usarlo dentro de una Cog
20
+ if obj is None:
21
+ return self
22
+ b = self._bound.get(id(obj))
23
+ if b is None:
24
+ b = self._bound[id(obj)] = Loop(self.fn, self.interval, count=self.count, instance=obj)
25
+ b._before, b._after = self._before, self._after
26
+ return b
27
+
28
+ def before_loop(self, fn):
29
+ self._before = fn
30
+ return fn
31
+
32
+ def after_loop(self, fn):
33
+ self._after = fn
34
+ return fn
35
+
36
+ def _call(self, fn):
37
+ return fn(self.instance) if self.instance is not None and fn in (self._before, self._after) else fn()
38
+
39
+ def start(self, *args, **kwargs):
40
+ if self._task and not self._task.done():
41
+ raise RuntimeError("la tarea ya está corriendo")
42
+ self._task = asyncio.create_task(self._run(args, kwargs))
43
+ return self._task
44
+
45
+ def stop(self):
46
+ if self._task:
47
+ self._task.cancel()
48
+
49
+ def is_running(self):
50
+ return bool(self._task and not self._task.done())
51
+
52
+ async def _run(self, args, kwargs):
53
+ try:
54
+ if self._before:
55
+ await (self._before(self.instance) if self.instance is not None else self._before())
56
+ while self.count is None or self.current_loop < self.count:
57
+ try:
58
+ if self.instance is not None:
59
+ await self.fn(self.instance, *args, **kwargs)
60
+ else:
61
+ await self.fn(*args, **kwargs)
62
+ except asyncio.CancelledError:
63
+ raise
64
+ except Exception:
65
+ log.exception("Error en la tarea %s", getattr(self.fn, "__name__", "?"))
66
+ self.current_loop += 1
67
+ await asyncio.sleep(self.interval)
68
+ except asyncio.CancelledError:
69
+ pass
70
+ finally:
71
+ if self._after:
72
+ try:
73
+ await (self._after(self.instance) if self.instance is not None else self._after())
74
+ except Exception:
75
+ log.exception("Error en after_loop")
76
+
77
+
78
+ def loop(*, seconds=0, minutes=0, hours=0, count=None):
79
+ def deco(fn):
80
+ return Loop(fn, seconds, minutes, hours, count)
81
+ return deco