Skip to content

Commit cf7d107

Browse files
committed
Refactored http.py to use client's http
1 parent 617a0c0 commit cf7d107

File tree

2 files changed

+26
-49
lines changed

2 files changed

+26
-49
lines changed

discord_slash/client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __init__(self,
3535
self.commands = {}
3636
self.subcommands = {}
3737
self.logger = logging.getLogger("discord_slash")
38-
self.req = http.SlashCommandRequest(self.logger)
38+
self.req = http.SlashCommandRequest(self.logger, self._discord)
3939
self.auto_register = auto_register
4040
if self.auto_register:
4141
self._discord.loop.create_task(self.register_all_commands())

discord_slash/http.py

Lines changed: 25 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
1-
import aiohttp
2-
import asyncio
3-
from .error import RequestFailure
1+
import typing
2+
import discord
3+
from discord.http import Route
4+
5+
6+
class CustomRoute(Route):
7+
"""discord.py's Route but changed ``BASE`` to use at slash command."""
8+
BASE = "https://discord.com/api/v8"
49

510

611
class SlashCommandRequest:
7-
def __init__(self, logger):
12+
def __init__(self, logger, _discord):
813
self.logger = logger
14+
self._discord: typing.Union[discord.Client, discord.AutoShardedClient] = _discord
915

10-
async def post(self, _resp, bot_id, interaction_id, token, initial=False) -> None:
16+
def post(self, _resp, bot_id, interaction_id, token, initial=False):
1117
"""
1218
Sends command response POST request to Discord API.
1319
@@ -17,24 +23,13 @@ async def post(self, _resp, bot_id, interaction_id, token, initial=False) -> Non
1723
:param interaction_id: Interaction ID.
1824
:param token: Command message token.
1925
:param initial: Whether this request is initial. Default ``False``
20-
:return: ``None``, since Discord API doesn't return anything.
21-
:raises: :class:`.error.RequestFailure` - Requesting to API has failed.
26+
:return: Coroutine
2227
"""
23-
req_url = f"https://discord.com/api/v8/interactions/{interaction_id}/{token}/callback" \
24-
if initial \
25-
else f"https://discord.com/api/v8/webhooks/{bot_id}/{token}"
26-
async with aiohttp.ClientSession() as session:
27-
async with session.post(req_url, json=_resp) as resp:
28-
if resp.status == 429:
29-
_json = await resp.json()
30-
self.logger.warning(f"We are being rate limited, retrying after {_json['retry_after']} seconds.")
31-
await asyncio.sleep(_json["retry_after"])
32-
return await self.post(_resp, bot_id, interaction_id, token, initial)
33-
if not 200 <= resp.status < 300:
34-
raise RequestFailure(resp.status, await resp.text())
35-
return None
28+
req_url = f"/interactions/{interaction_id}/{token}/callback" if initial else f"/webhooks/{bot_id}/{token}"
29+
route = CustomRoute("POST", req_url)
30+
return self._discord.http.request(route, json=_resp)
3631

37-
async def edit(self, _resp, bot_id, token, message_id="@original"):
32+
def edit(self, _resp, bot_id, token, message_id="@original"):
3833
"""
3934
Sends edit command response POST request to Discord API.
4035
@@ -43,39 +38,21 @@ async def edit(self, _resp, bot_id, token, message_id="@original"):
4338
:param bot_id: Bot ID.
4439
:param token: Command message token.
4540
:param message_id: Message ID to edit. Default initial message.
46-
:return: True if succeeded.
47-
:raises: :class:`.error.RequestFailure` - Requesting to API has failed.
41+
:return: Coroutine
4842
"""
49-
req_url = f"https://discord.com/api/v8/webhooks/{bot_id}/{token}/messages/{message_id}"
50-
async with aiohttp.ClientSession() as session:
51-
async with session.patch(req_url, json=_resp) as resp:
52-
if resp.status == 429:
53-
_json = await resp.json()
54-
self.logger.warning(f"We are being rate limited, retrying after {_json['retry_after']} seconds.")
55-
await asyncio.sleep(_json["retry_after"])
56-
return await self.edit(_resp, bot_id, token, message_id)
57-
if not 200 <= resp.status < 300:
58-
raise RequestFailure(resp.status, await resp.text())
59-
return True
43+
req_url = f"/webhooks/{bot_id}/{token}/messages/{message_id}"
44+
route = CustomRoute("PATCH", req_url)
45+
return self._discord.http.request(route, json=_resp)
6046

61-
async def delete(self, bot_id, token, message_id="@original"):
47+
def delete(self, bot_id, token, message_id="@original"):
6248
"""
6349
Sends delete command response POST request to Discord API.
6450
6551
:param bot_id: Bot ID.
6652
:param token: Command message token.
6753
:param message_id: Message ID to delete. Default initial message.
68-
:return: True if succeeded.
69-
:raises: :class:`.error.RequestFailure` - Requesting to API has failed.
54+
:return: Coroutine
7055
"""
71-
req_url = f"https://discord.com/api/v8/webhooks/{bot_id}/{token}/messages/{message_id}"
72-
async with aiohttp.ClientSession() as session:
73-
async with session.delete(req_url) as resp:
74-
if resp.status == 429:
75-
_json = await resp.json()
76-
self.logger.warning(f"We are being rate limited, retrying after {_json['retry_after']} seconds.")
77-
await asyncio.sleep(_json["retry_after"])
78-
return await self.delete(bot_id, token, message_id)
79-
if not 200 <= resp.status < 300:
80-
raise RequestFailure(resp.status, await resp.text())
81-
return True
56+
req_url = f"/webhooks/{bot_id}/{token}/messages/{message_id}"
57+
route = CustomRoute("DELETE", req_url)
58+
return self._discord.http.request(route)

0 commit comments

Comments
 (0)