Skip to content

Commit 44f753e

Browse files
committed
♻️ refactor JSON serialization functions to private module
1 parent d5263c7 commit 44f753e

File tree

6 files changed

+37
-42
lines changed

6 files changed

+37
-42
lines changed

discord/gateway.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
from .activity import BaseActivity
4343
from .enums import SpeakingState
4444
from .errors import ConnectionClosed, InvalidArgument
45+
from .utils.private import _from_json, _to_json
4546

4647
_log = logging.getLogger(__name__)
4748

@@ -450,7 +451,7 @@ async def received_message(self, msg, /):
450451
self._buffer = bytearray()
451452

452453
self.log_receive(msg)
453-
msg = utils._from_json(msg)
454+
msg = _from_json(msg)
454455

455456
_log.debug("For Shard ID %s: WebSocket Event: %s", self.shard_id, msg)
456457
event = msg.get("t")
@@ -637,15 +638,15 @@ async def send(self, data, /):
637638

638639
async def send_as_json(self, data):
639640
try:
640-
await self.send(utils._to_json(data))
641+
await self.send(_to_json(data))
641642
except RuntimeError as exc:
642643
if not self._can_handle_close():
643644
raise ConnectionClosed(self.socket, shard_id=self.shard_id) from exc
644645

645646
async def send_heartbeat(self, data):
646647
# This bypasses the rate limit handling code since it has a higher priority
647648
try:
648-
await self.socket.send_str(utils._to_json(data))
649+
await self.socket.send_str(_to_json(data))
649650
except RuntimeError as exc:
650651
if not self._can_handle_close():
651652
raise ConnectionClosed(self.socket, shard_id=self.shard_id) from exc
@@ -671,7 +672,7 @@ async def change_presence(self, *, activity=None, status=None, since=0.0):
671672
},
672673
}
673674

674-
sent = utils._to_json(payload)
675+
sent = _to_json(payload)
675676
_log.debug('Sending "%s" to change status', sent)
676677
await self.send(sent)
677678

@@ -774,7 +775,7 @@ async def _hook(self, *args):
774775

775776
async def send_as_json(self, data):
776777
_log.debug("Sending voice websocket frame: %s.", data)
777-
await self.ws.send_str(utils._to_json(data))
778+
await self.ws.send_str(_to_json(data))
778779

779780
send_heartbeat = send_as_json
780781

@@ -931,7 +932,7 @@ async def poll_event(self):
931932
# This exception is handled up the chain
932933
msg = await asyncio.wait_for(self.ws.receive(), timeout=30.0)
933934
if msg.type is aiohttp.WSMsgType.TEXT:
934-
await self.received_message(utils._from_json(msg.data))
935+
await self.received_message(_from_json(msg.data))
935936
elif msg.type is aiohttp.WSMsgType.ERROR:
936937
_log.debug("Received %s", msg)
937938
raise ConnectionClosed(self.ws, shard_id=None) from msg.data

discord/http.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434

3535
import aiohttp
3636

37-
from .utils.private import get_mime_type_for_image
37+
from .utils.private import get_mime_type_for_image, _to_json, _from_json
3838
from . import __version__, utils
3939
from .errors import (
4040
DiscordServerError,
@@ -98,7 +98,7 @@ async def json_or_text(response: aiohttp.ClientResponse) -> dict[str, Any] | str
9898
text = await response.text(encoding="utf-8")
9999
try:
100100
if response.headers["content-type"] == "application/json":
101-
return utils._from_json(text)
101+
return _from_json(text)
102102
except KeyError:
103103
# Thanks Cloudflare
104104
pass
@@ -261,7 +261,7 @@ async def request(
261261
# some checking if it's a JSON request
262262
if "json" in kwargs:
263263
headers["Content-Type"] = "application/json"
264-
kwargs["data"] = utils._to_json(kwargs.pop("json"))
264+
kwargs["data"] = _to_json(kwargs.pop("json"))
265265

266266
try:
267267
reason = kwargs.pop("reason")
@@ -569,7 +569,7 @@ def send_multipart_helper(
569569
}
570570
)
571571
payload["attachments"] = attachments
572-
form[0]["value"] = utils._to_json(payload)
572+
form[0]["value"] = _to_json(payload)
573573
return self.request(route, form=form, files=files)
574574

575575
def send_files(
@@ -642,7 +642,7 @@ def edit_multipart_helper(
642642
payload["attachments"] = attachments
643643
else:
644644
payload["attachments"].extend(attachments)
645-
form[0]["value"] = utils._to_json(payload)
645+
form[0]["value"] = _to_json(payload)
646646

647647
return self.request(route, form=form, files=files)
648648

@@ -1242,7 +1242,7 @@ def start_forum_thread(
12421242
)
12431243

12441244
payload["attachments"] = attachments
1245-
form[0]["value"] = utils._to_json(payload)
1245+
form[0]["value"] = _to_json(payload)
12461246
return self.request(route, form=form, reason=reason)
12471247
return self.request(route, json=payload, reason=reason)
12481248

@@ -2589,7 +2589,7 @@ def _edit_webhook_helper(
25892589
form: list[dict[str, Any]] = [
25902590
{
25912591
"name": "payload_json",
2592-
"value": utils._to_json(payload),
2592+
"value": _to_json(payload),
25932593
}
25942594
]
25952595

discord/utils/__init__.py

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525

2626
from __future__ import annotations
2727

28-
import json
2928
from typing import (
3029
TYPE_CHECKING,
3130
Any,
@@ -56,13 +55,6 @@
5655
escape_markdown,
5756
)
5857

59-
try:
60-
import msgspec
61-
except ModuleNotFoundError:
62-
HAS_MSGSPEC = False
63-
else:
64-
HAS_MSGSPEC = True
65-
6658
DISCORD_EPOCH = 1420070400000
6759

6860

@@ -181,18 +173,3 @@ async def get_or_fetch(obj, attr: str, id: int, *, default: Any = MISSING) -> An
181173
else:
182174
raise
183175
return getter
184-
185-
186-
if HAS_MSGSPEC:
187-
188-
def _to_json(obj: Any) -> str: # type: ignore
189-
return msgspec.json.encode(obj).decode("utf-8")
190-
191-
_from_json = msgspec.json.decode # type: ignore
192-
193-
else:
194-
195-
def _to_json(obj: Any) -> str:
196-
return json.dumps(obj, separators=(",", ":"), ensure_ascii=True)
197-
198-
_from_json = json.loads

discord/utils/private.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,3 +530,20 @@ def decorator(func: Callable[[T], T_co]) -> CachedSlotProperty[T, T_co]:
530530
return CachedSlotProperty(name, func)
531531

532532
return decorator
533+
534+
535+
try:
536+
import msgspec
537+
538+
def _to_json(obj: Any) -> str: # type: ignore
539+
return msgspec.json.encode(obj).decode("utf-8")
540+
541+
_from_json = msgspec.json.decode # type: ignore
542+
543+
except ModuleNotFoundError:
544+
import json
545+
546+
def _to_json(obj: Any) -> str:
547+
return json.dumps(obj, separators=(",", ":"), ensure_ascii=True)
548+
549+
_from_json = json.loads

discord/webhook/async_.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737
import aiohttp
3838

39-
from ..utils.private import bytes_to_base64_data, get_as_snowflake, parse_ratelimit_header
39+
from ..utils.private import bytes_to_base64_data, get_as_snowflake, parse_ratelimit_header, _to_json
4040
from .. import utils
4141
from ..asset import Asset
4242
from ..channel import ForumChannel, PartialMessageable
@@ -135,7 +135,7 @@ async def request(
135135

136136
if payload is not None:
137137
headers["Content-Type"] = "application/json"
138-
to_send = utils._to_json(payload)
138+
to_send = _to_json(payload)
139139

140140
if auth_token is not None:
141141
headers["Authorization"] = f"Bot {auth_token}"
@@ -509,7 +509,7 @@ def create_interaction_response(
509509
)
510510
if attachments:
511511
payload["data"]["attachments"] = attachments
512-
form[0]["value"] = utils._to_json(payload)
512+
form[0]["value"] = _to_json(payload)
513513

514514
route = Route(
515515
"POST",
@@ -701,7 +701,7 @@ def handle_message_parameters(
701701
payload["thread_name"] = thread_name
702702

703703
if multipart_files:
704-
multipart.append({"name": "payload_json", "value": utils._to_json(payload)})
704+
multipart.append({"name": "payload_json", "value": _to_json(payload)})
705705
payload = None
706706
multipart += multipart_files
707707

discord/webhook/sync.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
from urllib.parse import quote as urlquote
4242

4343
from .. import utils
44-
from ..utils.private import parse_ratelimit_header, bytes_to_base64_data
44+
from ..utils.private import parse_ratelimit_header, bytes_to_base64_data, _to_json
4545
from ..channel import PartialMessageable
4646
from ..errors import (
4747
DiscordServerError,
@@ -125,7 +125,7 @@ def request(
125125

126126
if payload is not None:
127127
headers["Content-Type"] = "application/json"
128-
to_send = utils._to_json(payload)
128+
to_send = _to_json(payload)
129129

130130
if auth_token is not None:
131131
headers["Authorization"] = f"Bot {auth_token}"

0 commit comments

Comments
 (0)