Skip to content

Commit 5ca01eb

Browse files
committed
Added docs
1 parent c4b71a8 commit 5ca01eb

File tree

135 files changed

+23294
-24
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

135 files changed

+23294
-24
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,5 @@ For now clone this repository and use `discod_slash` folder.
2626
(Maybe will upload this at PyPi soon)
2727

2828
## DOCS
29-
Not yet ready.
29+
See the source code. Maybe will use sphinx soon?
3030
See [discord-api-docs](https://github.com/discord/discord-api-docs/blob/feature/interactions/docs/interactions/Slash_Commands.md) for some more information.

discord_slash/__init__.py

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,11 @@
11
"""
2-
MIT License
2+
discord-py-slash-command
3+
~~~~~~~~~~~~~~~~~~~~~~~~
34
4-
Copyright (c) 2020 eunwoo1104
5+
Simple Discord Slash Command extension for discord.py
56
6-
Permission is hereby granted, free of charge, to any person obtaining a copy
7-
of this software and associated documentation files (the "Software"), to deal
8-
in the Software without restriction, including without limitation the rights
9-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10-
copies of the Software, and to permit persons to whom the Software is
11-
furnished to do so, subject to the following conditions:
12-
13-
The above copyright notice and this permission notice shall be included in all
14-
copies or substantial portions of the Software.
15-
16-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22-
SOFTWARE.
7+
:copyright: (c) 2020 eunwoo1104
8+
:license: MIT
239
"""
2410

2511
from .client import SlashCommand

discord_slash/client.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,31 +7,61 @@
77

88

99
class SlashCommand:
10+
"""
11+
Slash command extension class.
12+
13+
:param client: discord.py Bot class. Although it accepts :class:`discord.Client` at init, using it is not allowed since :class:`discord.Client` doesn't support :func:`add_listener`.
14+
:type client: Union[discord.Client, discord.ext.commands.Bot]
15+
"""
1016
def __init__(self,
1117
client: typing.Union[discord.Client,
1218
commands.Bot]
1319
):
1420
if isinstance(client, discord.Client) and not isinstance(client, commands.Bot):
15-
raise Exception("Currently only ext.Bot is supported.")
21+
raise Exception("Currently only commands.Bot is supported.")
1622
self._discord = client
1723
self.commands = {}
1824
self.http = http.SlashCommandRequest()
1925
self.logger = logging.getLogger("discord_slash")
2026
self._discord.add_listener(self.on_socket_response)
2127

2228
def slash(self, name=None):
29+
"""
30+
Decorator that registers coroutine as a slash command.\n
31+
1 arg is required for ctx(:func:`discord_slash.model.SlashContext`), and if your slash command has some args, then those args are also required.\n
32+
All args are passed in order.\n
33+
Note that Role, User, and Channel types are passed as id, since API doesn't give type of the option for now.
34+
35+
:param name: Name of the slash command.
36+
"""
2337
def wrapper(cmd):
2438
self.commands[cmd.__name__ if not name else name] = cmd
2539
self.logger.debug(f"Added command `{cmd.__name__ if not name else name}`")
2640
return cmd
2741
return wrapper
2842

2943
def process_options(self, options: dict) -> list:
44+
"""
45+
Not ready.
46+
47+
:param options: Dict of options.
48+
:type options: dict
49+
:return: list
50+
:raises: :class:`NotImplementedError` - This is still not implemented.
51+
"""
52+
raise NotImplementedError
53+
3054
for x in options:
3155
pass
3256
return []
3357

3458
async def on_socket_response(self, msg):
59+
"""
60+
This event listener is automatically registered at initialization of this class.\n
61+
DO NOT MANUALLY REGISTER, OVERRIDE, OR WHATEVER ACTION TO THIS COROUTINE UNLESS YOU KNOW WHAT YOU ARE DOING.
62+
63+
:param msg: Gateway message.
64+
"""
3565
if msg["t"] != "INTERACTION_CREATE":
3666
return
3767
to_use = msg["d"]

discord_slash/error.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class SlashCommandError(Exception):
2+
"""
3+
All exceptions of this extension can be captured with this.
4+
Note that discord.py doesn't trigger `on_command_error` event.
5+
"""
6+
pass
7+
8+
9+
class RequestFailure(SlashCommandError):
10+
"""
11+
Request to Discord API has failed.
12+
"""
13+
def __init__(self, status: int, msg: str):
14+
self.status = status
15+
self.msg = msg
16+
super().__init__(f"Request failed with resp: {self.status} | {self.msg}")
17+
18+
19+
class IncorrectFormat(SlashCommandError):
20+
"""
21+
Some formats are incorrect. See Discord API DOCS for proper format.
22+
"""
23+
def __init__(self, msg: str):
24+
super().__init__(msg)

discord_slash/http.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,25 @@
11
import aiohttp
2+
from .error import RequestFailure
23

34

45
class SlashCommandRequest:
56
def __init__(self):
67
pass
78

89
async def post(self, _resp, _id, token):
10+
"""
11+
Sends command response POST request to Discord API.
12+
13+
:param _resp: Command response.
14+
:type _resp: dict
15+
:param _id: Command message id.
16+
:param token: Command message token.
17+
:return: True if succeeded.
18+
:raises: :class:`error.RequestFailure` - Requesting to API has failed.
19+
"""
920
req_url = f"https://discord.com/api/v8/interactions/{_id}/{token}/callback"
1021
async with aiohttp.ClientSession() as session:
1122
async with session.post(req_url, json=_resp) as resp:
1223
if not 200 <= resp.status < 300:
13-
raise Exception(f"Request failed with resp: {resp.status} | {await resp.text()}")
24+
raise RequestFailure(resp.status, await resp.text())
1425
return True

discord_slash/model.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55

66

77
class SlashContext:
8+
"""
9+
Context of the slash command.\n
10+
Kinda similar with discord.ext.commands.Context.
11+
"""
812
def __init__(self,
913
_http: http.SlashCommandRequest,
1014
_json: dict,
@@ -23,6 +27,19 @@ async def send(self,
2327
text: str = "",
2428
embeds: typing.List[discord.Embed] = None,
2529
tts: bool = False):
30+
"""
31+
Sends response of the slash command.
32+
33+
:param send_type: Type of the response. Refer Discord API DOCS for more info about types. Default `4`.
34+
:type send_type: int
35+
:param text: Text of the response. Can be `None`.
36+
:type text: str
37+
:param embeds: Embeds of the response. Maximum 10, can be empty.
38+
:type embeds: List[discord.Embed]
39+
:param tts: Whether to speak message using tts. Default `False`.
40+
:type tts: bool
41+
:return: `None`
42+
"""
2643
if embeds and len(embeds) > 10:
2744
raise
2845
base = {

discord_slash/utils/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
"""
2+
discord-py-slash-command.utils
3+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4+
5+
Utility functions for slash command.
6+
7+
:copyright: (c) 2020 eunwoo1104
8+
:license: MIT
9+
"""

discord_slash/utils/manage_commands.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,17 @@ async def add_slash_command(bot_id,
77
cmd_name: str,
88
description: str,
99
options: list = None):
10+
"""
11+
A coroutine that sends a slash command add request to Discord API.
12+
13+
:param bot_id: User ID of the bot.
14+
:param bot_token: Token of the bot.
15+
:param guild_id: ID of the guild to add command. Pass `None` to add global command.
16+
:param cmd_name: Name of the command. Must be 3 or longer and 32 or shorter.
17+
:param description: Description of the command.
18+
:param options: List of the function.
19+
:return: JSON Response of the request.
20+
"""
1021
url = f"https://discord.com/api/v8/applications/{bot_id}"
1122
url += "/commands" if not guild_id else f"/guilds/{guild_id}/commands"
1223
base = {
@@ -24,6 +35,15 @@ async def remove_slash_command(bot_id,
2435
bot_token,
2536
guild_id,
2637
cmd_id):
38+
"""
39+
A coroutine that sends a slash command remove request to Discord API.
40+
41+
:param bot_id: User ID of the bot.
42+
:param bot_token: Token of the bot.
43+
:param guild_id: ID of the guild to remove command. Pass `None` to remove global command.
44+
:param cmd_id: ID of the command.
45+
:return: Response code of the request.
46+
"""
2747
url = f"https://discord.com/api/v8/applications/{bot_id}"
2848
url += "/commands" if not guild_id else f"/guilds/{guild_id}/commands"
2949
url += f"/{cmd_id}"
@@ -36,7 +56,17 @@ def create_option(name: str,
3656
description: str,
3757
option_type: int,
3858
required: bool,
39-
choices: list = None):
59+
choices: list = None) -> dict:
60+
"""
61+
Creates option used for creating slash command.
62+
63+
:param name: Name of the option.
64+
:param description: Descrption of the option.
65+
:param option_type: Type of the option.
66+
:param required: Whether this option is required.
67+
:param choices: Choices of the option. Can be empty.
68+
:return: dict
69+
"""
4070
return {
4171
"name": name,
4272
"description": description,
@@ -46,7 +76,14 @@ def create_option(name: str,
4676
}
4777

4878

49-
def create_choices(value: str, name: str):
79+
def create_choice(value: str, name: str):
80+
"""
81+
Creates choices used for creating command option.
82+
83+
:param value: Value of the choice.
84+
:param name: Name of the choice.
85+
:return: dict
86+
"""
5087
return {
5188
"value": value,
5289
"name": name

docs/Makefile

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Minimal makefile for Sphinx documentation
2+
#
3+
4+
# You can set these variables from the command line, and also
5+
# from the environment for the first two.
6+
SPHINXOPTS ?=
7+
SPHINXBUILD ?= sphinx-build
8+
SOURCEDIR = .
9+
BUILDDIR = _build
10+
11+
# Put it first so that "make" without argument is like "make help".
12+
help:
13+
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14+
15+
.PHONY: help Makefile
16+
17+
# Catch-all target: route all unknown targets to Sphinx using the new
18+
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19+
%: Makefile
20+
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
Binary file not shown.

0 commit comments

Comments
 (0)