necropy 0.1.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.
- necropy/__init__.py +31 -0
- necropy/bot.py +345 -0
- necropy/components.py +190 -0
- necropy/exceptions.py +47 -0
- necropy/http.py +309 -0
- necropy/models.py +288 -0
- necropy/utils.py +36 -0
- necropy/webhook.py +81 -0
- necropy-0.1.0.dist-info/METADATA +314 -0
- necropy-0.1.0.dist-info/RECORD +13 -0
- necropy-0.1.0.dist-info/WHEEL +5 -0
- necropy-0.1.0.dist-info/licenses/LICENSE +21 -0
- necropy-0.1.0.dist-info/top_level.txt +1 -0
necropy/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""necropy: Python tools for building bots on Necro."""
|
|
2
|
+
|
|
3
|
+
from .bot import Bot
|
|
4
|
+
from .components import ActionRow, Button, ButtonStyle, Embed, SelectMenu, SelectOption
|
|
5
|
+
from .exceptions import ClientClosedError, GatewayException, HTTPException, NecroError
|
|
6
|
+
from .http import API_PREFIX, API_URL, RESTClient
|
|
7
|
+
from .models import Interaction, Message, User
|
|
8
|
+
from .webhook import Webhook
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"API_PREFIX",
|
|
12
|
+
"API_URL",
|
|
13
|
+
"ActionRow",
|
|
14
|
+
"Bot",
|
|
15
|
+
"Button",
|
|
16
|
+
"ButtonStyle",
|
|
17
|
+
"ClientClosedError",
|
|
18
|
+
"Embed",
|
|
19
|
+
"GatewayException",
|
|
20
|
+
"HTTPException",
|
|
21
|
+
"Interaction",
|
|
22
|
+
"Message",
|
|
23
|
+
"NecroError",
|
|
24
|
+
"RESTClient",
|
|
25
|
+
"SelectMenu",
|
|
26
|
+
"SelectOption",
|
|
27
|
+
"User",
|
|
28
|
+
"Webhook",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
__version__ = "0.1.0"
|
necropy/bot.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
"""High-level synchronous bot framework with Socket.IO gateway support."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import socketio
|
|
12
|
+
|
|
13
|
+
from .http import API_URL, RESTClient, FileInput
|
|
14
|
+
from .models import Interaction, Message
|
|
15
|
+
from .utils import to_jsonable
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger("necropy")
|
|
18
|
+
GATEWAY_NAMESPACE = "/bots"
|
|
19
|
+
|
|
20
|
+
_EVENT_ALIASES = {
|
|
21
|
+
"on_ready": "ready",
|
|
22
|
+
"on_server_create": "serverCreate",
|
|
23
|
+
"on_server_delete": "serverDelete",
|
|
24
|
+
"on_message": "messageCreate",
|
|
25
|
+
"on_message_create": "messageCreate",
|
|
26
|
+
"on_message_update": "messageUpdate",
|
|
27
|
+
"on_message_delete": "messageDelete",
|
|
28
|
+
"on_member_join": "memberJoin",
|
|
29
|
+
"on_member_leave": "memberLeave",
|
|
30
|
+
"on_interaction": "interactionCreate",
|
|
31
|
+
"on_interaction_create": "interactionCreate",
|
|
32
|
+
"on_disconnect": "disconnect",
|
|
33
|
+
"on_connect_error": "connect_error",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Bot:
|
|
38
|
+
"""Build and run a Necro bot.
|
|
39
|
+
|
|
40
|
+
``Bot`` uses a synchronous ``python-socketio`` client. Event handlers may
|
|
41
|
+
be normal functions or ``async def`` coroutines. The REST API is synchronous.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
token: str,
|
|
47
|
+
*,
|
|
48
|
+
base_url: str = API_URL,
|
|
49
|
+
request_timeout: float = 15.0,
|
|
50
|
+
reconnection: bool = True,
|
|
51
|
+
logger: bool = False,
|
|
52
|
+
engineio_logger: bool = False,
|
|
53
|
+
) -> None:
|
|
54
|
+
self.token = token
|
|
55
|
+
self.base_url = base_url.rstrip("/")
|
|
56
|
+
self.rest = RESTClient(token, base_url=self.base_url, timeout=request_timeout)
|
|
57
|
+
self.gateway = socketio.Client(
|
|
58
|
+
reconnection=reconnection,
|
|
59
|
+
logger=logger,
|
|
60
|
+
engineio_logger=engineio_logger,
|
|
61
|
+
)
|
|
62
|
+
self._event_handlers: dict[str, list[Callable[..., Any]]] = {}
|
|
63
|
+
self._commands: dict[tuple[str | None, str], dict[str, Any]] = {}
|
|
64
|
+
self._command_callbacks: dict[tuple[str | None, str], Callable[..., Any]] = {}
|
|
65
|
+
self._component_callbacks: dict[str, Callable[..., Any]] = {}
|
|
66
|
+
self._register_gateway_handlers()
|
|
67
|
+
|
|
68
|
+
def _register_gateway_handlers(self) -> None:
|
|
69
|
+
events = (
|
|
70
|
+
"ready",
|
|
71
|
+
"serverCreate",
|
|
72
|
+
"serverDelete",
|
|
73
|
+
"messageCreate",
|
|
74
|
+
"messageUpdate",
|
|
75
|
+
"messageDelete",
|
|
76
|
+
"memberJoin",
|
|
77
|
+
"memberLeave",
|
|
78
|
+
"interactionCreate",
|
|
79
|
+
"disconnect",
|
|
80
|
+
"connect_error",
|
|
81
|
+
)
|
|
82
|
+
for event_name in events:
|
|
83
|
+
self.gateway.on(
|
|
84
|
+
event_name,
|
|
85
|
+
handler=self._make_gateway_handler(event_name),
|
|
86
|
+
namespace=GATEWAY_NAMESPACE,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
def _make_gateway_handler(self, event_name: str) -> Callable[..., None]:
|
|
90
|
+
def handler(data: Any = None, *args: Any) -> None:
|
|
91
|
+
if event_name == "messageCreate" and isinstance(data, dict):
|
|
92
|
+
raw_message = data.get("message", data)
|
|
93
|
+
self._dispatch_event(event_name, Message(self, raw_message))
|
|
94
|
+
return
|
|
95
|
+
if event_name == "messageUpdate" and isinstance(data, dict):
|
|
96
|
+
raw_message = data.get("message", data)
|
|
97
|
+
self._dispatch_event(event_name, Message(self, raw_message))
|
|
98
|
+
return
|
|
99
|
+
if event_name == "interactionCreate" and isinstance(data, dict):
|
|
100
|
+
interaction = Interaction(self, data)
|
|
101
|
+
self._dispatch_event(event_name, interaction)
|
|
102
|
+
self._dispatch_interaction(interaction)
|
|
103
|
+
return
|
|
104
|
+
self._dispatch_event(event_name, data, *args)
|
|
105
|
+
|
|
106
|
+
return handler
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _invoke(callback: Callable[..., Any], *args: Any) -> None:
|
|
110
|
+
try:
|
|
111
|
+
result = callback(*args)
|
|
112
|
+
if inspect.isawaitable(result):
|
|
113
|
+
try:
|
|
114
|
+
loop = asyncio.get_running_loop()
|
|
115
|
+
except RuntimeError:
|
|
116
|
+
asyncio.run(result)
|
|
117
|
+
else:
|
|
118
|
+
loop.create_task(result)
|
|
119
|
+
except Exception:
|
|
120
|
+
log.exception("Unhandled exception in bot callback %r", callback)
|
|
121
|
+
|
|
122
|
+
def _dispatch_event(self, event_name: str, *args: Any) -> None:
|
|
123
|
+
for callback in self._event_handlers.get(event_name, []):
|
|
124
|
+
self._invoke(callback, *args)
|
|
125
|
+
|
|
126
|
+
def _dispatch_interaction(self, interaction: Interaction) -> None:
|
|
127
|
+
if interaction.type == "command" and interaction.command_name:
|
|
128
|
+
name = interaction.command_name
|
|
129
|
+
server_id = str(interaction.server_id) if interaction.server_id is not None else None
|
|
130
|
+
callback = self._command_callbacks.get((server_id, name)) or self._command_callbacks.get((None, name))
|
|
131
|
+
if callback:
|
|
132
|
+
self._invoke(callback, interaction)
|
|
133
|
+
elif interaction.type == "component" and interaction.custom_id:
|
|
134
|
+
callback = self._component_callbacks.get(interaction.custom_id)
|
|
135
|
+
if callback:
|
|
136
|
+
self._invoke(callback, interaction)
|
|
137
|
+
|
|
138
|
+
def event(self, callback: Callable[..., Any] | None = None):
|
|
139
|
+
"""Register a gateway event using names such as ``on_message``.
|
|
140
|
+
|
|
141
|
+
Example::
|
|
142
|
+
|
|
143
|
+
@bot.event
|
|
144
|
+
def on_message(message):
|
|
145
|
+
...
|
|
146
|
+
"""
|
|
147
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
148
|
+
event_name = _EVENT_ALIASES.get(func.__name__, func.__name__)
|
|
149
|
+
self._event_handlers.setdefault(event_name, []).append(func)
|
|
150
|
+
return func
|
|
151
|
+
|
|
152
|
+
return decorator(callback) if callback is not None else decorator
|
|
153
|
+
|
|
154
|
+
def listen(self, event_name: str):
|
|
155
|
+
"""Register a handler for a raw Necro gateway event name."""
|
|
156
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
157
|
+
self._event_handlers.setdefault(event_name, []).append(func)
|
|
158
|
+
return func
|
|
159
|
+
|
|
160
|
+
return decorator
|
|
161
|
+
|
|
162
|
+
def command(
|
|
163
|
+
self,
|
|
164
|
+
name: str | None = None,
|
|
165
|
+
*,
|
|
166
|
+
description: str | None = None,
|
|
167
|
+
options: list[dict[str, Any]] | None = None,
|
|
168
|
+
server_id: int | str | None = None,
|
|
169
|
+
):
|
|
170
|
+
"""Register a slash command callback and its API definition.
|
|
171
|
+
|
|
172
|
+
Use :meth:`sync_commands` to publish registered commands to Necro.
|
|
173
|
+
The callback receives one :class:`Interaction` argument.
|
|
174
|
+
"""
|
|
175
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
176
|
+
command_name = (name or func.__name__).lower()
|
|
177
|
+
command_description = description or (inspect.getdoc(func) or f"Run {command_name}").splitlines()[0]
|
|
178
|
+
scope = str(server_id) if server_id is not None else None
|
|
179
|
+
definition: dict[str, Any] = {
|
|
180
|
+
"name": command_name,
|
|
181
|
+
"description": command_description,
|
|
182
|
+
}
|
|
183
|
+
if options:
|
|
184
|
+
definition["options"] = to_jsonable(options)
|
|
185
|
+
key = (scope, command_name)
|
|
186
|
+
self._commands[key] = definition
|
|
187
|
+
self._command_callbacks[key] = func
|
|
188
|
+
return func
|
|
189
|
+
|
|
190
|
+
return decorator
|
|
191
|
+
|
|
192
|
+
def component(self, custom_id: str):
|
|
193
|
+
"""Register a callback for a button or select-menu ``custom_id``."""
|
|
194
|
+
if not custom_id:
|
|
195
|
+
raise ValueError("custom_id cannot be empty")
|
|
196
|
+
|
|
197
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
198
|
+
self._component_callbacks[custom_id] = func
|
|
199
|
+
return func
|
|
200
|
+
|
|
201
|
+
return decorator
|
|
202
|
+
|
|
203
|
+
def command_definitions(self, server_id: int | str | None = None) -> list[dict[str, Any]]:
|
|
204
|
+
scope = str(server_id) if server_id is not None else None
|
|
205
|
+
return [dict(definition) for (item_scope, _), definition in self._commands.items() if item_scope == scope]
|
|
206
|
+
|
|
207
|
+
def sync_commands(self, *, server_id: int | str | None = None, replace: bool = True) -> list[dict[str, Any]]:
|
|
208
|
+
"""Publish registered commands (global by default, or for one server)."""
|
|
209
|
+
definitions = self.command_definitions(server_id)
|
|
210
|
+
if replace:
|
|
211
|
+
return self.rest.replace_commands(definitions, server_id=server_id)
|
|
212
|
+
return [self.rest.create_command(item, server_id=server_id) for item in definitions]
|
|
213
|
+
|
|
214
|
+
def list_commands(self, server_id: int | str | None = None) -> list[dict[str, Any]]:
|
|
215
|
+
"""Fetch registered global commands, or commands for one server."""
|
|
216
|
+
return self.rest.list_commands(server_id=server_id)
|
|
217
|
+
|
|
218
|
+
def delete_command(self, command_id: int | str, server_id: int | str | None = None) -> None:
|
|
219
|
+
"""Delete one registered command."""
|
|
220
|
+
self.rest.delete_command(command_id, server_id=server_id)
|
|
221
|
+
|
|
222
|
+
# High-level REST wrappers
|
|
223
|
+
def get_me(self) -> dict[str, Any]:
|
|
224
|
+
return self.rest.get_me()
|
|
225
|
+
|
|
226
|
+
def get_gateway(self) -> dict[str, Any]:
|
|
227
|
+
return self.rest.get_gateway()
|
|
228
|
+
|
|
229
|
+
def list_servers(self, *, after: int | str | None = None, limit: int = 100) -> list[dict[str, Any]]:
|
|
230
|
+
return self.rest.list_servers(after=after, limit=limit)
|
|
231
|
+
|
|
232
|
+
def get_server(self, server_id: int | str) -> dict[str, Any]:
|
|
233
|
+
return self.rest.get_server(server_id)
|
|
234
|
+
|
|
235
|
+
def leave_server(self, server_id: int | str) -> None:
|
|
236
|
+
self.rest.leave_server(server_id)
|
|
237
|
+
|
|
238
|
+
def list_channels(self, server_id: int | str) -> list[dict[str, Any]]:
|
|
239
|
+
return self.rest.list_channels(server_id)
|
|
240
|
+
|
|
241
|
+
def list_roles(self, server_id: int | str) -> list[dict[str, Any]]:
|
|
242
|
+
return self.rest.list_roles(server_id)
|
|
243
|
+
|
|
244
|
+
def list_members(
|
|
245
|
+
self, server_id: int | str, *, after: int | str | None = None, limit: int = 100
|
|
246
|
+
) -> list[dict[str, Any]]:
|
|
247
|
+
return self.rest.list_members(server_id, after=after, limit=limit)
|
|
248
|
+
|
|
249
|
+
def get_member(self, server_id: int | str, user_id: int | str) -> dict[str, Any]:
|
|
250
|
+
return self.rest.get_member(server_id, user_id)
|
|
251
|
+
|
|
252
|
+
def add_role(self, server_id: int | str, user_id: int | str, role_id: int | str) -> None:
|
|
253
|
+
self.rest.add_role(server_id, user_id, role_id)
|
|
254
|
+
|
|
255
|
+
def remove_role(self, server_id: int | str, user_id: int | str, role_id: int | str) -> None:
|
|
256
|
+
self.rest.remove_role(server_id, user_id, role_id)
|
|
257
|
+
|
|
258
|
+
def get_channel(self, channel_id: int | str) -> dict[str, Any]:
|
|
259
|
+
return self.rest.get_channel(channel_id)
|
|
260
|
+
|
|
261
|
+
def get_messages(
|
|
262
|
+
self,
|
|
263
|
+
channel_id: int | str,
|
|
264
|
+
*,
|
|
265
|
+
limit: int = 50,
|
|
266
|
+
before: int | str | None = None,
|
|
267
|
+
after: int | str | None = None,
|
|
268
|
+
) -> list[Message]:
|
|
269
|
+
raw = self.rest.get_messages(channel_id, limit=limit, before=before, after=after)
|
|
270
|
+
return [Message(self, item) for item in raw]
|
|
271
|
+
|
|
272
|
+
def get_message(self, channel_id: int | str, message_id: int | str) -> Message:
|
|
273
|
+
return Message(self, self.rest.get_message(channel_id, message_id))
|
|
274
|
+
|
|
275
|
+
def send_message(
|
|
276
|
+
self,
|
|
277
|
+
channel_id: int | str,
|
|
278
|
+
content: str | None = None,
|
|
279
|
+
*,
|
|
280
|
+
embeds: list[Any] | None = None,
|
|
281
|
+
components: list[Any] | None = None,
|
|
282
|
+
reply_to: int | str | None = None,
|
|
283
|
+
files: list[FileInput] | None = None,
|
|
284
|
+
**extra: Any,
|
|
285
|
+
) -> Message:
|
|
286
|
+
data = self.rest.send_message(
|
|
287
|
+
channel_id,
|
|
288
|
+
content=content,
|
|
289
|
+
embeds=embeds,
|
|
290
|
+
components=components,
|
|
291
|
+
reply_to=reply_to,
|
|
292
|
+
files=files,
|
|
293
|
+
**extra,
|
|
294
|
+
)
|
|
295
|
+
if not isinstance(data, dict):
|
|
296
|
+
raise RuntimeError("Necro did not return a message object")
|
|
297
|
+
return Message(self, data)
|
|
298
|
+
|
|
299
|
+
def edit_message(
|
|
300
|
+
self,
|
|
301
|
+
channel_id: int | str,
|
|
302
|
+
message_id: int | str,
|
|
303
|
+
content: str | None = None,
|
|
304
|
+
*,
|
|
305
|
+
embeds: list[Any] | None = None,
|
|
306
|
+
components: list[Any] | None = None,
|
|
307
|
+
**extra: Any,
|
|
308
|
+
) -> Message:
|
|
309
|
+
return Message(
|
|
310
|
+
self,
|
|
311
|
+
self.rest.edit_message(
|
|
312
|
+
channel_id, message_id, content=content, embeds=embeds, components=components, **extra
|
|
313
|
+
),
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
def delete_message(self, channel_id: int | str, message_id: int | str) -> None:
|
|
317
|
+
self.rest.delete_message(channel_id, message_id)
|
|
318
|
+
|
|
319
|
+
def connect(self) -> None:
|
|
320
|
+
"""Connect to the Necro Socket.IO gateway without blocking."""
|
|
321
|
+
self.gateway.connect(
|
|
322
|
+
self.base_url,
|
|
323
|
+
namespaces=[GATEWAY_NAMESPACE],
|
|
324
|
+
auth={"token": f"Bot {self.token}"},
|
|
325
|
+
transports=["websocket"],
|
|
326
|
+
socketio_path="socket.io",
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
def run(self) -> None:
|
|
330
|
+
"""Connect to Necro and block until disconnected."""
|
|
331
|
+
self.connect()
|
|
332
|
+
log.info("necropy gateway connected; waiting for events")
|
|
333
|
+
self.gateway.wait()
|
|
334
|
+
|
|
335
|
+
def close(self) -> None:
|
|
336
|
+
"""Disconnect from the gateway and close the HTTP session."""
|
|
337
|
+
if self.gateway.connected:
|
|
338
|
+
self.gateway.disconnect()
|
|
339
|
+
self.rest.close()
|
|
340
|
+
|
|
341
|
+
def __enter__(self) -> Bot:
|
|
342
|
+
return self
|
|
343
|
+
|
|
344
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
345
|
+
self.close()
|
necropy/components.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Builders for Necro embeds and message components."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from enum import IntEnum
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ButtonStyle(IntEnum):
|
|
11
|
+
PRIMARY = 1
|
|
12
|
+
SECONDARY = 2
|
|
13
|
+
SUCCESS = 3
|
|
14
|
+
DANGER = 4
|
|
15
|
+
LINK = 5
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Embed:
|
|
19
|
+
"""A fluent builder for a Necro embed/card."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
*,
|
|
24
|
+
title: str | None = None,
|
|
25
|
+
description: str | None = None,
|
|
26
|
+
url: str | None = None,
|
|
27
|
+
color: int | str | None = None,
|
|
28
|
+
timestamp: datetime | str | None = None,
|
|
29
|
+
) -> None:
|
|
30
|
+
self._data: dict[str, Any] = {}
|
|
31
|
+
for key, value in {
|
|
32
|
+
"title": title,
|
|
33
|
+
"description": description,
|
|
34
|
+
"url": url,
|
|
35
|
+
"color": color,
|
|
36
|
+
"timestamp": timestamp,
|
|
37
|
+
}.items():
|
|
38
|
+
if value is not None:
|
|
39
|
+
self._data[key] = value.isoformat() if isinstance(value, datetime) else value
|
|
40
|
+
|
|
41
|
+
def set_author(self, name: str, *, url: str | None = None, icon_url: str | None = None) -> Embed:
|
|
42
|
+
self._data["author"] = {k: v for k, v in {"name": name, "url": url, "icon_url": icon_url}.items() if v is not None}
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def add_field(self, name: str, value: str, *, inline: bool = False) -> Embed:
|
|
46
|
+
self._data.setdefault("fields", []).append({"name": name, "value": value, "inline": inline})
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
def set_footer(self, text: str, *, icon_url: str | None = None) -> Embed:
|
|
50
|
+
self._data["footer"] = {k: v for k, v in {"text": text, "icon_url": icon_url}.items() if v is not None}
|
|
51
|
+
return self
|
|
52
|
+
|
|
53
|
+
def set_thumbnail(self, url: str) -> Embed:
|
|
54
|
+
self._data["thumbnail"] = {"url": url}
|
|
55
|
+
return self
|
|
56
|
+
|
|
57
|
+
def set_image(self, url: str) -> Embed:
|
|
58
|
+
self._data["image"] = {"url": url}
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict[str, Any]:
|
|
62
|
+
return dict(self._data)
|
|
63
|
+
|
|
64
|
+
def __repr__(self) -> str:
|
|
65
|
+
return f"Embed(title={self._data.get('title')!r})"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Button:
|
|
69
|
+
"""A clickable button or URL button."""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
label: str | None = None,
|
|
74
|
+
*,
|
|
75
|
+
custom_id: str | None = None,
|
|
76
|
+
style: ButtonStyle | int = ButtonStyle.PRIMARY,
|
|
77
|
+
url: str | None = None,
|
|
78
|
+
emoji: str | dict[str, Any] | None = None,
|
|
79
|
+
disabled: bool = False,
|
|
80
|
+
) -> None:
|
|
81
|
+
self.label = label
|
|
82
|
+
self.custom_id = custom_id
|
|
83
|
+
self.style = int(style)
|
|
84
|
+
self.url = url
|
|
85
|
+
self.emoji = emoji
|
|
86
|
+
self.disabled = disabled
|
|
87
|
+
if self.style == ButtonStyle.LINK and not url:
|
|
88
|
+
raise ValueError("Link buttons require a URL")
|
|
89
|
+
if self.style == ButtonStyle.LINK and custom_id is not None:
|
|
90
|
+
raise ValueError("Link buttons cannot have custom_id")
|
|
91
|
+
if self.style != ButtonStyle.LINK and not custom_id:
|
|
92
|
+
raise ValueError("Interactive buttons require custom_id")
|
|
93
|
+
if self.style != ButtonStyle.LINK and url is not None:
|
|
94
|
+
raise ValueError("Only link buttons can have a URL")
|
|
95
|
+
if not label and not emoji:
|
|
96
|
+
raise ValueError("A button needs a label or emoji")
|
|
97
|
+
|
|
98
|
+
def to_dict(self) -> dict[str, Any]:
|
|
99
|
+
data: dict[str, Any] = {"type": 2, "style": self.style, "disabled": self.disabled}
|
|
100
|
+
for key, value in {
|
|
101
|
+
"label": self.label,
|
|
102
|
+
"custom_id": self.custom_id,
|
|
103
|
+
"url": self.url,
|
|
104
|
+
"emoji": self.emoji,
|
|
105
|
+
}.items():
|
|
106
|
+
if value is not None:
|
|
107
|
+
data[key] = value
|
|
108
|
+
return data
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class SelectOption:
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
label: str,
|
|
115
|
+
value: str,
|
|
116
|
+
*,
|
|
117
|
+
description: str | None = None,
|
|
118
|
+
emoji: str | dict[str, Any] | None = None,
|
|
119
|
+
default: bool = False,
|
|
120
|
+
) -> None:
|
|
121
|
+
self.label = label
|
|
122
|
+
self.value = value
|
|
123
|
+
self.description = description
|
|
124
|
+
self.emoji = emoji
|
|
125
|
+
self.default = default
|
|
126
|
+
|
|
127
|
+
def to_dict(self) -> dict[str, Any]:
|
|
128
|
+
return {
|
|
129
|
+
key: value
|
|
130
|
+
for key, value in {
|
|
131
|
+
"label": self.label,
|
|
132
|
+
"value": self.value,
|
|
133
|
+
"description": self.description,
|
|
134
|
+
"emoji": self.emoji,
|
|
135
|
+
"default": self.default,
|
|
136
|
+
}.items()
|
|
137
|
+
if value is not None
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class SelectMenu:
|
|
142
|
+
"""A string select menu (other select-menu types are not supported by Necro yet)."""
|
|
143
|
+
|
|
144
|
+
def __init__(
|
|
145
|
+
self,
|
|
146
|
+
custom_id: str,
|
|
147
|
+
options: list[SelectOption | dict[str, Any]],
|
|
148
|
+
*,
|
|
149
|
+
placeholder: str | None = None,
|
|
150
|
+
min_values: int = 1,
|
|
151
|
+
max_values: int = 1,
|
|
152
|
+
disabled: bool = False,
|
|
153
|
+
) -> None:
|
|
154
|
+
if not 1 <= len(options) <= 25:
|
|
155
|
+
raise ValueError("Select menus need between 1 and 25 options")
|
|
156
|
+
self.custom_id = custom_id
|
|
157
|
+
self.options = options
|
|
158
|
+
self.placeholder = placeholder
|
|
159
|
+
self.min_values = min_values
|
|
160
|
+
self.max_values = max_values
|
|
161
|
+
self.disabled = disabled
|
|
162
|
+
|
|
163
|
+
def to_dict(self) -> dict[str, Any]:
|
|
164
|
+
return {
|
|
165
|
+
"type": 3,
|
|
166
|
+
"custom_id": self.custom_id,
|
|
167
|
+
"options": [option.to_dict() if hasattr(option, "to_dict") else option for option in self.options],
|
|
168
|
+
"min_values": self.min_values,
|
|
169
|
+
"max_values": self.max_values,
|
|
170
|
+
"disabled": self.disabled,
|
|
171
|
+
**({"placeholder": self.placeholder} if self.placeholder is not None else {}),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class ActionRow:
|
|
176
|
+
"""A row containing up to five buttons, or exactly one select menu."""
|
|
177
|
+
|
|
178
|
+
def __init__(self, *components: Button | SelectMenu | dict[str, Any]) -> None:
|
|
179
|
+
if not 1 <= len(components) <= 5:
|
|
180
|
+
raise ValueError("An action row needs between 1 and 5 components")
|
|
181
|
+
menus = [item for item in components if isinstance(item, SelectMenu)]
|
|
182
|
+
if menus and len(components) != 1:
|
|
183
|
+
raise ValueError("A select menu must be alone in its action row")
|
|
184
|
+
self.components = list(components)
|
|
185
|
+
|
|
186
|
+
def to_dict(self) -> dict[str, Any]:
|
|
187
|
+
return {
|
|
188
|
+
"type": 1,
|
|
189
|
+
"components": [item.to_dict() if hasattr(item, "to_dict") else item for item in self.components],
|
|
190
|
+
}
|
necropy/exceptions.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Exceptions raised by necropy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NecroError(Exception):
|
|
9
|
+
"""Base exception for errors raised by necropy."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HTTPException(NecroError):
|
|
13
|
+
"""An unsuccessful response returned by the Necro REST API."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
status: int,
|
|
18
|
+
message: str = "Request failed",
|
|
19
|
+
code: str | None = None,
|
|
20
|
+
*,
|
|
21
|
+
retry_after: float | None = None,
|
|
22
|
+
response_data: Any = None,
|
|
23
|
+
) -> None:
|
|
24
|
+
self.status = status
|
|
25
|
+
self.status_code = status
|
|
26
|
+
self.message = message
|
|
27
|
+
self.code = code
|
|
28
|
+
self.retry_after = retry_after
|
|
29
|
+
self.response_data = response_data
|
|
30
|
+
details = f"HTTP {status}"
|
|
31
|
+
if code:
|
|
32
|
+
details += f" {code}"
|
|
33
|
+
details += f": {message}"
|
|
34
|
+
super().__init__(details)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class GatewayException(NecroError):
|
|
38
|
+
"""An error raised while connecting to the Socket.IO gateway."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, message: str, code: str | None = None) -> None:
|
|
41
|
+
self.code = code
|
|
42
|
+
self.message = message
|
|
43
|
+
super().__init__(f"{code}: {message}" if code else message)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ClientClosedError(NecroError):
|
|
47
|
+
"""Raised when trying to use a closed client."""
|