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/__init__.py +10 -0
- maxenger/client.py +616 -0
- maxenger/commands.py +440 -0
- maxenger/embed.py +40 -0
- maxenger/permissions.py +39 -0
- maxenger/tasks.py +81 -0
- maxenger/ui.py +146 -0
- maxenger-0.2.0.dist-info/METADATA +148 -0
- maxenger-0.2.0.dist-info/RECORD +12 -0
- maxenger-0.2.0.dist-info/WHEEL +5 -0
- maxenger-0.2.0.dist-info/licenses/LICENSE +21 -0
- maxenger-0.2.0.dist-info/top_level.txt +1 -0
maxenger/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""maxenger — librería para hacer bots de Maxenger."""
|
|
2
|
+
from .client import (Client, Channel, Message, User, Member, Role, Party, PartyInfo, Reaction, File,
|
|
3
|
+
Interaction, MaxengerError)
|
|
4
|
+
from .permissions import Permissions
|
|
5
|
+
from .embed import Embed
|
|
6
|
+
from . import ui, commands, tasks
|
|
7
|
+
|
|
8
|
+
__version__ = "0.2.0"
|
|
9
|
+
__all__ = ["Client", "Channel", "Message", "User", "Member", "Role", "Party", "PartyInfo", "Reaction", "File",
|
|
10
|
+
"Interaction", "MaxengerError", "Permissions", "Embed", "ui", "commands", "tasks"]
|
maxenger/client.py
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
"""Conexión con Maxenger y objetos básicos (usuario, canal, mensaje, fiesta, interacción)."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import inspect
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
from collections import OrderedDict
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
import aiohttp
|
|
12
|
+
import socketio
|
|
13
|
+
|
|
14
|
+
from .embed import Embed
|
|
15
|
+
from .permissions import Permissions, ALL as _ALL
|
|
16
|
+
from .ui import Select
|
|
17
|
+
|
|
18
|
+
log = logging.getLogger("maxenger")
|
|
19
|
+
NS = "/bots"
|
|
20
|
+
DEFAULT_URL = "https://maxenger.dpdns.org"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MaxengerError(Exception):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _lru(d, cap=500):
|
|
28
|
+
while len(d) > cap:
|
|
29
|
+
d.popitem(last=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _embeds(embed, embeds):
|
|
33
|
+
out = list(embeds or [])
|
|
34
|
+
if embed is not None:
|
|
35
|
+
out.insert(0, embed)
|
|
36
|
+
return [e.to_dict() if isinstance(e, Embed) else e for e in out] or None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class File:
|
|
40
|
+
"""Un archivo para mandar: File('foto.png') o File(datos_bytes, 'x.txt', spoiler=True)."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, fp, filename=None, *, spoiler=False):
|
|
43
|
+
if isinstance(fp, (bytes, bytearray)):
|
|
44
|
+
self.data, self.filename = bytes(fp), filename or "archivo"
|
|
45
|
+
else:
|
|
46
|
+
self.data, self.path = None, os.fspath(fp)
|
|
47
|
+
self.filename = filename or os.path.basename(self.path)
|
|
48
|
+
self.spoiler = spoiler
|
|
49
|
+
|
|
50
|
+
def read(self):
|
|
51
|
+
if self.data is None:
|
|
52
|
+
with open(self.path, "rb") as f:
|
|
53
|
+
return f.read()
|
|
54
|
+
return self.data
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class User:
|
|
58
|
+
def __init__(self, data):
|
|
59
|
+
data = data or {}
|
|
60
|
+
self.id = int(data.get("id") or 0)
|
|
61
|
+
self.username = data.get("username")
|
|
62
|
+
self.name = data.get("name") or data.get("display_name") or data.get("username") or "usuario"
|
|
63
|
+
self.avatar_url = data.get("avatar_url")
|
|
64
|
+
self.bot = bool(data.get("is_bot"))
|
|
65
|
+
|
|
66
|
+
mention = property(lambda s: f"<@{s.id}>")
|
|
67
|
+
display_name = property(lambda s: s.name)
|
|
68
|
+
|
|
69
|
+
def __eq__(self, o):
|
|
70
|
+
return isinstance(o, User) and o.id == self.id
|
|
71
|
+
|
|
72
|
+
def __hash__(self):
|
|
73
|
+
return self.id
|
|
74
|
+
|
|
75
|
+
def __repr__(self):
|
|
76
|
+
return f"<User {self.id} {self.name!r}>"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class Role:
|
|
80
|
+
def __init__(self, d):
|
|
81
|
+
self.id, self.name, self.color = int(d["id"]), d.get("name"), d.get("color")
|
|
82
|
+
self.permissions = Permissions(d.get("permissions") or 0)
|
|
83
|
+
self.position, self.is_default = int(d.get("position") or 0), bool(d.get("is_default"))
|
|
84
|
+
self.bot_user_id = d.get("bot_user_id")
|
|
85
|
+
|
|
86
|
+
mention = property(lambda s: f"<@&{s.id}>")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Member(User):
|
|
90
|
+
"""Persona dentro de una fiesta: con apodo, roles y permisos."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, d, party):
|
|
93
|
+
super().__init__(d)
|
|
94
|
+
self.party, self.nickname = party, d.get("nickname")
|
|
95
|
+
self.role_ids = [int(x) for x in d.get("role_ids") or []]
|
|
96
|
+
self.is_owner = bool(d.get("is_owner"))
|
|
97
|
+
self.color = d.get("color")
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def display_name(self):
|
|
101
|
+
return self.nickname or self.name
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def roles(self):
|
|
105
|
+
by = {r.id: r for r in self.party.roles}
|
|
106
|
+
return [by[i] for i in self.role_ids if i in by]
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def permissions(self):
|
|
110
|
+
if self.is_owner:
|
|
111
|
+
return Permissions(_ALL)
|
|
112
|
+
v = 0
|
|
113
|
+
for r in self.party.roles:
|
|
114
|
+
if r.is_default or r.id in self.role_ids:
|
|
115
|
+
v |= r.permissions.value
|
|
116
|
+
return Permissions(v)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class PartyInfo:
|
|
120
|
+
"""Fotografía de una fiesta: miembros, roles y canales. Se obtiene con `await party.fetch()`."""
|
|
121
|
+
|
|
122
|
+
def __init__(self, client, d):
|
|
123
|
+
self._c = client
|
|
124
|
+
self.id, self.name, self.owner_id = int(d["id"]), d.get("name"), int(d.get("owner_id") or 0)
|
|
125
|
+
self.roles = [Role(r) for r in d.get("roles") or []]
|
|
126
|
+
self.members = [Member(m, self) for m in d.get("members") or []]
|
|
127
|
+
self.channels = [Channel(client, c["conversation_id"], c.get("name"), Party(client, self.id, self.name),
|
|
128
|
+
kind=c.get("kind"), channel_id=c.get("id")) for c in d.get("channels") or []]
|
|
129
|
+
self.my_permissions = Permissions((d.get("my") or {}).get("perms") or 0)
|
|
130
|
+
self.fetched_at = time.time()
|
|
131
|
+
|
|
132
|
+
def get_member(self, user_id):
|
|
133
|
+
return next((m for m in self.members if m.id == int(user_id)), None)
|
|
134
|
+
|
|
135
|
+
def get_channel(self, conversation_id):
|
|
136
|
+
return next((c for c in self.channels if c.id == int(conversation_id)), None)
|
|
137
|
+
|
|
138
|
+
def get_role(self, role_id):
|
|
139
|
+
return next((r for r in self.roles if r.id == int(role_id)), None)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class Party:
|
|
143
|
+
def __init__(self, client, pid, name=None):
|
|
144
|
+
self._c, self.id, self.name = client, int(pid), name
|
|
145
|
+
|
|
146
|
+
async def fetch(self, refresh=False):
|
|
147
|
+
return await self._c.get_party(self.id, refresh=refresh)
|
|
148
|
+
|
|
149
|
+
async def kick(self, user):
|
|
150
|
+
await self._c.call("member:kick", {"party_id": self.id, "user_id": int(getattr(user, "id", user))})
|
|
151
|
+
|
|
152
|
+
async def ban(self, user, reason=None):
|
|
153
|
+
await self._c.call("member:ban", {"party_id": self.id, "user_id": int(getattr(user, "id", user)), "reason": reason})
|
|
154
|
+
|
|
155
|
+
async def unban(self, user):
|
|
156
|
+
await self._c.call("member:unban", {"party_id": self.id, "user_id": int(getattr(user, "id", user))})
|
|
157
|
+
|
|
158
|
+
async def set_roles(self, user, roles):
|
|
159
|
+
ids = [int(getattr(r, "id", r)) for r in roles]
|
|
160
|
+
await self._c.call("member:roles", {"party_id": self.id, "user_id": int(getattr(user, "id", user)), "role_ids": ids})
|
|
161
|
+
self._c._parties.pop(self.id, None)
|
|
162
|
+
|
|
163
|
+
async def set_nickname(self, user, nickname):
|
|
164
|
+
await self._c.call("member:nick", {"party_id": self.id, "user_id": int(getattr(user, "id", user)), "nickname": nickname})
|
|
165
|
+
self._c._parties.pop(self.id, None)
|
|
166
|
+
|
|
167
|
+
async def create_channel(self, name, kind="text"):
|
|
168
|
+
r = await self._c.call("channel:create", {"party_id": self.id, "name": name, "kind": kind})
|
|
169
|
+
self._c._parties.pop(self.id, None)
|
|
170
|
+
return r.get("channel")
|
|
171
|
+
|
|
172
|
+
async def delete_channel(self, channel_id):
|
|
173
|
+
await self._c.call("channel:delete", {"party_id": self.id, "channel_id": int(channel_id)})
|
|
174
|
+
self._c._parties.pop(self.id, None)
|
|
175
|
+
|
|
176
|
+
def __repr__(self):
|
|
177
|
+
return f"<Party {self.id} {self.name!r}>"
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class Channel:
|
|
181
|
+
def __init__(self, client, conv_id, name=None, party=None, kind=None, channel_id=None):
|
|
182
|
+
self._c, self.id, self.name, self.party = client, int(conv_id), name, party
|
|
183
|
+
self.kind, self.channel_id = kind, channel_id
|
|
184
|
+
|
|
185
|
+
async def send(self, content=None, *, embed=None, embeds=None, view=None, reply_to=None, file=None, files=None):
|
|
186
|
+
data = {"conversation_id": self.id, "body": content or "", "embeds": _embeds(embed, embeds)}
|
|
187
|
+
todos = list(files or []) + ([file] if file else [])
|
|
188
|
+
if todos:
|
|
189
|
+
ids, spoilers = [], []
|
|
190
|
+
for f in todos[:10]:
|
|
191
|
+
aid = await self._c._upload(f)
|
|
192
|
+
ids.append(aid)
|
|
193
|
+
if f.spoiler:
|
|
194
|
+
spoilers.append(aid)
|
|
195
|
+
data["attachment_ids"], data["spoiler_ids"] = ids, spoilers
|
|
196
|
+
if view is not None:
|
|
197
|
+
data["components"] = view.to_components()
|
|
198
|
+
if reply_to is not None:
|
|
199
|
+
data["reply_to_id"] = int(getattr(reply_to, "id", reply_to))
|
|
200
|
+
r = await self._c.call("message:send", data)
|
|
201
|
+
msg = Message._sent(self._c, self, r["id"], content or "")
|
|
202
|
+
if view is not None:
|
|
203
|
+
self._c._views[("m", msg.id)] = view
|
|
204
|
+
_lru(self._c._views)
|
|
205
|
+
return msg
|
|
206
|
+
|
|
207
|
+
async def history(self, limit=50, *, before=None, oldest_first=False):
|
|
208
|
+
"""Mensajes anteriores: `async for m in canal.history(limit=200)` (del más nuevo al más viejo)."""
|
|
209
|
+
out, cursor = [], before
|
|
210
|
+
while len(out) < limit:
|
|
211
|
+
r = await self._c.call("messages:history", {"conversation_id": self.id, "before_id": cursor,
|
|
212
|
+
"limit": min(100, limit - len(out))})
|
|
213
|
+
page = r.get("messages") or []
|
|
214
|
+
for m in reversed(page):
|
|
215
|
+
out.append(Message(self._c, self, m))
|
|
216
|
+
if not page or not r.get("has_more"):
|
|
217
|
+
break
|
|
218
|
+
cursor = page[0]["id"]
|
|
219
|
+
if oldest_first:
|
|
220
|
+
out.reverse()
|
|
221
|
+
for m in out:
|
|
222
|
+
yield m
|
|
223
|
+
|
|
224
|
+
async def fetch_message(self, message_id):
|
|
225
|
+
r = await self._c.call("message:get", {"conversation_id": self.id, "message_id": int(message_id)})
|
|
226
|
+
return Message(self._c, self, r["message"])
|
|
227
|
+
|
|
228
|
+
def typing(self):
|
|
229
|
+
return _Typing(self._c, self.id)
|
|
230
|
+
|
|
231
|
+
def __repr__(self):
|
|
232
|
+
return f"<Channel {self.id} {self.name!r}>"
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class _Typing:
|
|
236
|
+
def __init__(self, c, cid):
|
|
237
|
+
self.c, self.cid = c, cid
|
|
238
|
+
|
|
239
|
+
async def __aenter__(self):
|
|
240
|
+
await self.c.emit("typing", {"conversation_id": self.cid, "typing": True})
|
|
241
|
+
|
|
242
|
+
async def __aexit__(self, *a):
|
|
243
|
+
await self.c.emit("typing", {"conversation_id": self.cid, "typing": False})
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class Message:
|
|
247
|
+
def __init__(self, client, channel, data, author=None):
|
|
248
|
+
self._c, self.channel = client, channel
|
|
249
|
+
self.id = int(data["id"])
|
|
250
|
+
self.content = data.get("body") or ""
|
|
251
|
+
self.author = author or User(data.get("sender") or {"id": data.get("sender_id")})
|
|
252
|
+
self.reply_to = (data.get("reply") or {}).get("id")
|
|
253
|
+
self.mentions = [int(x) for x in (data.get("mentions") or [])]
|
|
254
|
+
self.attachments = data.get("attachments") or []
|
|
255
|
+
self.reactions = data.get("reactions") or []
|
|
256
|
+
self.edited = bool(data.get("edited"))
|
|
257
|
+
self.party = channel.party
|
|
258
|
+
self.invoked = None
|
|
259
|
+
|
|
260
|
+
@classmethod
|
|
261
|
+
def _sent(cls, client, channel, mid, content):
|
|
262
|
+
return cls(client, channel, {"id": mid, "body": content}, author=client.user)
|
|
263
|
+
|
|
264
|
+
async def reply(self, content=None, **kw):
|
|
265
|
+
return await self.channel.send(content, reply_to=self.id, **kw)
|
|
266
|
+
|
|
267
|
+
async def edit(self, *, content=None, embed=None, embeds=None, view=None):
|
|
268
|
+
data = {"conversation_id": self.channel.id, "message_id": self.id}
|
|
269
|
+
if content is not None:
|
|
270
|
+
data["body"] = content
|
|
271
|
+
if embed is not None or embeds is not None:
|
|
272
|
+
data["embeds"] = _embeds(embed, embeds) or []
|
|
273
|
+
if view is not None:
|
|
274
|
+
data["components"] = view.to_components()
|
|
275
|
+
self._c._views[("m", self.id)] = view
|
|
276
|
+
await self._c.call("message:edit", data)
|
|
277
|
+
return self
|
|
278
|
+
|
|
279
|
+
async def delete(self):
|
|
280
|
+
await self._c.call("message:delete", {"conversation_id": self.channel.id, "message_id": self.id})
|
|
281
|
+
|
|
282
|
+
async def react(self, emoji, on=True):
|
|
283
|
+
await self._c.call("reaction:set", {"conversation_id": self.channel.id, "message_id": self.id,
|
|
284
|
+
"emoji": emoji, "on": on})
|
|
285
|
+
|
|
286
|
+
async def unreact(self, emoji):
|
|
287
|
+
await self.react(emoji, on=False)
|
|
288
|
+
|
|
289
|
+
async def fetch_reactors(self, emoji):
|
|
290
|
+
r = await self._c.call("reaction:list", {"conversation_id": self.channel.id, "message_id": self.id, "emoji": emoji})
|
|
291
|
+
return [User(u) for u in (r.get("users") or [])]
|
|
292
|
+
|
|
293
|
+
async def refresh(self):
|
|
294
|
+
return await self.channel.fetch_message(self.id)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class Reaction:
|
|
298
|
+
def __init__(self, message, emoji, count):
|
|
299
|
+
self.message, self.emoji, self.count = message, emoji, count
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class Interaction:
|
|
303
|
+
"""Clic en un botón/menú o envío de un formulario."""
|
|
304
|
+
|
|
305
|
+
def __init__(self, client, d, channel, user, message):
|
|
306
|
+
self._c, self.data, self.channel, self.user, self.message = client, d, channel, user, message
|
|
307
|
+
self.custom_id, self.kind = d.get("custom_id"), d.get("kind")
|
|
308
|
+
self.values = d.get("values") or []
|
|
309
|
+
self.popup_id = d.get("popup_id")
|
|
310
|
+
self.voice_conversation_id = d.get("voice_conversation_id")
|
|
311
|
+
self.party = channel.party
|
|
312
|
+
|
|
313
|
+
async def respond(self, content=None, *, embed=None, embeds=None, view=None):
|
|
314
|
+
"""Respuesta privada: solo la ve quien hizo clic."""
|
|
315
|
+
pid = "p" + uuid.uuid4().hex[:12]
|
|
316
|
+
payload = {"user_id": self.user.id, "conversation_id": self.channel.id, "text": content or "",
|
|
317
|
+
"embeds": _embeds(embed, embeds), "popup_id": pid}
|
|
318
|
+
if view is not None:
|
|
319
|
+
payload["components"] = view.to_components()
|
|
320
|
+
r = await self._c.call("interaction:reply", payload)
|
|
321
|
+
if view is not None:
|
|
322
|
+
self._c._views[("p", self.user.id, r.get("popup_id", pid))] = view
|
|
323
|
+
_lru(self._c._views)
|
|
324
|
+
|
|
325
|
+
async def edit_message(self, **kw):
|
|
326
|
+
if self.message:
|
|
327
|
+
await self.message.edit(**kw)
|
|
328
|
+
|
|
329
|
+
async def send_modal(self, modal):
|
|
330
|
+
await self._c.call("interaction:modal", {
|
|
331
|
+
"user_id": self.user.id, "conversation_id": self.channel.id, "custom_id": modal.custom_id,
|
|
332
|
+
"title": modal.title, "fields": [f.to_dict() for f in modal.children]})
|
|
333
|
+
self._c._modals[(self.user.id, modal.custom_id)] = modal
|
|
334
|
+
_lru(self._c._modals)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
class Client:
|
|
338
|
+
def __init__(self, token, url=DEFAULT_URL):
|
|
339
|
+
self.token, self.url = token, url.rstrip("/")
|
|
340
|
+
self.sio = None
|
|
341
|
+
self.user = None
|
|
342
|
+
self.prefix = None
|
|
343
|
+
self._handlers = {}
|
|
344
|
+
self._waiters = {}
|
|
345
|
+
self._views, self._modals, self._seen = OrderedDict(), OrderedDict(), OrderedDict()
|
|
346
|
+
self._tasks = set()
|
|
347
|
+
self._parties = {}
|
|
348
|
+
self._activity = None
|
|
349
|
+
self._http = None
|
|
350
|
+
|
|
351
|
+
# ---------- eventos ----------
|
|
352
|
+
def event(self, fn):
|
|
353
|
+
self._handlers.setdefault(fn.__name__.removeprefix("on_"), []).append(fn)
|
|
354
|
+
return fn
|
|
355
|
+
|
|
356
|
+
def listen(self, name=None):
|
|
357
|
+
def deco(fn):
|
|
358
|
+
self.add_listener(fn, name)
|
|
359
|
+
return fn
|
|
360
|
+
return deco
|
|
361
|
+
|
|
362
|
+
def add_listener(self, fn, name=None):
|
|
363
|
+
self._handlers.setdefault((name or fn.__name__).removeprefix("on_"), []).append(fn)
|
|
364
|
+
|
|
365
|
+
def dispatch(self, name, *args):
|
|
366
|
+
for fut, check in list(self._waiters.get(name, [])):
|
|
367
|
+
try:
|
|
368
|
+
if not fut.done() and (check is None or check(*args)):
|
|
369
|
+
fut.set_result(args[0] if len(args) == 1 else args)
|
|
370
|
+
self._waiters[name].remove((fut, check))
|
|
371
|
+
except Exception as e:
|
|
372
|
+
if not fut.done():
|
|
373
|
+
fut.set_exception(e)
|
|
374
|
+
for fn in list(self._handlers.get(name, [])):
|
|
375
|
+
self._spawn(self._run(name, fn, args))
|
|
376
|
+
|
|
377
|
+
async def wait_for(self, event, *, check=None, timeout=None):
|
|
378
|
+
"""Espera el siguiente evento (por ejemplo 'message') que cumpla `check`. Lanza TimeoutError."""
|
|
379
|
+
fut = asyncio.get_running_loop().create_future()
|
|
380
|
+
entry = (fut, check)
|
|
381
|
+
self._waiters.setdefault(event.removeprefix("on_"), []).append(entry)
|
|
382
|
+
try:
|
|
383
|
+
return await asyncio.wait_for(fut, timeout)
|
|
384
|
+
finally:
|
|
385
|
+
lst = self._waiters.get(event.removeprefix("on_"), [])
|
|
386
|
+
if entry in lst:
|
|
387
|
+
lst.remove(entry)
|
|
388
|
+
|
|
389
|
+
async def _run(self, name, fn, args):
|
|
390
|
+
try:
|
|
391
|
+
await fn(*args)
|
|
392
|
+
except Exception as e: # un error en tu código no tumba al bot
|
|
393
|
+
if name == "error":
|
|
394
|
+
log.error("Error en on_error: %r", e)
|
|
395
|
+
elif self._handlers.get("error"):
|
|
396
|
+
self.dispatch("error", name, e)
|
|
397
|
+
else:
|
|
398
|
+
log.exception("Error en el evento %s", name)
|
|
399
|
+
|
|
400
|
+
def _spawn(self, coro):
|
|
401
|
+
t = asyncio.create_task(coro)
|
|
402
|
+
self._tasks.add(t)
|
|
403
|
+
t.add_done_callback(self._tasks.discard)
|
|
404
|
+
|
|
405
|
+
# ---------- conexión ----------
|
|
406
|
+
async def call(self, event, data, timeout=15):
|
|
407
|
+
if not self.sio or not self.sio.connected:
|
|
408
|
+
raise MaxengerError("sin conexión con Maxenger")
|
|
409
|
+
r = await self.sio.call(event, data, namespace=NS, timeout=timeout) or {}
|
|
410
|
+
if not r.get("ok", False):
|
|
411
|
+
raise MaxengerError(r.get("error") or "falló la acción")
|
|
412
|
+
return r
|
|
413
|
+
|
|
414
|
+
async def emit(self, event, data):
|
|
415
|
+
if self.sio and self.sio.connected:
|
|
416
|
+
await self.sio.emit(event, data, namespace=NS)
|
|
417
|
+
|
|
418
|
+
async def register_commands(self, commands):
|
|
419
|
+
"""commands: [{name, description, args:[{name, required}]}]"""
|
|
420
|
+
await self.call("commands:register", {"commands": commands})
|
|
421
|
+
|
|
422
|
+
# ---------- presencia ----------
|
|
423
|
+
async def set_activity(self, title, *, kind="playing", subtitle=None):
|
|
424
|
+
"""Lo que muestra el perfil del bot: «Jugando a …». Se vuelve a poner solo si se reconecta."""
|
|
425
|
+
self._activity = {"title": title, "kind": kind, "subtitle": subtitle}
|
|
426
|
+
await self.call("presence:set", {"activity": self._activity})
|
|
427
|
+
|
|
428
|
+
async def clear_activity(self):
|
|
429
|
+
self._activity = None
|
|
430
|
+
await self.call("presence:set", {"activity": None})
|
|
431
|
+
|
|
432
|
+
# ---------- fiestas ----------
|
|
433
|
+
def get_party(self, party_id, refresh=False):
|
|
434
|
+
"""Devuelve (con await) la fiesta con miembros, roles y canales; se guarda 60 s para no pedirla de más."""
|
|
435
|
+
return self._get_party(int(party_id), refresh)
|
|
436
|
+
|
|
437
|
+
async def _get_party(self, pid, refresh):
|
|
438
|
+
old = self._parties.get(pid)
|
|
439
|
+
if old and not refresh and time.time() - old.fetched_at < 60:
|
|
440
|
+
return old
|
|
441
|
+
r = await self.call("party:get", {"party_id": pid})
|
|
442
|
+
self._parties[pid] = PartyInfo(self, r["party"])
|
|
443
|
+
return self._parties[pid]
|
|
444
|
+
|
|
445
|
+
async def fetch_message(self, conversation_id, message_id):
|
|
446
|
+
return await Channel(self, conversation_id).fetch_message(message_id)
|
|
447
|
+
|
|
448
|
+
# ---------- archivos ----------
|
|
449
|
+
async def _upload(self, f):
|
|
450
|
+
if self._http is None:
|
|
451
|
+
self._http = aiohttp.ClientSession()
|
|
452
|
+
head = {"Authorization": f"Bearer {self.token}", "Content-Type": "application/octet-stream",
|
|
453
|
+
"X-File-Name": quote(f.filename)}
|
|
454
|
+
base = self.url + "/api/bot/v1"
|
|
455
|
+
async with self._http.post(base + "/uploads", data=f.read(), headers=head) as r:
|
|
456
|
+
j = await r.json(content_type=None)
|
|
457
|
+
if r.status >= 300:
|
|
458
|
+
raise MaxengerError((j or {}).get("error") or "no se pudo subir el archivo")
|
|
459
|
+
for _ in range(60): # los archivos grandes se comprimen antes de poder enviarse
|
|
460
|
+
if j.get("status") == "ready":
|
|
461
|
+
return j["id"]
|
|
462
|
+
if j.get("status") == "failed":
|
|
463
|
+
raise MaxengerError("el archivo no se pudo procesar")
|
|
464
|
+
await asyncio.sleep(1)
|
|
465
|
+
async with self._http.get(f"{base}/uploads/{j['id']}", headers={"Authorization": head["Authorization"]}) as r:
|
|
466
|
+
j2 = await r.json(content_type=None)
|
|
467
|
+
j["status"] = j2.get("status")
|
|
468
|
+
raise MaxengerError("el archivo tardó demasiado en procesarse")
|
|
469
|
+
|
|
470
|
+
# ---------- arranque ----------
|
|
471
|
+
async def start(self):
|
|
472
|
+
self.sio = sio = socketio.AsyncClient(reconnection=True, reconnection_attempts=0,
|
|
473
|
+
reconnection_delay=2, reconnection_delay_max=60)
|
|
474
|
+
simples = (("ready", self._on_ready), ("message:new", self._on_message), ("interaction", self._on_interaction),
|
|
475
|
+
("message:edit", self._on_edit), ("message:delete", self._on_delete),
|
|
476
|
+
("disconnect", self._on_disconnect))
|
|
477
|
+
for ev, fn in simples:
|
|
478
|
+
sio.on(ev, fn, namespace=NS)
|
|
479
|
+
for ev, fn in (("reaction:add", self._on_reaction), ("reaction:remove", self._on_reaction),
|
|
480
|
+
("member:join", self._on_member), ("member:remove", self._on_member)):
|
|
481
|
+
sio.on(ev, self._con_nombre(fn, ev), namespace=NS)
|
|
482
|
+
espera = 5
|
|
483
|
+
try:
|
|
484
|
+
while True:
|
|
485
|
+
try:
|
|
486
|
+
await sio.connect(self.url, namespaces=[NS], auth={"token": self.token}, transports=["websocket"])
|
|
487
|
+
espera = 5
|
|
488
|
+
await sio.wait()
|
|
489
|
+
except asyncio.CancelledError:
|
|
490
|
+
raise
|
|
491
|
+
except Exception as e:
|
|
492
|
+
log.warning("No se pudo conectar (%s). ¿URL o token correctos? Reintento en %ss", e, espera)
|
|
493
|
+
try:
|
|
494
|
+
await sio.disconnect()
|
|
495
|
+
except Exception:
|
|
496
|
+
pass
|
|
497
|
+
await asyncio.sleep(espera)
|
|
498
|
+
espera = min(espera * 2, 120)
|
|
499
|
+
finally:
|
|
500
|
+
if self._http:
|
|
501
|
+
await self._http.close()
|
|
502
|
+
|
|
503
|
+
@staticmethod
|
|
504
|
+
def _con_nombre(fn, ev):
|
|
505
|
+
async def h(d):
|
|
506
|
+
await fn(d, ev)
|
|
507
|
+
return h
|
|
508
|
+
|
|
509
|
+
def run(self):
|
|
510
|
+
try:
|
|
511
|
+
asyncio.run(self.start())
|
|
512
|
+
except KeyboardInterrupt:
|
|
513
|
+
pass
|
|
514
|
+
|
|
515
|
+
async def close(self):
|
|
516
|
+
if self.sio:
|
|
517
|
+
await self.sio.disconnect()
|
|
518
|
+
|
|
519
|
+
# ---------- eventos del servidor ----------
|
|
520
|
+
async def _on_ready(self, d):
|
|
521
|
+
self.user = User({"id": d["user_id"], "name": "bot", "is_bot": True})
|
|
522
|
+
self.prefix = d.get("prefix")
|
|
523
|
+
self._parties.clear()
|
|
524
|
+
self._spawn(self._ready_cuando_conecte())
|
|
525
|
+
|
|
526
|
+
async def _ready_cuando_conecte(self):
|
|
527
|
+
for _ in range(100): # el aviso llega mientras termina de conectar
|
|
528
|
+
if self.sio and self.sio.connected:
|
|
529
|
+
break
|
|
530
|
+
await asyncio.sleep(0.05)
|
|
531
|
+
if self._activity:
|
|
532
|
+
try:
|
|
533
|
+
await self.call("presence:set", {"activity": self._activity})
|
|
534
|
+
except MaxengerError:
|
|
535
|
+
pass
|
|
536
|
+
self.dispatch("ready")
|
|
537
|
+
|
|
538
|
+
async def _on_disconnect(self, *a):
|
|
539
|
+
self.dispatch("disconnect")
|
|
540
|
+
|
|
541
|
+
def _party(self, pid, pname=None):
|
|
542
|
+
return Party(self, pid, pname) if pid else None
|
|
543
|
+
|
|
544
|
+
def _channel(self, conv, name=None, pid=None, pname=None):
|
|
545
|
+
return Channel(self, conv, name, self._party(pid, pname))
|
|
546
|
+
|
|
547
|
+
async def _on_message(self, d):
|
|
548
|
+
try:
|
|
549
|
+
m = d["message"]
|
|
550
|
+
mid = m["id"]
|
|
551
|
+
except Exception:
|
|
552
|
+
return
|
|
553
|
+
if mid in self._seen:
|
|
554
|
+
return
|
|
555
|
+
self._seen[mid] = 1
|
|
556
|
+
_lru(self._seen)
|
|
557
|
+
if self.user and int(m.get("sender_id") or 0) == self.user.id:
|
|
558
|
+
return
|
|
559
|
+
ch = self._channel(m["conversation_id"], d.get("channel_name"), d.get("party_id"), d.get("party_name"))
|
|
560
|
+
msg = Message(self, ch, m)
|
|
561
|
+
msg.invoked = d.get("invoked")
|
|
562
|
+
msg.voice_conversation_id = d.get("voice_conversation_id")
|
|
563
|
+
self.dispatch("message", msg)
|
|
564
|
+
|
|
565
|
+
async def _on_edit(self, d):
|
|
566
|
+
m = d.get("message") or {}
|
|
567
|
+
if not m.get("id") or (self.user and int(m.get("sender_id") or 0) == self.user.id):
|
|
568
|
+
return
|
|
569
|
+
self.dispatch("message_edit", Message(self, self._channel(m["conversation_id"], None, d.get("party_id")), m))
|
|
570
|
+
|
|
571
|
+
async def _on_delete(self, d):
|
|
572
|
+
self.dispatch("message_delete", self._channel(d["conversation_id"], None, d.get("party_id")), int(d["message_id"]))
|
|
573
|
+
|
|
574
|
+
async def _on_reaction(self, d, event):
|
|
575
|
+
user = User(d.get("user") or {"id": d.get("user_id")})
|
|
576
|
+
if self.user and user.id == self.user.id:
|
|
577
|
+
return
|
|
578
|
+
ch = self._channel(d["conversation_id"], None, d.get("party_id"))
|
|
579
|
+
r = Reaction(Message._sent(self, ch, d["message_id"], ""), d.get("emoji"), int(d.get("count") or 0))
|
|
580
|
+
self.dispatch("reaction_add" if event.endswith("add") else "reaction_remove", r, user)
|
|
581
|
+
|
|
582
|
+
async def _on_member(self, d, event):
|
|
583
|
+
pid = int(d["party_id"])
|
|
584
|
+
self._parties.pop(pid, None) # la lista de miembros cambió
|
|
585
|
+
user = User(d.get("user"))
|
|
586
|
+
if event == "member:join":
|
|
587
|
+
self.dispatch("member_join", Party(self, pid), user)
|
|
588
|
+
else:
|
|
589
|
+
self.dispatch("member_remove", Party(self, pid), user, d.get("reason") or "leave")
|
|
590
|
+
|
|
591
|
+
async def _on_interaction(self, d):
|
|
592
|
+
try:
|
|
593
|
+
ch = self._channel(d["conversation_id"], d.get("channel_name"), d.get("party_id"), d.get("party_name"))
|
|
594
|
+
user = User(d.get("user"))
|
|
595
|
+
msg = Message._sent(self, ch, d["message_id"], "") if d.get("message_id") else None
|
|
596
|
+
it = Interaction(self, d, ch, user, msg)
|
|
597
|
+
cid = d.get("custom_id")
|
|
598
|
+
if d.get("kind") == "modal":
|
|
599
|
+
modal = self._modals.pop((user.id, cid), None)
|
|
600
|
+
if not modal:
|
|
601
|
+
return
|
|
602
|
+
for f in modal.children:
|
|
603
|
+
f.value = str((d.get("values") or {}).get(f.custom_id, ""))
|
|
604
|
+
return await modal.on_submit(it)
|
|
605
|
+
popup = d.get("popup_id")
|
|
606
|
+
view = self._views.get(("p", user.id, popup)) if popup else self._views.get(("m", int(d.get("message_id") or 0)))
|
|
607
|
+
item = view.find(cid) if view else None
|
|
608
|
+
if item is None:
|
|
609
|
+
return await it.respond("⌛ Este botón ya expiró.")
|
|
610
|
+
if isinstance(item, Select):
|
|
611
|
+
item.values = [str(v) for v in d.get("values") or []]
|
|
612
|
+
if not await view.interaction_check(it):
|
|
613
|
+
return
|
|
614
|
+
await item.callback(it, item)
|
|
615
|
+
except Exception:
|
|
616
|
+
log.exception("Error en un botón o formulario")
|