disunity 0.1.16__tar.gz → 0.2.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 (60) hide show
  1. disunity-0.2.0/PKG-INFO +190 -0
  2. disunity-0.2.0/README.md +141 -0
  3. disunity-0.2.0/pyproject.toml +58 -0
  4. {disunity-0.1.16 → disunity-0.2.0}/setup.cfg +4 -4
  5. disunity-0.2.0/src/disunity/__init__.py +21 -0
  6. disunity-0.2.0/src/disunity/cache.py +58 -0
  7. {disunity-0.1.16 → disunity-0.2.0}/src/disunity/embed.py +10 -3
  8. disunity-0.2.0/src/disunity/errors.py +63 -0
  9. disunity-0.2.0/src/disunity/identifiers.py +164 -0
  10. disunity-0.2.0/src/disunity/models/__init__.py +39 -0
  11. {disunity-0.1.16 → disunity-0.2.0}/src/disunity/models/attachment.py +4 -2
  12. disunity-0.2.0/src/disunity/models/channel.py +21 -0
  13. {disunity-0.1.16 → disunity-0.2.0}/src/disunity/models/components.py +28 -16
  14. disunity-0.2.0/src/disunity/models/context.py +405 -0
  15. disunity-0.2.0/src/disunity/models/interaction.py +127 -0
  16. disunity-0.2.0/src/disunity/models/member.py +32 -0
  17. disunity-0.2.0/src/disunity/models/message.py +125 -0
  18. disunity-0.2.0/src/disunity/models/resolved_attachment.py +19 -0
  19. disunity-0.2.0/src/disunity/models/role.py +21 -0
  20. disunity-0.2.0/src/disunity/models/user.py +35 -0
  21. disunity-0.2.0/src/disunity/package.py +166 -0
  22. disunity-0.2.0/src/disunity/server.py +556 -0
  23. disunity-0.2.0/src/disunity/utils.py +132 -0
  24. disunity-0.2.0/src/disunity.egg-info/PKG-INFO +190 -0
  25. {disunity-0.1.16 → disunity-0.2.0}/src/disunity.egg-info/SOURCES.txt +19 -1
  26. disunity-0.2.0/src/disunity.egg-info/requires.txt +8 -0
  27. disunity-0.2.0/tests/test_autocomplete.py +43 -0
  28. disunity-0.2.0/tests/test_commands.py +44 -0
  29. disunity-0.2.0/tests/test_components.py +105 -0
  30. disunity-0.2.0/tests/test_custom_id.py +97 -0
  31. disunity-0.2.0/tests/test_error_message.py +220 -0
  32. disunity-0.2.0/tests/test_followup.py +88 -0
  33. disunity-0.2.0/tests/test_hooks.py +95 -0
  34. disunity-0.2.0/tests/test_http.py +212 -0
  35. disunity-0.2.0/tests/test_models.py +168 -0
  36. disunity-0.2.0/tests/test_original.py +148 -0
  37. disunity-0.2.0/tests/test_resolved.py +137 -0
  38. disunity-0.2.0/tests/test_resolved_models.py +63 -0
  39. disunity-0.2.0/tests/test_subcommands.py +64 -0
  40. disunity-0.2.0/tests/test_transport.py +44 -0
  41. disunity-0.1.16/PKG-INFO +0 -74
  42. disunity-0.1.16/README.md +0 -60
  43. disunity-0.1.16/pyproject.toml +0 -29
  44. disunity-0.1.16/src/disunity/__init__.py +0 -6
  45. disunity-0.1.16/src/disunity/cache.py +0 -41
  46. disunity-0.1.16/src/disunity/errors.py +0 -27
  47. disunity-0.1.16/src/disunity/identifiers.py +0 -178
  48. disunity-0.1.16/src/disunity/models/__init__.py +0 -16
  49. disunity-0.1.16/src/disunity/models/context.py +0 -147
  50. disunity-0.1.16/src/disunity/models/interaction.py +0 -63
  51. disunity-0.1.16/src/disunity/models/member.py +0 -22
  52. disunity-0.1.16/src/disunity/models/message.py +0 -129
  53. disunity-0.1.16/src/disunity/models/user.py +0 -24
  54. disunity-0.1.16/src/disunity/package.py +0 -205
  55. disunity-0.1.16/src/disunity/server.py +0 -379
  56. disunity-0.1.16/src/disunity/utils.py +0 -42
  57. disunity-0.1.16/src/disunity.egg-info/PKG-INFO +0 -74
  58. {disunity-0.1.16 → disunity-0.2.0}/LICENSE +0 -0
  59. {disunity-0.1.16 → disunity-0.2.0}/src/disunity.egg-info/dependency_links.txt +0 -0
  60. {disunity-0.1.16 → disunity-0.2.0}/src/disunity.egg-info/top_level.txt +0 -0
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.4
2
+ Name: disunity
3
+ Version: 0.2.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.2.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
+ # Documentation
119
+
120
+ Agent-oriented reference docs live in [docs/](docs/index.md).
121
+
122
+ # Tests
123
+
124
+ ```
125
+ pip install -e .[dev]
126
+ pytest
127
+ ```
128
+
129
+ # Disclaimer
130
+
131
+ 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.
132
+
133
+ # Side note
134
+
135
+ 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.
136
+
137
+ # Releasing
138
+
139
+ 1. Bump `__version__` in `src/disunity/__init__.py` and update the changelog below.
140
+ 2. Commit, then tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
141
+
142
+ 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).
143
+
144
+ One-time setup:
145
+ - On PyPI, add a trusted publisher for this project: GitHub owner `murillotadeo`, repository `disunity`, workflow `publish.yml`, environment `pypi`.
146
+ - In the GitHub repository settings, create an environment named `pypi`.
147
+
148
+ # Changelog
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,141 @@
1
+ # disunity
2
+
3
+ Python framework for Discord interactions using a web server (Quart). Version 0.2.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
+ # Documentation
70
+
71
+ Agent-oriented reference docs live in [docs/](docs/index.md).
72
+
73
+ # Tests
74
+
75
+ ```
76
+ pip install -e .[dev]
77
+ pytest
78
+ ```
79
+
80
+ # Disclaimer
81
+
82
+ 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.
83
+
84
+ # Side note
85
+
86
+ 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.
87
+
88
+ # Releasing
89
+
90
+ 1. Bump `__version__` in `src/disunity/__init__.py` and update the changelog below.
91
+ 2. Commit, then tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
92
+
93
+ 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).
94
+
95
+ One-time setup:
96
+ - On PyPI, add a trusted publisher for this project: GitHub owner `murillotadeo`, repository `disunity`, workflow `publish.yml`, environment `pypi`.
97
+ - In the GitHub repository settings, create an environment named `pypi`.
98
+
99
+ # Changelog
100
+
101
+ ## 0.2.0
102
+
103
+ ### Fixed
104
+ - `requires_ephemeral=True` on acked commands and sub commands no longer crashes (response `{"type": 5, "data": {"flags": 64}}`).
105
+ - Several `@Package.sub` decorators for the same base command and group no longer overwrite each other.
106
+ - 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.
107
+ - Modal submits honor `requires_ack` (type 6 when the modal came from a message, else type 5).
108
+ - `UserTextInput` `placeholder`, `min_length` and `value` can be combined.
109
+ - Link buttons no longer send `custom_id`; select option values are sent as `str`; empty descriptions/placeholders are omitted.
110
+ - `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.
111
+ - `Member.server_avatar_url` uses the guild avatar URL.
112
+ - `User.mention` is `<@id>`, `User.username` drops `#0`, default avatar uses the correct formula for new usernames.
113
+ - `check_user()` returns `False` when there is no author; `invoked_by` on components comes from `message.interaction_metadata` (fallback `message.interaction`).
114
+ - `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`.
115
+ - Background tasks are referenced and their exceptions logged.
116
+
117
+ ### Added
118
+ - `ctx.options` works for autocomplete; `ctx.focused_option`, `ctx.sub_command`, `ctx.sub_command_group`, `ctx.guild_id`, `ctx.created_at`, `ctx.app`.
119
+ - `ctx.modal_value(custom_id)`; `modal_values` is flattened (Label type 18 and action rows).
120
+ - `allowed_mentions` parameter on `ctx.callback` / `ctx.followup`; `User.display_name`.
121
+ - Autocomplete choices are truncated to 25.
122
+ - Errors: base class `DisunityError`, `HTTPRequestError.status/.code/.data`, `ResponseDecodeError`.
123
+ - `make_https_request`: shared aiohttp session (closed `after_serving`), 429 retry honoring `retry_after` (`max_rate_limit_retries`, `max_rate_limit_wait`), async `auth()`.
124
+ - `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`).
125
+ - `ValueError` for component names containing `-`; warnings for duplicate registrations.
126
+ - `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`.
127
+ - 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.
128
+ - Models `Role`, `Channel`, `ResolvedAttachment` (in `disunity.models`) and `utils.ChannelTypes`.
129
+ - `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.
130
+ - `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`.
131
+
132
+ ### Changed
133
+ - Runtime dependencies are real `[project].dependencies`: `quart>=0.20`, `aiohttp>=3.9`, `PyNaCl>=1.5`. Python >= 3.10.
134
+ - Version lives in `disunity.__version__` (`utils.__version__` re-exports it).
135
+ - `quart.flask_patch` is gone: use `from quart import request`.
136
+ - No auth headers are sent to non-Discord hosts when `headers=None`.
137
+ - `global_check` returning a non-`True`, non-dict value acks components silently (type 6); commands still get PONG.
138
+
139
+ ### Removed
140
+ - `requests` dependency.
141
+ - `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.2.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 not bool(name) or not bool(value):
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("url", None)
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"] = {"name": str(name)}
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)
@@ -0,0 +1,63 @@
1
+ class DisunityError(Exception):
2
+ """Base class for every exception raised by disunity."""
3
+
4
+
5
+ class InvalidMethodUse(DisunityError):
6
+ def __init__(self, reason):
7
+ super().__init__(reason)
8
+
9
+
10
+ class CommandNotFound(DisunityError):
11
+ def __init__(self, command):
12
+ super().__init__(f"Command with name {command} could not be found")
13
+
14
+
15
+ class ComponentNotFound(DisunityError):
16
+ def __init__(self, component):
17
+ super().__init__(f"No listener for components with name {component} exists")
18
+
19
+
20
+ class AutocompleteNotFound(DisunityError):
21
+ def __init__(self, command_name):
22
+ super().__init__(
23
+ f"No listener for autocomplete for command {command_name} exists"
24
+ )
25
+
26
+
27
+ class HTTPRequestError(DisunityError):
28
+ """
29
+ A request made with ``DisunityServer.make_https_request`` failed.
30
+
31
+ Attributes
32
+ ----------
33
+ status: int
34
+ HTTP status code of the response.
35
+ data: dict | str | None
36
+ Decoded JSON body of the response, or the raw text when it was not JSON.
37
+ code: int | None
38
+ Discord JSON error code (e.g. 10015 Unknown Webhook) when present.
39
+ """
40
+
41
+ def __init__(self, status_code, error_message):
42
+ self.status: int = status_code
43
+ self.data = error_message
44
+ self.code: int | None = (
45
+ error_message.get("code") if isinstance(error_message, dict) else None
46
+ )
47
+ # The message format is relied upon by callers that match on str(exc),
48
+ # e.g. "'code': 10015" - keep it stable.
49
+ super().__init__(
50
+ f"HTTP request returned with status {status_code}: {error_message}"
51
+ )
52
+
53
+
54
+ class ResponseDecodeError(HTTPRequestError):
55
+ """A successful response had a body that could not be decoded as JSON."""
56
+
57
+ def __init__(self, status_code, body_text):
58
+ DisunityError.__init__(
59
+ self, f"HTTP request returned with status {status_code}: body is not valid JSON"
60
+ )
61
+ self.status = status_code
62
+ self.data = body_text
63
+ self.code = None