disunity 0.1.17__tar.gz → 0.3.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.
- disunity-0.3.0/PKG-INFO +239 -0
- disunity-0.3.0/README.md +190 -0
- disunity-0.3.0/pyproject.toml +58 -0
- {disunity-0.1.17 → disunity-0.3.0}/setup.cfg +4 -4
- disunity-0.3.0/src/disunity/__init__.py +21 -0
- disunity-0.3.0/src/disunity/cache.py +58 -0
- {disunity-0.1.17 → disunity-0.3.0}/src/disunity/embed.py +10 -3
- disunity-0.3.0/src/disunity/errors.py +67 -0
- disunity-0.3.0/src/disunity/identifiers.py +164 -0
- disunity-0.3.0/src/disunity/models/__init__.py +71 -0
- disunity-0.3.0/src/disunity/models/_v2.py +145 -0
- {disunity-0.1.17 → disunity-0.3.0}/src/disunity/models/attachment.py +4 -2
- disunity-0.3.0/src/disunity/models/channel.py +21 -0
- disunity-0.3.0/src/disunity/models/components.py +1048 -0
- disunity-0.3.0/src/disunity/models/context.py +533 -0
- disunity-0.3.0/src/disunity/models/interaction.py +134 -0
- disunity-0.3.0/src/disunity/models/member.py +32 -0
- disunity-0.3.0/src/disunity/models/message.py +172 -0
- disunity-0.3.0/src/disunity/models/resolved_attachment.py +19 -0
- disunity-0.3.0/src/disunity/models/role.py +21 -0
- disunity-0.3.0/src/disunity/models/user.py +35 -0
- disunity-0.3.0/src/disunity/package.py +166 -0
- disunity-0.3.0/src/disunity/server.py +556 -0
- disunity-0.3.0/src/disunity/utils.py +134 -0
- disunity-0.3.0/src/disunity.egg-info/PKG-INFO +239 -0
- {disunity-0.1.17 → disunity-0.3.0}/src/disunity.egg-info/SOURCES.txt +22 -1
- disunity-0.3.0/src/disunity.egg-info/requires.txt +8 -0
- disunity-0.3.0/tests/test_autocomplete.py +43 -0
- disunity-0.3.0/tests/test_commands.py +44 -0
- disunity-0.3.0/tests/test_components.py +105 -0
- disunity-0.3.0/tests/test_components_v2.py +619 -0
- disunity-0.3.0/tests/test_custom_id.py +97 -0
- disunity-0.3.0/tests/test_error_message.py +220 -0
- disunity-0.3.0/tests/test_followup.py +88 -0
- disunity-0.3.0/tests/test_hooks.py +95 -0
- disunity-0.3.0/tests/test_http.py +212 -0
- disunity-0.3.0/tests/test_models.py +168 -0
- disunity-0.3.0/tests/test_original.py +148 -0
- disunity-0.3.0/tests/test_resolved.py +137 -0
- disunity-0.3.0/tests/test_resolved_models.py +63 -0
- disunity-0.3.0/tests/test_send_v2.py +651 -0
- disunity-0.3.0/tests/test_subcommands.py +64 -0
- disunity-0.3.0/tests/test_transport.py +44 -0
- disunity-0.1.17/PKG-INFO +0 -74
- disunity-0.1.17/README.md +0 -60
- disunity-0.1.17/pyproject.toml +0 -29
- disunity-0.1.17/src/disunity/__init__.py +0 -6
- disunity-0.1.17/src/disunity/cache.py +0 -41
- disunity-0.1.17/src/disunity/errors.py +0 -27
- disunity-0.1.17/src/disunity/identifiers.py +0 -178
- disunity-0.1.17/src/disunity/models/__init__.py +0 -16
- disunity-0.1.17/src/disunity/models/components.py +0 -243
- disunity-0.1.17/src/disunity/models/context.py +0 -150
- disunity-0.1.17/src/disunity/models/interaction.py +0 -63
- disunity-0.1.17/src/disunity/models/member.py +0 -22
- disunity-0.1.17/src/disunity/models/message.py +0 -129
- disunity-0.1.17/src/disunity/models/user.py +0 -24
- disunity-0.1.17/src/disunity/package.py +0 -205
- disunity-0.1.17/src/disunity/server.py +0 -379
- disunity-0.1.17/src/disunity/utils.py +0 -42
- disunity-0.1.17/src/disunity.egg-info/PKG-INFO +0 -74
- {disunity-0.1.17 → disunity-0.3.0}/LICENSE +0 -0
- {disunity-0.1.17 → disunity-0.3.0}/src/disunity.egg-info/dependency_links.txt +0 -0
- {disunity-0.1.17 → disunity-0.3.0}/src/disunity.egg-info/top_level.txt +0 -0
disunity-0.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: disunity
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python framework for Discord interactions using a web server
|
|
5
|
+
Author: Tadeo Murillo
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2022 Duxle
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/murillotadeo/disunity
|
|
29
|
+
Project-URL: Bug Tracker, https://github.com/murillotadeo/disunity/issues
|
|
30
|
+
Classifier: Programming Language :: Python :: 3
|
|
31
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
32
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
33
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Framework :: AsyncIO
|
|
38
|
+
Requires-Python: >=3.10
|
|
39
|
+
Description-Content-Type: text/markdown
|
|
40
|
+
License-File: LICENSE
|
|
41
|
+
Requires-Dist: quart>=0.20
|
|
42
|
+
Requires-Dist: aiohttp>=3.9
|
|
43
|
+
Requires-Dist: PyNaCl>=1.5
|
|
44
|
+
Provides-Extra: dev
|
|
45
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
46
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
|
|
47
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
48
|
+
Dynamic: license-file
|
|
49
|
+
|
|
50
|
+
# disunity
|
|
51
|
+
|
|
52
|
+
Python framework for Discord interactions using a web server (Quart). Version 0.3.0, Python >= 3.10.
|
|
53
|
+
|
|
54
|
+
# Installation
|
|
55
|
+
|
|
56
|
+
`pip install disunity`
|
|
57
|
+
|
|
58
|
+
Dependencies (`quart`, `aiohttp`, `PyNaCl`) are installed automatically.
|
|
59
|
+
|
|
60
|
+
# Introduction to Disunity
|
|
61
|
+
|
|
62
|
+
The constructor needs the application's public key, client secret, client id and (optionally) a bot token:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import disunity
|
|
66
|
+
|
|
67
|
+
server = disunity.DisunityServer(
|
|
68
|
+
public_key="<APPLICATION_PUBLIC_KEY>",
|
|
69
|
+
client_secret="<CLIENT_SECRET>",
|
|
70
|
+
client_id=123456789012345678,
|
|
71
|
+
bot_token=None, # only needed for non-interaction API calls
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
server.run() # development server
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Using packages (use an `async` hook: sync `before_serving` hooks run in a worker thread):
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import pathlib
|
|
82
|
+
import disunity
|
|
83
|
+
|
|
84
|
+
server = disunity.DisunityServer(public_key="...", client_secret="...", client_id=123456789012345678)
|
|
85
|
+
|
|
86
|
+
@server.before_serving
|
|
87
|
+
async def load_packages():
|
|
88
|
+
for f in pathlib.Path("packages").glob("*.py"):
|
|
89
|
+
server.load_package(f"{f.parent}.{f.stem}")
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
# Running in production
|
|
93
|
+
|
|
94
|
+
`DisunityServer` is an ASGI app. Serve it with an ASGI server, for example:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
hypercorn main:server
|
|
98
|
+
uvicorn main:server
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
# Setting up a package
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from disunity import package
|
|
105
|
+
|
|
106
|
+
class FirstPackage(package.Package):
|
|
107
|
+
def __init__(self, app):
|
|
108
|
+
self.app = app
|
|
109
|
+
|
|
110
|
+
@package.Package.command("ping")
|
|
111
|
+
async def ping(self, ctx):
|
|
112
|
+
return await ctx.callback("Pong!")
|
|
113
|
+
|
|
114
|
+
def setup(app):
|
|
115
|
+
app.register_package(FirstPackage(app))
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
# Components V2
|
|
119
|
+
|
|
120
|
+
Discord's Components V2 lets a message be built from layout components (text, sections, images, files, separators, containers) instead of `content` and `embeds`. Passing a layout component to `components` enables it automatically (the `IS_COMPONENTS_V2` flag is set for you); such a message can't have `content` or `embeds`:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from disunity.models import (
|
|
124
|
+
ActionRow, Button, ButtonStyles, Container, Section, Separator, TextDisplay, Thumbnail,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
@package.Package.command("poll")
|
|
128
|
+
async def poll(self, ctx):
|
|
129
|
+
return await ctx.callback(components=[
|
|
130
|
+
Container([
|
|
131
|
+
Section(["## Favourite color?", "Vote below."],
|
|
132
|
+
Thumbnail("https://example.com/palette.png", description="Color palette")),
|
|
133
|
+
Separator(),
|
|
134
|
+
TextDisplay("Votes close in 10 minutes."),
|
|
135
|
+
ActionRow([
|
|
136
|
+
Button("vote-blue", "Blue", ButtonStyles.PRIMARY),
|
|
137
|
+
Button("vote-red", "Red", ButtonStyles.DANGER),
|
|
138
|
+
]),
|
|
139
|
+
], accent_color=0x5865F2),
|
|
140
|
+
])
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
See [docs/components.md](docs/components.md) and [docs/gotchas.md](docs/gotchas.md) (#13, including what was verified on Discord and what is still unverified).
|
|
144
|
+
|
|
145
|
+
# Documentation
|
|
146
|
+
|
|
147
|
+
Agent-oriented reference docs live in [docs/](docs/index.md).
|
|
148
|
+
|
|
149
|
+
# Tests
|
|
150
|
+
|
|
151
|
+
```
|
|
152
|
+
pip install -e .[dev]
|
|
153
|
+
pytest
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
# Disclaimer
|
|
157
|
+
|
|
158
|
+
This will require that you already have hosting service for the server to run on as well as a domain to host the server on.
|
|
159
|
+
|
|
160
|
+
# Side note
|
|
161
|
+
|
|
162
|
+
The server will receive interactions at the `/interactions` endpoint of your server, e.g. `https://example.com/interactions`. Once you run the server, put that URL into the "Interactions Endpoint URL" of your app in the Discord developer portal.
|
|
163
|
+
|
|
164
|
+
# Releasing
|
|
165
|
+
|
|
166
|
+
1. Bump `__version__` in `src/disunity/__init__.py` and update the changelog below.
|
|
167
|
+
2. Commit, then tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
|
|
168
|
+
|
|
169
|
+
Pushing a `v*` tag runs `.github/workflows/publish.yml`, which checks that the tag matches `__version__`, runs the tests, builds the package and publishes it to PyPI using trusted publishing (no token).
|
|
170
|
+
|
|
171
|
+
One-time setup:
|
|
172
|
+
- On PyPI, add a trusted publisher for this project: GitHub owner `murillotadeo`, repository `disunity`, workflow `publish.yml`, environment `pypi`.
|
|
173
|
+
- In the GitHub repository settings, create an environment named `pypi`.
|
|
174
|
+
|
|
175
|
+
# Changelog
|
|
176
|
+
|
|
177
|
+
## 0.3.0
|
|
178
|
+
|
|
179
|
+
Nothing breaking: legacy messages, components and modals produce exactly the same payloads as in 0.2.0. Components V2 was tested live on Discord (2026-11-29) except for what `docs/gotchas.md` #13 lists as unverified.
|
|
180
|
+
|
|
181
|
+
### Added
|
|
182
|
+
- Components V2 layout components (`disunity.models`): `TextDisplay`, `Section`, `Thumbnail`, `MediaGallery` / `MediaGalleryItem`, `File`, `Separator` / `SeparatorSpacing`, `Container`, all with an optional `id`. Media accepts a URL or an `Attachment` (sent as `attachment://<filename>`); `File` only supports `attachment://`.
|
|
183
|
+
- Native selects `UserSelect`, `RoleSelect`, `MentionableSelect`, `ChannelSelect` (with `channel_types`) and `SelectDefaultValue`; `ComponentTypes` constants.
|
|
184
|
+
- `Label` (modals only) wrapping a `UserTextInput`, `SelectMenu` or any of the new selects; `Modal` now accepts `Label` and `TextDisplay`.
|
|
185
|
+
- `components_v2` parameter on `ctx.callback`, `ctx.followup`, `ctx.edit_original`, `Message.edit_as_webhook` and `Message.edit_as_bot`. The V2 flag is set automatically when a layout component is passed, and kept on messages that already have it.
|
|
186
|
+
- `Message.flags` and `Message.is_components_v2`.
|
|
187
|
+
- `ctx.modal_select_values(custom_id)` to read selects submitted inside a modal `Label`.
|
|
188
|
+
- `utils.MessageFlags.SUPPRESS_EMBEDS` (4) and `IS_COMPONENTS_V2` (`1 << 15`).
|
|
189
|
+
- `errors.ComponentsV2Error` (a `DisunityError` and a `ValueError`) for invalid layouts and for mixing V2 with `content` / `embeds`.
|
|
190
|
+
- Optional new arguments on existing classes: `SelectMenuOption` / `MenuOption` `default`; `SelectMenu` `min_values`, `max_values`, `required`; `UserTextInput` `label` may be `None` when wrapped in a `Label`.
|
|
191
|
+
|
|
192
|
+
### Changed
|
|
193
|
+
- A message may hold at most 40 components in total, nested ones included (raises `ComponentsV2Error`; media gallery items don't count), and a `Container` takes 1 to 40 children.
|
|
194
|
+
- `ctx.edit_original` clears `content` and `embeds` (sends null / `[]`) while it doesn't know the original is V2, so it can turn a legacy original into a V2 message; it now starts from the V2 flag of the component's own message.
|
|
195
|
+
- V2 messages can't have `content` or `embeds`, can't be deferred with type 5 (defer, then `edit_original`), and `ctx.callback` can't upload files (use `followup` / `edit_original` for `attachment://` references).
|
|
196
|
+
- `Modal` with a `Label` or `TextDisplay` validates 1 to 5 components, a title of at most 45 characters and 4000 characters of text in total; modals with only `UserTextInput`s are validated as before.
|
|
197
|
+
- Docs: Components V2 section in `docs/components.md`, `docs/gotchas.md` #13, and updated `context`, `models`, `errors`, `utils`, `index`.
|
|
198
|
+
|
|
199
|
+
## 0.2.0
|
|
200
|
+
|
|
201
|
+
### Fixed
|
|
202
|
+
- `requires_ephemeral=True` on acked commands and sub commands no longer crashes (response `{"type": 5, "data": {"flags": 64}}`).
|
|
203
|
+
- Several `@Package.sub` decorators for the same base command and group no longer overwrite each other.
|
|
204
|
+
- Component `timeout` is now enforced for `requires_ack=True` components and modal submits; timed-out interactions get an ephemeral "This component has timed out." and the handler does not run. The timeout is measured from the component message's creation time.
|
|
205
|
+
- Modal submits honor `requires_ack` (type 6 when the modal came from a message, else type 5).
|
|
206
|
+
- `UserTextInput` `placeholder`, `min_length` and `value` can be combined.
|
|
207
|
+
- Link buttons no longer send `custom_id`; select option values are sent as `str`; empty descriptions/placeholders are omitted.
|
|
208
|
+
- `Message.edit_as_webhook` / `edit_as_bot` send only the provided fields; `edit_as_webhook` raises `ExpiredInteractionError` on 10015/50027 and re-raises other `HTTPRequestError`s instead of ignoring them.
|
|
209
|
+
- `Member.server_avatar_url` uses the guild avatar URL.
|
|
210
|
+
- `User.mention` is `<@id>`, `User.username` drops `#0`, default avatar uses the correct formula for new usernames.
|
|
211
|
+
- `check_user()` returns `False` when there is no author; `invoked_by` on components comes from `message.interaction_metadata` (fallback `message.interaction`).
|
|
212
|
+
- `global_after_interaction` also runs when the handler raised; `error_handler` is always called inside the `except` block and also receives errors from `global_after_interaction`.
|
|
213
|
+
- Background tasks are referenced and their exceptions logged.
|
|
214
|
+
|
|
215
|
+
### Added
|
|
216
|
+
- `ctx.options` works for autocomplete; `ctx.focused_option`, `ctx.sub_command`, `ctx.sub_command_group`, `ctx.guild_id`, `ctx.created_at`, `ctx.app`.
|
|
217
|
+
- `ctx.modal_value(custom_id)`; `modal_values` is flattened (Label type 18 and action rows).
|
|
218
|
+
- `allowed_mentions` parameter on `ctx.callback` / `ctx.followup`; `User.display_name`.
|
|
219
|
+
- Autocomplete choices are truncated to 25.
|
|
220
|
+
- Errors: base class `DisunityError`, `HTTPRequestError.status/.code/.data`, `ResponseDecodeError`.
|
|
221
|
+
- `make_https_request`: shared aiohttp session (closed `after_serving`), 429 retry honoring `retry_after` (`max_rate_limit_retries`, `max_rate_limit_wait`), async `auth()`.
|
|
222
|
+
- `ctx.followup` retries Unknown Webhook (10015) up to 3 times shortly after deferring and logs timing; the server warns when the initial response is late (`late_response_warning`).
|
|
223
|
+
- `ValueError` for component names containing `-`; warnings for duplicate registrations.
|
|
224
|
+
- `ctx.edit_original(...)` (only the given fields are sent, `components=[]` clears), `ctx.get_original()`, `ctx.delete_original()`; they share the Unknown Webhook retry with `followup`.
|
|
225
|
+
- Resolved option helpers: `ctx.get_user/get_member/get_role/get_channel/get_attachment(option_name)`, `ctx.target_id` and `ctx.get_target_user/get_target_member/get_target_message()` for context menu commands.
|
|
226
|
+
- Models `Role`, `Channel`, `ResolvedAttachment` (in `disunity.models`) and `utils.ChannelTypes`.
|
|
227
|
+
- `DisunityServer.error_message`: when a handler raises and `error_handler` swallows the exception, the user gets an ephemeral "Something went wrong" message (response or followup); set it to `None` to disable.
|
|
228
|
+
- `make_custom_id(name, *args)` / `utils.parse_custom_id`, `utils.CUSTOM_ID_SEPARATOR` / `CUSTOM_ID_MAX_LENGTH`, and `ctx.component_name` / `ctx.custom_args`; routing uses `parse_custom_id`.
|
|
229
|
+
|
|
230
|
+
### Changed
|
|
231
|
+
- Runtime dependencies are real `[project].dependencies`: `quart>=0.20`, `aiohttp>=3.9`, `PyNaCl>=1.5`. Python >= 3.10.
|
|
232
|
+
- Version lives in `disunity.__version__` (`utils.__version__` re-exports it).
|
|
233
|
+
- `quart.flask_patch` is gone: use `from quart import request`.
|
|
234
|
+
- No auth headers are sent to non-Discord hosts when `headers=None`.
|
|
235
|
+
- `global_check` returning a non-`True`, non-dict value acks components silently (type 6); commands still get PONG.
|
|
236
|
+
|
|
237
|
+
### Removed
|
|
238
|
+
- `requests` dependency.
|
|
239
|
+
- `override_checks` parameter of `make_https_request`.
|
disunity-0.3.0/README.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# disunity
|
|
2
|
+
|
|
3
|
+
Python framework for Discord interactions using a web server (Quart). Version 0.3.0, Python >= 3.10.
|
|
4
|
+
|
|
5
|
+
# Installation
|
|
6
|
+
|
|
7
|
+
`pip install disunity`
|
|
8
|
+
|
|
9
|
+
Dependencies (`quart`, `aiohttp`, `PyNaCl`) are installed automatically.
|
|
10
|
+
|
|
11
|
+
# Introduction to Disunity
|
|
12
|
+
|
|
13
|
+
The constructor needs the application's public key, client secret, client id and (optionally) a bot token:
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import disunity
|
|
17
|
+
|
|
18
|
+
server = disunity.DisunityServer(
|
|
19
|
+
public_key="<APPLICATION_PUBLIC_KEY>",
|
|
20
|
+
client_secret="<CLIENT_SECRET>",
|
|
21
|
+
client_id=123456789012345678,
|
|
22
|
+
bot_token=None, # only needed for non-interaction API calls
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
if __name__ == "__main__":
|
|
26
|
+
server.run() # development server
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Using packages (use an `async` hook: sync `before_serving` hooks run in a worker thread):
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import pathlib
|
|
33
|
+
import disunity
|
|
34
|
+
|
|
35
|
+
server = disunity.DisunityServer(public_key="...", client_secret="...", client_id=123456789012345678)
|
|
36
|
+
|
|
37
|
+
@server.before_serving
|
|
38
|
+
async def load_packages():
|
|
39
|
+
for f in pathlib.Path("packages").glob("*.py"):
|
|
40
|
+
server.load_package(f"{f.parent}.{f.stem}")
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
# Running in production
|
|
44
|
+
|
|
45
|
+
`DisunityServer` is an ASGI app. Serve it with an ASGI server, for example:
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
hypercorn main:server
|
|
49
|
+
uvicorn main:server
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
# Setting up a package
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from disunity import package
|
|
56
|
+
|
|
57
|
+
class FirstPackage(package.Package):
|
|
58
|
+
def __init__(self, app):
|
|
59
|
+
self.app = app
|
|
60
|
+
|
|
61
|
+
@package.Package.command("ping")
|
|
62
|
+
async def ping(self, ctx):
|
|
63
|
+
return await ctx.callback("Pong!")
|
|
64
|
+
|
|
65
|
+
def setup(app):
|
|
66
|
+
app.register_package(FirstPackage(app))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
# Components V2
|
|
70
|
+
|
|
71
|
+
Discord's Components V2 lets a message be built from layout components (text, sections, images, files, separators, containers) instead of `content` and `embeds`. Passing a layout component to `components` enables it automatically (the `IS_COMPONENTS_V2` flag is set for you); such a message can't have `content` or `embeds`:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from disunity.models import (
|
|
75
|
+
ActionRow, Button, ButtonStyles, Container, Section, Separator, TextDisplay, Thumbnail,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@package.Package.command("poll")
|
|
79
|
+
async def poll(self, ctx):
|
|
80
|
+
return await ctx.callback(components=[
|
|
81
|
+
Container([
|
|
82
|
+
Section(["## Favourite color?", "Vote below."],
|
|
83
|
+
Thumbnail("https://example.com/palette.png", description="Color palette")),
|
|
84
|
+
Separator(),
|
|
85
|
+
TextDisplay("Votes close in 10 minutes."),
|
|
86
|
+
ActionRow([
|
|
87
|
+
Button("vote-blue", "Blue", ButtonStyles.PRIMARY),
|
|
88
|
+
Button("vote-red", "Red", ButtonStyles.DANGER),
|
|
89
|
+
]),
|
|
90
|
+
], accent_color=0x5865F2),
|
|
91
|
+
])
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
See [docs/components.md](docs/components.md) and [docs/gotchas.md](docs/gotchas.md) (#13, including what was verified on Discord and what is still unverified).
|
|
95
|
+
|
|
96
|
+
# Documentation
|
|
97
|
+
|
|
98
|
+
Agent-oriented reference docs live in [docs/](docs/index.md).
|
|
99
|
+
|
|
100
|
+
# Tests
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
pip install -e .[dev]
|
|
104
|
+
pytest
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
# Disclaimer
|
|
108
|
+
|
|
109
|
+
This will require that you already have hosting service for the server to run on as well as a domain to host the server on.
|
|
110
|
+
|
|
111
|
+
# Side note
|
|
112
|
+
|
|
113
|
+
The server will receive interactions at the `/interactions` endpoint of your server, e.g. `https://example.com/interactions`. Once you run the server, put that URL into the "Interactions Endpoint URL" of your app in the Discord developer portal.
|
|
114
|
+
|
|
115
|
+
# Releasing
|
|
116
|
+
|
|
117
|
+
1. Bump `__version__` in `src/disunity/__init__.py` and update the changelog below.
|
|
118
|
+
2. Commit, then tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
|
|
119
|
+
|
|
120
|
+
Pushing a `v*` tag runs `.github/workflows/publish.yml`, which checks that the tag matches `__version__`, runs the tests, builds the package and publishes it to PyPI using trusted publishing (no token).
|
|
121
|
+
|
|
122
|
+
One-time setup:
|
|
123
|
+
- On PyPI, add a trusted publisher for this project: GitHub owner `murillotadeo`, repository `disunity`, workflow `publish.yml`, environment `pypi`.
|
|
124
|
+
- In the GitHub repository settings, create an environment named `pypi`.
|
|
125
|
+
|
|
126
|
+
# Changelog
|
|
127
|
+
|
|
128
|
+
## 0.3.0
|
|
129
|
+
|
|
130
|
+
Nothing breaking: legacy messages, components and modals produce exactly the same payloads as in 0.2.0. Components V2 was tested live on Discord (2026-11-29) except for what `docs/gotchas.md` #13 lists as unverified.
|
|
131
|
+
|
|
132
|
+
### Added
|
|
133
|
+
- Components V2 layout components (`disunity.models`): `TextDisplay`, `Section`, `Thumbnail`, `MediaGallery` / `MediaGalleryItem`, `File`, `Separator` / `SeparatorSpacing`, `Container`, all with an optional `id`. Media accepts a URL or an `Attachment` (sent as `attachment://<filename>`); `File` only supports `attachment://`.
|
|
134
|
+
- Native selects `UserSelect`, `RoleSelect`, `MentionableSelect`, `ChannelSelect` (with `channel_types`) and `SelectDefaultValue`; `ComponentTypes` constants.
|
|
135
|
+
- `Label` (modals only) wrapping a `UserTextInput`, `SelectMenu` or any of the new selects; `Modal` now accepts `Label` and `TextDisplay`.
|
|
136
|
+
- `components_v2` parameter on `ctx.callback`, `ctx.followup`, `ctx.edit_original`, `Message.edit_as_webhook` and `Message.edit_as_bot`. The V2 flag is set automatically when a layout component is passed, and kept on messages that already have it.
|
|
137
|
+
- `Message.flags` and `Message.is_components_v2`.
|
|
138
|
+
- `ctx.modal_select_values(custom_id)` to read selects submitted inside a modal `Label`.
|
|
139
|
+
- `utils.MessageFlags.SUPPRESS_EMBEDS` (4) and `IS_COMPONENTS_V2` (`1 << 15`).
|
|
140
|
+
- `errors.ComponentsV2Error` (a `DisunityError` and a `ValueError`) for invalid layouts and for mixing V2 with `content` / `embeds`.
|
|
141
|
+
- Optional new arguments on existing classes: `SelectMenuOption` / `MenuOption` `default`; `SelectMenu` `min_values`, `max_values`, `required`; `UserTextInput` `label` may be `None` when wrapped in a `Label`.
|
|
142
|
+
|
|
143
|
+
### Changed
|
|
144
|
+
- A message may hold at most 40 components in total, nested ones included (raises `ComponentsV2Error`; media gallery items don't count), and a `Container` takes 1 to 40 children.
|
|
145
|
+
- `ctx.edit_original` clears `content` and `embeds` (sends null / `[]`) while it doesn't know the original is V2, so it can turn a legacy original into a V2 message; it now starts from the V2 flag of the component's own message.
|
|
146
|
+
- V2 messages can't have `content` or `embeds`, can't be deferred with type 5 (defer, then `edit_original`), and `ctx.callback` can't upload files (use `followup` / `edit_original` for `attachment://` references).
|
|
147
|
+
- `Modal` with a `Label` or `TextDisplay` validates 1 to 5 components, a title of at most 45 characters and 4000 characters of text in total; modals with only `UserTextInput`s are validated as before.
|
|
148
|
+
- Docs: Components V2 section in `docs/components.md`, `docs/gotchas.md` #13, and updated `context`, `models`, `errors`, `utils`, `index`.
|
|
149
|
+
|
|
150
|
+
## 0.2.0
|
|
151
|
+
|
|
152
|
+
### Fixed
|
|
153
|
+
- `requires_ephemeral=True` on acked commands and sub commands no longer crashes (response `{"type": 5, "data": {"flags": 64}}`).
|
|
154
|
+
- Several `@Package.sub` decorators for the same base command and group no longer overwrite each other.
|
|
155
|
+
- Component `timeout` is now enforced for `requires_ack=True` components and modal submits; timed-out interactions get an ephemeral "This component has timed out." and the handler does not run. The timeout is measured from the component message's creation time.
|
|
156
|
+
- Modal submits honor `requires_ack` (type 6 when the modal came from a message, else type 5).
|
|
157
|
+
- `UserTextInput` `placeholder`, `min_length` and `value` can be combined.
|
|
158
|
+
- Link buttons no longer send `custom_id`; select option values are sent as `str`; empty descriptions/placeholders are omitted.
|
|
159
|
+
- `Message.edit_as_webhook` / `edit_as_bot` send only the provided fields; `edit_as_webhook` raises `ExpiredInteractionError` on 10015/50027 and re-raises other `HTTPRequestError`s instead of ignoring them.
|
|
160
|
+
- `Member.server_avatar_url` uses the guild avatar URL.
|
|
161
|
+
- `User.mention` is `<@id>`, `User.username` drops `#0`, default avatar uses the correct formula for new usernames.
|
|
162
|
+
- `check_user()` returns `False` when there is no author; `invoked_by` on components comes from `message.interaction_metadata` (fallback `message.interaction`).
|
|
163
|
+
- `global_after_interaction` also runs when the handler raised; `error_handler` is always called inside the `except` block and also receives errors from `global_after_interaction`.
|
|
164
|
+
- Background tasks are referenced and their exceptions logged.
|
|
165
|
+
|
|
166
|
+
### Added
|
|
167
|
+
- `ctx.options` works for autocomplete; `ctx.focused_option`, `ctx.sub_command`, `ctx.sub_command_group`, `ctx.guild_id`, `ctx.created_at`, `ctx.app`.
|
|
168
|
+
- `ctx.modal_value(custom_id)`; `modal_values` is flattened (Label type 18 and action rows).
|
|
169
|
+
- `allowed_mentions` parameter on `ctx.callback` / `ctx.followup`; `User.display_name`.
|
|
170
|
+
- Autocomplete choices are truncated to 25.
|
|
171
|
+
- Errors: base class `DisunityError`, `HTTPRequestError.status/.code/.data`, `ResponseDecodeError`.
|
|
172
|
+
- `make_https_request`: shared aiohttp session (closed `after_serving`), 429 retry honoring `retry_after` (`max_rate_limit_retries`, `max_rate_limit_wait`), async `auth()`.
|
|
173
|
+
- `ctx.followup` retries Unknown Webhook (10015) up to 3 times shortly after deferring and logs timing; the server warns when the initial response is late (`late_response_warning`).
|
|
174
|
+
- `ValueError` for component names containing `-`; warnings for duplicate registrations.
|
|
175
|
+
- `ctx.edit_original(...)` (only the given fields are sent, `components=[]` clears), `ctx.get_original()`, `ctx.delete_original()`; they share the Unknown Webhook retry with `followup`.
|
|
176
|
+
- Resolved option helpers: `ctx.get_user/get_member/get_role/get_channel/get_attachment(option_name)`, `ctx.target_id` and `ctx.get_target_user/get_target_member/get_target_message()` for context menu commands.
|
|
177
|
+
- Models `Role`, `Channel`, `ResolvedAttachment` (in `disunity.models`) and `utils.ChannelTypes`.
|
|
178
|
+
- `DisunityServer.error_message`: when a handler raises and `error_handler` swallows the exception, the user gets an ephemeral "Something went wrong" message (response or followup); set it to `None` to disable.
|
|
179
|
+
- `make_custom_id(name, *args)` / `utils.parse_custom_id`, `utils.CUSTOM_ID_SEPARATOR` / `CUSTOM_ID_MAX_LENGTH`, and `ctx.component_name` / `ctx.custom_args`; routing uses `parse_custom_id`.
|
|
180
|
+
|
|
181
|
+
### Changed
|
|
182
|
+
- Runtime dependencies are real `[project].dependencies`: `quart>=0.20`, `aiohttp>=3.9`, `PyNaCl>=1.5`. Python >= 3.10.
|
|
183
|
+
- Version lives in `disunity.__version__` (`utils.__version__` re-exports it).
|
|
184
|
+
- `quart.flask_patch` is gone: use `from quart import request`.
|
|
185
|
+
- No auth headers are sent to non-Discord hosts when `headers=None`.
|
|
186
|
+
- `global_check` returning a non-`True`, non-dict value acks components silently (type 6); commands still get PONG.
|
|
187
|
+
|
|
188
|
+
### Removed
|
|
189
|
+
- `requests` dependency.
|
|
190
|
+
- `override_checks` parameter of `make_https_request`.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "disunity"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
authors = [{ name = "Tadeo Murillo" }]
|
|
9
|
+
description = "Python framework for Discord interactions using a web server"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = { file = "LICENSE" }
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = [
|
|
14
|
+
"quart>=0.20",
|
|
15
|
+
"aiohttp>=3.9",
|
|
16
|
+
"PyNaCl>=1.5",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"License :: OSI Approved :: MIT License",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
"Framework :: AsyncIO",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
dev = [
|
|
31
|
+
"pytest>=8",
|
|
32
|
+
"pytest-asyncio>=0.23",
|
|
33
|
+
"ruff>=0.6",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
"Homepage" = "https://github.com/murillotadeo/disunity"
|
|
38
|
+
"Bug Tracker" = "https://github.com/murillotadeo/disunity/issues"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.dynamic]
|
|
41
|
+
version = { attr = "disunity.__version__" }
|
|
42
|
+
|
|
43
|
+
[tool.setuptools.packages.find]
|
|
44
|
+
where = ["src"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
asyncio_mode = "auto"
|
|
48
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
49
|
+
testpaths = ["tests"]
|
|
50
|
+
|
|
51
|
+
[tool.ruff]
|
|
52
|
+
line-length = 100
|
|
53
|
+
target-version = "py310"
|
|
54
|
+
src = ["src", "tests"]
|
|
55
|
+
|
|
56
|
+
[tool.ruff.lint]
|
|
57
|
+
select = ["E", "F", "W", "I", "B", "UP"]
|
|
58
|
+
ignore = ["E501", "B008"]
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
[egg_info]
|
|
2
|
-
tag_build =
|
|
3
|
-
tag_date = 0
|
|
4
|
-
|
|
1
|
+
[egg_info]
|
|
2
|
+
tag_build =
|
|
3
|
+
tag_date = 0
|
|
4
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
__version__ = "0.3.0"
|
|
2
|
+
|
|
3
|
+
from . import utils
|
|
4
|
+
from .embed import Embed
|
|
5
|
+
from .identifiers import SubOption
|
|
6
|
+
from .models import Attachment, Message
|
|
7
|
+
from .package import Package
|
|
8
|
+
from .server import DisunityServer
|
|
9
|
+
from .utils import make_custom_id
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"__version__",
|
|
13
|
+
"Attachment",
|
|
14
|
+
"DisunityServer",
|
|
15
|
+
"Embed",
|
|
16
|
+
"Message",
|
|
17
|
+
"Package",
|
|
18
|
+
"SubOption",
|
|
19
|
+
"make_custom_id",
|
|
20
|
+
"utils",
|
|
21
|
+
]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
|
|
3
|
+
from .identifiers import (
|
|
4
|
+
Autocomplete,
|
|
5
|
+
CacheableSubCommand,
|
|
6
|
+
Command,
|
|
7
|
+
Component,
|
|
8
|
+
TopLevelSubCommand,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ApplicationCache:
|
|
15
|
+
"""Registry of every handler, keyed by the name Discord sends us."""
|
|
16
|
+
|
|
17
|
+
def __init__(self):
|
|
18
|
+
self.commands: dict[str, Command | CacheableSubCommand] = {}
|
|
19
|
+
self.components: dict[str, Component] = {}
|
|
20
|
+
self.autocompletes: dict[str, Autocomplete] = {}
|
|
21
|
+
|
|
22
|
+
def add_item(
|
|
23
|
+
self, incoming: TopLevelSubCommand | Command | Component | Autocomplete
|
|
24
|
+
):
|
|
25
|
+
if isinstance(incoming, TopLevelSubCommand):
|
|
26
|
+
name = str(incoming.name)
|
|
27
|
+
existing = self.commands.get(name)
|
|
28
|
+
if isinstance(existing, Command):
|
|
29
|
+
log.warning(
|
|
30
|
+
"Sub commands of %r replace the plain command with the same name", name
|
|
31
|
+
)
|
|
32
|
+
existing = None
|
|
33
|
+
if existing is None:
|
|
34
|
+
existing = self.commands[name] = CacheableSubCommand(name)
|
|
35
|
+
existing.add(incoming)
|
|
36
|
+
|
|
37
|
+
elif isinstance(incoming, Command):
|
|
38
|
+
name = str(incoming.name)
|
|
39
|
+
if name in self.commands:
|
|
40
|
+
log.warning("Command %r is registered more than once; the last one wins", name)
|
|
41
|
+
self.commands[name] = incoming
|
|
42
|
+
|
|
43
|
+
elif isinstance(incoming, Component):
|
|
44
|
+
name = str(incoming.name)
|
|
45
|
+
if name in self.components:
|
|
46
|
+
log.warning("Component %r is registered more than once; the last one wins", name)
|
|
47
|
+
self.components[name] = incoming
|
|
48
|
+
|
|
49
|
+
elif isinstance(incoming, Autocomplete):
|
|
50
|
+
name = str(incoming.command_name)
|
|
51
|
+
if name in self.autocompletes:
|
|
52
|
+
log.warning(
|
|
53
|
+
"Autocomplete for %r is registered more than once; the last one wins", name
|
|
54
|
+
)
|
|
55
|
+
self.autocompletes[name] = incoming
|
|
56
|
+
|
|
57
|
+
else:
|
|
58
|
+
raise TypeError(f"Cannot cache object of type {type(incoming).__name__}")
|
|
@@ -58,7 +58,12 @@ class Embed:
|
|
|
58
58
|
return self.__json.get("fields", None)
|
|
59
59
|
|
|
60
60
|
def add_field(self, name: str, value: str, inline: bool = False) -> Embed:
|
|
61
|
-
if
|
|
61
|
+
if name is None or value is None:
|
|
62
|
+
raise EmptyEmbedError("Embed field cannot contain an empty value")
|
|
63
|
+
|
|
64
|
+
name = str(name)
|
|
65
|
+
value = str(value)
|
|
66
|
+
if name == "" or value == "":
|
|
62
67
|
raise EmptyEmbedError("Embed field cannot contain an empty value")
|
|
63
68
|
|
|
64
69
|
if "fields" not in self.__json:
|
|
@@ -85,7 +90,7 @@ class Embed:
|
|
|
85
90
|
|
|
86
91
|
@property
|
|
87
92
|
def image(self) -> None | dict:
|
|
88
|
-
return self.__json.get("
|
|
93
|
+
return self.__json.get("image", None)
|
|
89
94
|
|
|
90
95
|
def set_image(self, image_url: str) -> Embed:
|
|
91
96
|
if "image" not in self.__json:
|
|
@@ -113,7 +118,9 @@ class Embed:
|
|
|
113
118
|
self, name: str, url: None | str = None, icon_url: None | str = None
|
|
114
119
|
) -> Embed:
|
|
115
120
|
if "author" not in self.__json:
|
|
116
|
-
self.__json["author"] = {
|
|
121
|
+
self.__json["author"] = {}
|
|
122
|
+
|
|
123
|
+
self.__json["author"]["name"] = str(name)
|
|
117
124
|
|
|
118
125
|
if url is not None:
|
|
119
126
|
self.__json["author"]["url"] = str(url)
|