pyyapper 1.8.0__tar.gz → 1.9.0__tar.gz

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.
Files changed (48) hide show
  1. {pyyapper-1.8.0/src/pyyapper.egg-info → pyyapper-1.9.0}/PKG-INFO +1 -1
  2. {pyyapper-1.8.0 → pyyapper-1.9.0}/pyproject.toml +1 -1
  3. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/__init__.py +7 -0
  4. pyyapper-1.9.0/src/pyyapper/_version.py +1 -0
  5. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/bot.py +204 -5
  6. pyyapper-1.9.0/src/pyyapper/builders.py +108 -0
  7. pyyapper-1.9.0/src/pyyapper/collectors.py +104 -0
  8. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/tasks.py +439 -327
  9. pyyapper-1.9.0/src/pyyapper/storage.py +43 -0
  10. pyyapper-1.9.0/src/pyyapper/testing.py +57 -0
  11. {pyyapper-1.8.0 → pyyapper-1.9.0/src/pyyapper.egg-info}/PKG-INFO +1 -1
  12. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper.egg-info/SOURCES.txt +4 -0
  13. pyyapper-1.8.0/src/pyyapper/_version.py +0 -1
  14. {pyyapper-1.8.0 → pyyapper-1.9.0}/LICENSE +0 -0
  15. {pyyapper-1.8.0 → pyyapper-1.9.0}/README.md +0 -0
  16. {pyyapper-1.8.0 → pyyapper-1.9.0}/setup.cfg +0 -0
  17. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/buttons.py +0 -0
  18. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/cache.py +0 -0
  19. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/commands.py +0 -0
  20. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/components_v2.py +0 -0
  21. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/config.py +0 -0
  22. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/embeds.py +0 -0
  23. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/errors.py +0 -0
  24. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/__init__.py +0 -0
  25. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/commands/__init__.py +0 -0
  26. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/commands/checks.py +0 -0
  27. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/commands/converters.py +0 -0
  28. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/commands/core.py +0 -0
  29. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/ext/commands/errors.py +0 -0
  30. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/http.py +0 -0
  31. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/i18n.py +0 -0
  32. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/metrics.py +0 -0
  33. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/models.py +0 -0
  34. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/oauth.py +0 -0
  35. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/pagination.py +0 -0
  36. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/presence.py +0 -0
  37. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/py.typed +0 -0
  38. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/voice.py +0 -0
  39. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/wait_for.py +0 -0
  40. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper/webhooks.py +0 -0
  41. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper.egg-info/dependency_links.txt +0 -0
  42. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper.egg-info/requires.txt +0 -0
  43. {pyyapper-1.8.0 → pyyapper-1.9.0}/src/pyyapper.egg-info/top_level.txt +0 -0
  44. {pyyapper-1.8.0 → pyyapper-1.9.0}/tests/test_ext_commands.py +0 -0
  45. {pyyapper-1.8.0 → pyyapper-1.9.0}/tests/test_oauth.py +0 -0
  46. {pyyapper-1.8.0 → pyyapper-1.9.0}/tests/test_smoke.py +0 -0
  47. {pyyapper-1.8.0 → pyyapper-1.9.0}/tests/test_tasks.py +0 -0
  48. {pyyapper-1.8.0 → pyyapper-1.9.0}/tests/test_webhooks.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyyapper
3
- Version: 1.8.0
3
+ Version: 1.9.0
4
4
  Summary: An intuitive, async Python library for the Yapper bot API.
5
5
  Author: PyYapper contributors
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pyyapper"
7
- version = "1.8.0"
7
+ version = "1.9.0"
8
8
  description = "An intuitive, async Python library for the Yapper bot API."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -29,6 +29,10 @@ from .config import load_config, load_env_file, get_token
29
29
  from .i18n import Translator, t as translate
30
30
  from .metrics import Metrics
31
31
  from .ext import commands, tasks
32
+ from .testing import MockBot, MockContext, MockInteraction
33
+ from .builders import MessageBuilder, EmbedTemplate, PermissionOverwrite
34
+ from .storage import JSONStore
35
+ from .collectors import collect_messages, collect_reactions, collect_clicks
32
36
  from . import components_v2 as components_v2
33
37
  from .components_v2 import (
34
38
  IS_COMPONENTS_V2, TextDisplay, Thumbnail, Section, MediaGallery, MediaGalleryItem,
@@ -57,6 +61,9 @@ __all__ = [
57
61
  "text", "thumbnail", "section", "gallery", "separator", "file_display",
58
62
  "container", "action_row", "row", "normalize_components",
59
63
  "Cog", "Command", "Group",
64
+ "MockBot", "MockContext", "MockInteraction",
65
+ "MessageBuilder", "EmbedTemplate", "PermissionOverwrite",
66
+ "JSONStore", "collect_messages", "collect_reactions", "collect_clicks",
60
67
  "__version__",
61
68
  ]
62
69
 
@@ -0,0 +1 @@
1
+ __version__ = "1.9.0"
@@ -92,6 +92,124 @@ class Context:
92
92
  async def send_layout(self, components: Any, **opts: Any) -> Any:
93
93
  return await self._bot.send_layout(self.channel_id, components, **opts)
94
94
 
95
+ # ---- QOL shortcuts ----
96
+ async def pin(self) -> Any:
97
+ return await self._bot.pin(self.channel_id, self.id)
98
+
99
+ async def unpin(self) -> Any:
100
+ return await self._bot.unpin(self.channel_id, self.id)
101
+
102
+ async def react(self, emoji: str) -> Any:
103
+ return await self._bot.react(self.channel_id, self.id, emoji)
104
+
105
+ async def delete(self) -> Any:
106
+ return await self._bot.delete(self.channel_id, self.id)
107
+
108
+ async def edit(self, content: Any = None, **opts: Any) -> Any:
109
+ return await self._bot.edit(self.channel_id, self.id, content, **opts)
110
+
111
+ async def confirm(self, question: str, *, timeout: float = 30.0,
112
+ yes: str = "Yes", no: str = "No") -> bool:
113
+ from .buttons import Button, Row
114
+ token = __import__("uuid").uuid4().hex
115
+ yid, nid = f"{token}:yes", f"{token}:no"
116
+ msg = await self._bot.send(self.channel_id, question, components=[
117
+ Row(Button.success(yes, yid), Button.danger(no, nid))
118
+ ])
119
+ entry = {"match": None, "fn": None}
120
+ fut = asyncio.get_event_loop().create_future() if False else None
121
+ loop = asyncio.get_running_loop()
122
+ future = loop.create_future()
123
+
124
+ async def handler(ic):
125
+ if getattr(ic, "custom_id", "") not in (yid, nid):
126
+ return
127
+ if getattr(ic, "user_id", None) != self.author_id:
128
+ try:
129
+ await ic.ephemeral("Not your prompt.")
130
+ except Exception:
131
+ pass
132
+ return
133
+ result = ic.custom_id == yid
134
+ if not future.done():
135
+ future.set_result(result)
136
+ try:
137
+ await ic.update(components=[])
138
+ except Exception:
139
+ pass
140
+
141
+ entry = {"match": __import__("re").compile(f"^{token}:"), "fn": handler}
142
+ self._bot.buttons.append(entry)
143
+ try:
144
+ res = await asyncio.wait_for(future, timeout=timeout)
145
+ return bool(res)
146
+ except asyncio.TimeoutError:
147
+ try:
148
+ await self._bot.edit(self.channel_id, (msg.get("id") if isinstance(msg, dict) else getattr(msg, "id", None)), components=[])
149
+ except Exception:
150
+ pass
151
+ return False
152
+ finally:
153
+ try:
154
+ self._bot.buttons.remove(entry)
155
+ except ValueError:
156
+ pass
157
+
158
+ async def create_thread(self, name: str, *, message_id: Any = None, content: str = "",
159
+ auto_archive: int = 1440) -> Any:
160
+ mid = message_id if message_id is not None else self.id
161
+ return await self._bot.create_thread(self.channel_id, name=name, message_id=mid, content=content)
162
+
163
+ async def poll(self, question: str, options: list, *, duration: float = 60.0,
164
+ channel_id: Any = None) -> dict:
165
+ from .buttons import Button, Row
166
+ ch = channel_id if channel_id is not None else self.channel_id
167
+ token = __import__("uuid").uuid4().hex
168
+ counts = {i: 0 for i in range(len(options))}
169
+ voted: set = set()
170
+ btns = [Button.primary(str(opt)[:80], f"{token}:{i}") for i, opt in enumerate(options)]
171
+ # chunk into rows of 5
172
+ rows = []
173
+ for i in range(0, len(btns), 5):
174
+ rows.append(Row(*btns[i:i+5]))
175
+ msg = await self._bot.send(ch, question, components=rows)
176
+ mid = msg.get("id") if isinstance(msg, dict) else getattr(msg, "id", None)
177
+ entry = None
178
+
179
+ async def handler(ic):
180
+ nonlocal counts
181
+ if not str(getattr(ic, "custom_id", "")).startswith(token + ":"):
182
+ return
183
+ if getattr(ic, "user_id", None) in voted:
184
+ try:
185
+ await ic.ephemeral("You already voted.")
186
+ except Exception:
187
+ pass
188
+ return
189
+ idx = int(str(ic.custom_id).split(":")[-1])
190
+ voted.add(getattr(ic, "user_id", None))
191
+ counts[idx] += 1
192
+ tally = "\n".join(f"{opt}: {counts[i]}" for i, opt in enumerate(options))
193
+ try:
194
+ await ic.update(content=f"{question}\n\n{tally}")
195
+ except Exception:
196
+ pass
197
+
198
+ entry = {"match": __import__("re").compile(f"^{token}:"), "fn": handler}
199
+ self._bot.buttons.append(entry)
200
+ await asyncio.sleep(duration)
201
+ try:
202
+ self._bot.buttons.remove(entry)
203
+ except ValueError:
204
+ pass
205
+ tally = "\n".join(f"{opt}: {counts[i]}" for i, opt in enumerate(options))
206
+ winner = max(counts, key=lambda k: counts[k]) if counts else 0
207
+ try:
208
+ await self._bot.edit(ch, mid, content=f"{question}\n\n{tally}\n\nWinner: {options[winner]}")
209
+ except Exception:
210
+ pass
211
+ return {"counts": counts, "winner": options[winner], "total": len(voted)}
212
+
95
213
  def __repr__(self) -> str:
96
214
  return f"Context(id={self.id!r}, author={self.author!r})"
97
215
 
@@ -191,6 +309,8 @@ class Bot:
191
309
  max_age: Optional[int] = None,
192
310
  cache_ttl: float = 0.0,
193
311
  config: Any = None,
312
+ debug: bool = False,
313
+ dry_run: bool = False,
194
314
  ) -> None:
195
315
  if isinstance(config, (str,)):
196
316
  from .config import load_config, get_token
@@ -208,6 +328,8 @@ class Bot:
208
328
  self.base_url = base_url
209
329
  self.ignore_bots = bool(ignore_bots)
210
330
  self.max_age = max_age
331
+ self.debug = bool(debug)
332
+ self.dry_run = bool(dry_run)
211
333
  self._presence = None
212
334
  self._cache = TTLCache(default_ttl=cache_ttl)
213
335
  self.cache_ttl = cache_ttl
@@ -278,7 +400,7 @@ class Bot:
278
400
  # ------------------------------------------------------------------ #
279
401
  # Registration
280
402
  # ------------------------------------------------------------------ #
281
- def on(self, event: str, fn: Optional[Callable] = None) -> Any:
403
+ def on(self, event: str, fn: Optional[Callable] = None, *, filter: Optional[Callable] = None) -> Any:
282
404
  """Register an event handler.
283
405
 
284
406
  Can be used as a decorator::
@@ -293,12 +415,34 @@ class Bot:
293
415
  """
294
416
  if event not in EVENTS:
295
417
  raise ValueError(f"Unknown event {event!r}. Valid: {sorted(EVENTS)}")
418
+ def _wrap(f: Callable) -> Callable:
419
+ if filter is None:
420
+ return f
421
+ orig = f
422
+
423
+ async def wrapped(payload):
424
+ try:
425
+ ok = filter(payload)
426
+ if asyncio.iscoroutine(ok):
427
+ ok = await ok
428
+ except Exception:
429
+ ok = False
430
+ if not ok:
431
+ return
432
+ if asyncio.iscoroutinefunction(orig):
433
+ await orig(payload)
434
+ else:
435
+ orig(payload)
436
+
437
+ wrapped.__name__ = getattr(orig, "__name__", "wrapped")
438
+ return wrapped
439
+
296
440
  if fn is None:
297
441
  def decorator(f: Callable) -> Callable:
298
- self.handlers.setdefault(event, []).append(f)
442
+ self.handlers.setdefault(event, []).append(_wrap(f))
299
443
  return f
300
444
  return decorator
301
- self.handlers.setdefault(event, []).append(fn)
445
+ self.handlers.setdefault(event, []).append(_wrap(fn))
302
446
  return fn
303
447
 
304
448
  def event(self, fn: Optional[Callable] = None) -> Any:
@@ -1004,6 +1148,14 @@ class Bot:
1004
1148
  cid = await self.dm(user_id)
1005
1149
  return await self.send(cid, content, **opts)
1006
1150
 
1151
+ async def webhook_send(self, url: str, content: Any = "", **opts: Any) -> Any:
1152
+ from .webhooks import Webhook
1153
+ wh = Webhook.from_url(url)
1154
+ try:
1155
+ return await wh.send(content, **opts)
1156
+ finally:
1157
+ await wh.close()
1158
+
1007
1159
  # ------------------------------------------------------------------ #
1008
1160
  # Lifecycle
1009
1161
  # ------------------------------------------------------------------ #
@@ -1150,6 +1302,34 @@ class Bot:
1150
1302
  """Drop cached read results. ``key=None`` clears everything."""
1151
1303
  self._cache.invalidate(key)
1152
1304
 
1305
+ def commands_info(self) -> list[dict[str, Any]]:
1306
+ out = []
1307
+ for name, info in self.commands.items():
1308
+ fn = info.get("fn") if isinstance(info, dict) else None
1309
+ out.append({
1310
+ "name": name,
1311
+ "description": info.get("description", "") if isinstance(info, dict) else "",
1312
+ "checks": getattr(fn, "checks", None) or getattr(fn, "_checks", None),
1313
+ "cooldown": getattr(fn, "cooldown", None) or getattr(fn, "_cooldown", None),
1314
+ "aliases": getattr(fn, "aliases", None),
1315
+ })
1316
+ return out
1317
+
1318
+ def inspect_command(self, name: str) -> Optional[dict[str, Any]]:
1319
+ info = self.commands.get(name)
1320
+ if not info:
1321
+ return None
1322
+ fn = info.get("fn") if isinstance(info, dict) else None
1323
+ return {
1324
+ "name": name,
1325
+ "description": info.get("description", "") if isinstance(info, dict) else "",
1326
+ "callback": fn,
1327
+ "checks": getattr(fn, "checks", None) or getattr(fn, "_checks", None),
1328
+ "cooldown": getattr(fn, "cooldown", None) or getattr(fn, "_cooldown", None),
1329
+ "aliases": getattr(fn, "aliases", None),
1330
+ "cog": getattr(fn, "cog", None),
1331
+ }
1332
+
1153
1333
  async def send_many(self, channel_id: Any, contents: Any, *, concurrency: int = 5, **opts: Any) -> list:
1154
1334
  sem = asyncio.Semaphore(max(1, int(concurrency)))
1155
1335
 
@@ -1159,6 +1339,18 @@ class Bot:
1159
1339
 
1160
1340
  return list(await asyncio.gather(*(_one(c) for c in (contents or [])), return_exceptions=True))
1161
1341
 
1342
+ def collect_messages(self, channel_id: Any, *, check: Any = None, timeout: float = 30.0, max_messages: int = 0) -> Any:
1343
+ from .collectors import MessageCollector
1344
+ return MessageCollector(self, channel_id, check=check, timeout=timeout, max_messages=max_messages)
1345
+
1346
+ def collect_reactions(self, message_id: Any, *, check: Any = None, timeout: float = 30.0, max_reactions: int = 0) -> Any:
1347
+ from .collectors import ReactionCollector
1348
+ return ReactionCollector(self, message_id, check=check, timeout=timeout, max_reactions=max_reactions)
1349
+
1350
+ def collect_clicks(self, message_id: Any, *, check: Any = None, timeout: float = 30.0, max_clicks: int = 0) -> Any:
1351
+ from .collectors import ButtonCollector
1352
+ return ButtonCollector(self, message_id, check=check, timeout=timeout, max_clicks=max_clicks)
1353
+
1162
1354
  # ------------------------------------------------------------------ #
1163
1355
  # Internals
1164
1356
  # ------------------------------------------------------------------ #
@@ -1218,8 +1410,15 @@ class Bot:
1218
1410
  args = (m.group(3) or "").strip()
1219
1411
  # If command_for is set and points at another bot, don't handle.
1220
1412
  command_for = data.get("command_for")
1221
- if command_for and self.me is not None and command_for != getattr(self.me, "id", None):
1222
- name = None
1413
+ if command_for and self.me is not None:
1414
+ cf = command_for[0] if isinstance(command_for, (list, tuple)) and command_for else command_for
1415
+ if cf != getattr(self.me, "id", None):
1416
+ name = None
1417
+ # Strip a trailing bot mention used for disambiguation (/cmd @bot).
1418
+ if args:
1419
+ me_id = getattr(self.me, "id", None) if self.me is not None else None
1420
+ if me_id:
1421
+ args = re.sub(rf"\s*<@!?{re.escape(str(me_id))}>\s*$", "", str(args)).strip()
1223
1422
  if name and name in self.commands:
1224
1423
  ctx.command = name
1225
1424
  ctx.args = args or ""
@@ -0,0 +1,108 @@
1
+ """Fluent builders and templates for PyYapper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ from .embeds import Embed
8
+ from .buttons import Button, Row
9
+
10
+
11
+ class MessageBuilder:
12
+ """Fluent message builder."""
13
+
14
+ def __init__(self) -> None:
15
+ self._content: str = ""
16
+ self._embeds: list[Any] = []
17
+ self._components: list[Any] = []
18
+ self._reply_to: Any = None
19
+
20
+ def content(self, text: Any) -> "MessageBuilder":
21
+ self._content = "" if text is None else str(text)
22
+ return self
23
+
24
+ def embed(self, e: Any) -> "MessageBuilder":
25
+ self._embeds.append(e)
26
+ return self
27
+
28
+ def embeds(self, es: list[Any]) -> "MessageBuilder":
29
+ self._embeds.extend(es or [])
30
+ return self
31
+
32
+ def row(self, *buttons: Any) -> "MessageBuilder":
33
+ self._components.append(Row(*buttons))
34
+ return self
35
+
36
+ def components(self, cs: list[Any]) -> "MessageBuilder":
37
+ self._components.extend(cs or [])
38
+ return self
39
+
40
+ def reply_to(self, mid: Any) -> "MessageBuilder":
41
+ self._reply_to = mid
42
+ return self
43
+
44
+ async def send(self, bot: Any, channel_id: Any, **opts: Any) -> Any:
45
+ kw = dict(opts)
46
+ if self._reply_to is not None:
47
+ kw["reply_to"] = self._reply_to
48
+ if self._embeds:
49
+ kw["embeds"] = self._embeds
50
+ if self._components:
51
+ kw["components"] = self._components
52
+ return await bot.send(channel_id, self._content, **kw)
53
+
54
+ async def reply(self, ctx: Any, **opts: Any) -> Any:
55
+ kw = dict(opts)
56
+ if self._embeds:
57
+ kw["embeds"] = self._embeds
58
+ if self._components:
59
+ kw["components"] = self._components
60
+ return await ctx.reply(self._content, **kw)
61
+
62
+
63
+ class EmbedTemplate:
64
+ """Registry of named embed templates."""
65
+
66
+ _templates: dict[str, Any] = {}
67
+
68
+ @classmethod
69
+ def register(cls, name: str, factory: Any) -> None:
70
+ cls._templates[name] = factory
71
+
72
+ @classmethod
73
+ def render(cls, name: str, **kw: Any) -> Embed:
74
+ factory = cls._templates.get(name)
75
+ if factory is None:
76
+ raise KeyError(f"Unknown embed template: {name}")
77
+ if callable(factory):
78
+ return factory(**kw)
79
+ # factory may be an Embed already
80
+ return factory
81
+
82
+ @classmethod
83
+ def quick(cls, title: str, description: str = "", color: Any = None) -> Embed:
84
+ e = Embed().title(title)
85
+ if description:
86
+ e.description(description)
87
+ if color is not None:
88
+ e.color(color)
89
+ return e
90
+
91
+
92
+ class PermissionOverwrite:
93
+ """Fluent permission overwrite builder (for channel edits)."""
94
+
95
+ def __init__(self) -> None:
96
+ self.allow: list[str] = []
97
+ self.deny: list[str] = []
98
+
99
+ def allow(self, *perms: str) -> "PermissionOverwrite":
100
+ self.allow.extend(perms)
101
+ return self
102
+
103
+ def deny(self, *perms: str) -> "PermissionOverwrite":
104
+ self.deny.extend(perms)
105
+ return self
106
+
107
+ def to_dict(self) -> dict[str, Any]:
108
+ return {"allow": self.allow, "deny": self.deny}
@@ -0,0 +1,104 @@
1
+ """Collectors for PyYapper: gather messages, reactions, or button clicks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from typing import Any, Callable, Optional
7
+
8
+
9
+ class MessageCollector:
10
+ def __init__(self, bot: Any, channel_id: Any, *, check: Optional[Callable[[Any], bool]] = None,
11
+ timeout: float = 30.0, max_messages: int = 0) -> None:
12
+ self.bot = bot
13
+ self.channel_id = channel_id
14
+ self.check = check or (lambda m: True)
15
+ self.timeout = timeout
16
+ self.max_messages = max_messages
17
+ self.collected: list[Any] = []
18
+ self._done = asyncio.Event()
19
+ self._token = None
20
+
21
+ async def run(self) -> list[Any]:
22
+ # Use wait_for on message events filtered by channel.
23
+ deadline = asyncio.get_event_loop().time() + self.timeout if hasattr(asyncio.get_event_loop(), "time") else None
24
+ end = asyncio.get_event_loop().time() + self.timeout
25
+ while asyncio.get_event_loop().time() < end:
26
+ try:
27
+ remaining = end - asyncio.get_event_loop().time()
28
+ if remaining <= 0:
29
+ break
30
+ msg = await self.bot.wait_for("message", check=lambda m: (
31
+ getattr(m, "channel_id", None) == self.channel_id and self.check(m)
32
+ ), timeout=remaining)
33
+ self.collected.append(msg)
34
+ if self.max_messages and len(self.collected) >= self.max_messages:
35
+ break
36
+ except asyncio.TimeoutError:
37
+ break
38
+ return self.collected
39
+
40
+
41
+ class ReactionCollector:
42
+ def __init__(self, bot: Any, message_id: Any, *, check=None, timeout: float = 30.0, max_reactions: int = 0):
43
+ self.bot = bot
44
+ self.message_id = message_id
45
+ self.check = check or (lambda r: True)
46
+ self.timeout = timeout
47
+ self.max_reactions = max_reactions
48
+ self.collected: list[Any] = []
49
+
50
+ async def run(self) -> list[Any]:
51
+ end = asyncio.get_event_loop().time() + self.timeout
52
+ while asyncio.get_event_loop().time() < end:
53
+ try:
54
+ remaining = end - asyncio.get_event_loop().time()
55
+ if remaining <= 0:
56
+ break
57
+ ev = await self.bot.wait_for("reaction_add", check=lambda e: (
58
+ getattr(e, "message_id", None) == self.message_id and self.check(e)
59
+ ), timeout=remaining)
60
+ self.collected.append(ev)
61
+ if self.max_reactions and len(self.collected) >= self.max_reactions:
62
+ break
63
+ except asyncio.TimeoutError:
64
+ break
65
+ return self.collected
66
+
67
+
68
+ class ButtonCollector:
69
+ def __init__(self, bot: Any, message_id: Any, *, check=None, timeout: float = 30.0, max_clicks: int = 0):
70
+ self.bot = bot
71
+ self.message_id = message_id
72
+ self.check = check or (lambda i: True)
73
+ self.timeout = timeout
74
+ self.max_clicks = max_clicks
75
+ self.collected: list[Any] = []
76
+
77
+ async def run(self) -> list[Any]:
78
+ end = asyncio.get_event_loop().time() + self.timeout
79
+ while asyncio.get_event_loop().time() < end:
80
+ try:
81
+ remaining = end - asyncio.get_event_loop().time()
82
+ if remaining <= 0:
83
+ break
84
+ ic = await self.bot.wait_for("interaction", check=lambda i: (
85
+ getattr(i, "message_id", None) == self.message_id and self.check(i)
86
+ ), timeout=remaining)
87
+ self.collected.append(ic)
88
+ if self.max_clicks and len(self.collected) >= self.max_clicks:
89
+ break
90
+ except asyncio.TimeoutError:
91
+ break
92
+ return self.collected
93
+
94
+
95
+ def collect_messages(bot, channel_id, *, check=None, timeout=30.0, max_messages=0):
96
+ return MessageCollector(bot, channel_id, check=check, timeout=timeout, max_messages=max_messages)
97
+
98
+
99
+ def collect_reactions(bot, message_id, *, check=None, timeout=30.0, max_reactions=0):
100
+ return ReactionCollector(bot, message_id, check=check, timeout=timeout, max_reactions=max_reactions)
101
+
102
+
103
+ def collect_clicks(bot, message_id, *, check=None, timeout=30.0, max_clicks=0):
104
+ return ButtonCollector(bot, message_id, check=check, timeout=timeout, max_clicks=max_clicks)