/
client.py
1176 lines (973 loc) · 45.3 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
try:
from orjson import dumps, loads
except ImportError:
from json import dumps, loads
from asyncio import (
FIRST_COMPLETED,
Event,
Lock,
Task,
TimeoutError,
create_task,
get_event_loop,
get_running_loop,
new_event_loop,
wait,
wait_for,
)
from contextlib import suppress
from enum import IntEnum
from sys import platform, version_info
from time import perf_counter
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
from zlib import decompressobj
from aiohttp import ClientWebSocketResponse, WSMessage, WSMsgType
from ...base import __version__, get_logger
from ...client.enums import ComponentType, InteractionType, OptionType
from ...client.models import Option
from ...utils.missing import MISSING
from ..dispatch import Listener
from ..error import LibraryException
from ..http.client import HTTPClient
from ..models.flags import Intents
from ..models.guild import Guild
from ..models.gw import GuildMember, GuildRole, VoiceState
from ..models.member import Member
from ..models.message import Message
from ..models.misc import Snowflake
from ..models.presence import ClientPresence
from ..models.role import Role
from .heartbeat import _Heartbeat
from .ratelimit import WSRateLimit
if TYPE_CHECKING:
from ...client.context import _Context
from ..cache import Cache, Storage
from ..models.gw import GuildMembers
log = get_logger("gateway")
__all__ = ("WebSocketClient", "OpCodeType")
class OpCodeType(IntEnum):
"""
An enumerable object for the Gateway's OPCODE result state.
This is representative of the OPCodes generated by the WebSocket.
.. note::
Equivalent of `Gateway Opcodes <https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-opcodes>`_ in the Discord API.
"""
DISPATCH = 0
HEARTBEAT = 1
IDENTIFY = 2
PRESENCE = 3
VOICE_STATE = 4
VOICE_PING = 5
RESUME = 6
RECONNECT = 7
REQUEST_MEMBERS = 8
INVALIDATE_SESSION = 9
HELLO = 10
HEARTBEAT_ACK = 11
GUILD_SYNC = 12
class WebSocketClient:
"""
A class representing the client's connection to the Gateway via. WebSocket.
.. note ::
The ``__heartbeat_event`` Event object is different from the one built in to the Heartbeater object.
The latter is used to trace heartbeat acknowledgement.
:ivar AbstractEventLoop _loop: The asynchronous event loop.
:ivar Listener _dispatch: The built-in event dispatcher.
:ivar WSRateLimit _ratelimiter: The websocket ratelimiter object.
:ivar HTTPClient _http: The user-facing HTTP client.
:ivar ClientWebSocketResponse _client: The WebSocket data of the connection.
:ivar Event __closed: Whether the connection has been closed or not.
:ivar dict _options: The connection options made during connection.
:ivar Intents _intents: The gateway intents used for connection.
:ivar dict _ready: The contents of the application returned when ready.
:ivar _Heartbeat __heartbeater: The context state of a "heartbeat" made to the Gateway.
:ivar Event __heartbeat_event: The state of the overall heartbeat process.
:ivar Optional[List[Tuple[int]]] __shard: The shards used during connection.
:ivar Optional[ClientPresence] __presence: The presence used in connection.
:ivar Event ready: The ready state of the client as an ``asyncio.Event``.
:ivar Task _task: The task containing the heartbeat manager process.
:ivar bool __started: Whether the client has started.
:ivar Optional[str] session_id: The ID of the ongoing session.
:ivar Optional[int] sequence: The sequence identifier of the ongoing session.
:ivar float _last_send: The latest time of the last send_packet function call since connection creation, in seconds.
:ivar float _last_ack: The latest time of the last ``HEARTBEAT_ACK`` event since connection creation, in seconds.
:ivar Optional[str] resume_url: The Websocket ratelimit URL for resuming connections, if any.
:ivar Optional[str] ws_url: The Websocket URL for instantiating connections without resuming.
:ivar Lock reconnect_lock: The lock used for reconnecting the client.
:ivar Lock _closing_lock: The lock used for closing the client.
:ivar Optional[Task] __stopping: The task containing stopping the client, if any.
"""
__slots__ = (
"_loop",
"_dispatch",
"__unavailable_guilds",
"_ratelimiter",
"_http",
"_client",
"_cache",
"__closed", # placeholder to work with variables atm. its event variant of "_closed"
"_options",
"_intents",
"_ready",
"__heartbeater",
"__shard",
"__presence",
"_zlib",
"_task",
"__heartbeat_event",
"__started",
"session_id",
"sequence",
"ready",
"_last_send",
"_last_ack",
"resume_url",
"ws_url",
"reconnect_lock",
"_closing_lock",
"__stopping",
)
def __init__(
self,
token: str,
intents: Intents,
cache: "Cache",
session_id: Optional[str] = MISSING,
sequence: Optional[int] = MISSING,
shards: Optional[List[Tuple[int]]] = MISSING,
presence: Optional[ClientPresence] = MISSING,
) -> None:
"""
:param str token: The token of the application for connecting to the Gateway.
:param Intents intents: The Gateway intents of the application for event dispatch.
:param Optional[str] session_id: The ID of the session if trying to reconnect. Defaults to ``None``.
:param Optional[int] sequence: The identifier sequence if trying to reconnect. Defaults to ``None``.
:param Optional[List[Tuple[int]]] shards: The list of shards for the application's initial connection, if provided. Defaults to ``None``.
:param Optional[ClientPresence] presence: The presence shown on an application once first connected. Defaults to ``None``.
"""
try:
self._loop = get_event_loop() if version_info < (3, 10) else get_running_loop()
except RuntimeError:
self._loop = new_event_loop()
self._dispatch: Listener = Listener()
self.__unavailable_guilds = []
self._ratelimiter = (
WSRateLimit(loop=self._loop) if version_info < (3, 10) else WSRateLimit()
)
self.__heartbeater: _Heartbeat = _Heartbeat(
loop=self._loop if version_info < (3, 10) else None
)
self._http: HTTPClient = token
self._cache: "Cache" = cache
self._client: Optional["ClientWebSocketResponse"] = None
self.__closed: Event = Event(loop=self._loop) if version_info < (3, 10) else Event()
self._options: dict = {
"max_msg_size": 0,
"timeout": 60,
"autoclose": False,
"compress": 0,
"headers": {
"User-Agent": f"DiscordBot (https://github.com/interactions-py/library {__version__}) "
},
}
self._intents: Intents = intents
self.__shard: Optional[List[Tuple[int]]] = None if shards is MISSING else shards
self.__presence: Optional[ClientPresence] = None if presence is MISSING else presence
self._task: Optional[Task] = None
self.__heartbeat_event = Event(loop=self._loop) if version_info < (3, 10) else Event()
self.__started: bool = False
self.session_id: Optional[str] = None if session_id is MISSING else session_id
self.sequence: Optional[str] = None if sequence is MISSING else sequence
self.ready: Event = Event(loop=self._loop) if version_info < (3, 10) else Event()
self._last_send: float = perf_counter()
self._last_ack: float = perf_counter()
self.resume_url: Optional[str] = None
self.ws_url: Optional[str] = None
self.reconnect_lock = Lock(loop=self._loop) if version_info < (3, 10) else Lock()
self._closing_lock = Event(loop=self._loop) if version_info < (3, 10) else Event()
self.__stopping: Optional[Task] = None
self._zlib = decompressobj()
@property
def latency(self) -> float:
"""
The latency of the connection, in seconds.
"""
return self._last_ack - self._last_send
async def run_heartbeat(self) -> None:
"""Controls the heartbeat manager. Do note that this shouldn't be executed by outside processes."""
if self.__heartbeat_event.is_set(): # resets task of heartbeat event mgr loop
# Because we're hardresetting the process every instance its called, also helps with recursion
self.__heartbeat_event.clear()
if not self.__heartbeater.event.is_set(): # resets task of heartbeat ack event
self.__heartbeater.event.set()
try:
await self._manage_heartbeat()
except Exception:
self._closing_lock.set()
log.exception("Heartbeater exception.")
async def _manage_heartbeat(self) -> None:
"""Manages the heartbeat loop."""
log.debug(f"Sending heartbeat every {self.__heartbeater.delay / 1000} seconds...")
while not self.__heartbeat_event.is_set():
log.debug("Sending heartbeat...")
if not self.__heartbeater.event.is_set():
log.debug("HEARTBEAT_ACK missing, reconnecting...")
await self._reconnect(True) # resume here.
self.__heartbeater.event.clear()
await self.__heartbeat()
try:
# wait for next iteration, accounting for latency
await wait_for(
self.__heartbeat_event.wait(), timeout=self.__heartbeater.delay / 1000
)
except TimeoutError:
continue # Then we can check heartbeat ack this way and then like it autorestarts.
else:
return # break loop because something went wrong.
async def run(self) -> None:
"""
Handles the client's connection with the Gateway.
"""
if isinstance(self._http, str):
self._http = HTTPClient(self._http, self._cache)
url = await self._http.get_gateway()
self.ws_url = url
self._client = await self._http._req._session.ws_connect(url, **self._options)
data = await self.__receive_packet(True) # First data is the hello packet.
self.__heartbeater.delay = data["d"]["heartbeat_interval"]
self._task = create_task(self.run_heartbeat())
await self.__identify(self.__shard, self.__presence)
self.__closed.set()
self.__heartbeater.event.set()
while True:
if self.__stopping is None:
self.__stopping = create_task(self._closing_lock.wait())
_receive = create_task(self.__receive_packet())
done, _ = await wait({self.__stopping, _receive}, return_when=FIRST_COMPLETED)
# Using asyncio.wait to find which one reaches first, when its *closed* or when a message is
# *received*
if _receive in done:
msg = await _receive
else:
await self.__stopping
_receive.cancel()
return
if msg is not None: # this can happen
await self._handle_stream(msg)
async def _handle_stream(self, stream: Dict[str, Any]):
"""
Parses raw stream data recieved from the Gateway, including Gateway opcodes and events.
.. note ::
This should never be called directly.
:param Dict[str, Any] stream: The packet stream to handle.
"""
op: Optional[int] = stream.get("op")
event: Optional[str] = stream.get("t")
data: Optional[Dict[str, Any]] = stream.get("d")
if seq := stream.get("s"):
self.sequence = seq
if op != OpCodeType.DISPATCH:
log.debug(data)
if op == OpCodeType.HEARTBEAT:
await self.__heartbeat()
if op == OpCodeType.HEARTBEAT_ACK:
self._last_ack = perf_counter()
log.debug("HEARTBEAT_ACK")
self.__heartbeater.event.set()
if op == OpCodeType.INVALIDATE_SESSION:
log.debug("INVALID_SESSION")
self.ready.clear()
await self._reconnect(bool(data))
if op == OpCodeType.RECONNECT:
log.debug("RECONNECT")
await self._reconnect(True)
elif event == "RESUMED":
log.debug(f"RESUMED (session_id: {self.session_id}, seq: {self.sequence})")
elif event == "READY":
self.ready.set()
self._dispatch.dispatch("on_ready")
self._ready = data
self.__unavailable_guilds = [i["id"] for i in data["guilds"]]
self.session_id = data["session_id"]
self.resume_url = data["resume_gateway_url"]
if not self.__started:
self.__started = True
self._dispatch.dispatch("on_start")
log.debug(f"READY (session_id: {self.session_id}, seq: {self.sequence})")
else:
log.debug(f"{event}: {str(data).encode('utf-8')}")
self._dispatch_event(event, data)
async def wait_until_ready(self) -> None:
"""Waits for the client to become ready according to the Gateway."""
await self.ready.wait()
def _dispatch_event(self, event: str, data: dict) -> None:
"""
Dispatches an event from the Gateway.
:param str event: The name of the event.
:param dict data: The data for the event.
"""
self._dispatch.dispatch("raw_socket_create", event, data)
path: str = "interactions"
path += ".models" if event == "INTERACTION_CREATE" else ".api.models"
if event == "INTERACTION_CREATE":
if data.get("type"):
_context = self.__contextualize(data)
_name: str = ""
__args: list = [_context]
__kwargs: dict = {}
if data["type"] == InteractionType.APPLICATION_COMMAND:
_name = f"command_{_context.data.name}"
if options := _context.data.options:
for option in options:
_type = self.__option_type_context(
_context,
option.type.value,
)
if _type:
_type[option.value]._client = self._http
option.value = _type[option.value]
_option = self.__sub_command_context(option, _context)
__kwargs.update(_option)
self._dispatch.dispatch("on_command", _context)
elif data["type"] == InteractionType.MESSAGE_COMPONENT:
_name = f"component_{_context.data.custom_id}"
if values := _context.data.values:
if _context.data.component_type.value not in {5, 6, 7, 8}:
__args.append(values)
else:
_list = [] # temp storage for items
_data = self.__select_option_type_context(
_context, _context.data.component_type.value
) # resolved.
for value in values:
_list.append(_data[value])
__args.append(_list)
self._dispatch.dispatch("on_component", _context)
elif data["type"] == InteractionType.APPLICATION_COMMAND_AUTOCOMPLETE:
_name = f"autocomplete_{_context.data.name}"
if _context.data.options:
for option in _context.data.options:
if option.type not in (
OptionType.SUB_COMMAND,
OptionType.SUB_COMMAND_GROUP,
):
if option.focused:
__name, _value = self.__sub_command_context(option, _context)
_name += f"_{__name}" if __name else ""
if _value:
__args.append(_value)
break
elif option.type == OptionType.SUB_COMMAND:
for _option in option.options:
if _option.focused:
__name, _value = self.__sub_command_context(
_option, _context
)
_name += f"_{__name}" if __name else ""
if _value:
__args.append(_value)
break
elif option.type == OptionType.SUB_COMMAND_GROUP:
for _option in option.options:
for __option in _option.options:
if __option.focused:
__name, _value = self.__sub_command_context(
__option, _context
)
_name += f"_{__name}" if __name else ""
if _value:
__args.append(_value)
break
break
self._dispatch.dispatch("on_autocomplete", _context)
elif data["type"] == InteractionType.MODAL_SUBMIT:
_name = f"modal_{_context.data.custom_id}"
if _context.data.components:
for component in _context.data.components:
if component.components:
__args.append([_value.value for _value in component.components][0])
self._dispatch.dispatch("on_modal", _context)
self._dispatch.dispatch(_name, *__args, **__kwargs)
self._dispatch.dispatch("on_interaction", _context)
self._dispatch.dispatch("on_interaction_create", _context)
else:
log.warning(
"Context is being created for the interaction, but no type is specified. Skipping..."
)
elif event not in {"TYPING_START", "VOICE_SERVER_UPDATE"}:
name: str = event.lower()
try:
data["_client"] = self._http
_event_path: list = [section.capitalize() for section in name.split("_")]
_name: str = _event_path[0] if len(_event_path) < 3 else "".join(_event_path[:-1])
model = getattr(__import__(path), _name)
obj = model(**data)
guild_obj = guild_model = None
if model is GuildRole:
guild_obj = (
Role(**role_data, _client=self._http)
if (role_data := data.get("role"))
else None
)
guild_model = Role
elif model is GuildMember:
guild_obj = Member(**data)
guild_model = Member
_cache: "Storage" = self._http.cache[model]
_guild_cache: "Storage" = self._http.cache[guild_model]
ids = None
id = self.__get_object_id(data, obj, model)
if id is None:
ids = self.__get_object_ids(obj, model)
if "_create" in name or "_add" in name:
if name == "guild_create":
if id and str(id) in self.__unavailable_guilds:
self.__unavailable_guilds.remove(str(id))
else:
self._dispatch.dispatch("on_guild_join", obj)
self._dispatch.dispatch(f"on_{name}", obj)
if id:
_cache.merge(obj, id)
if guild_obj:
_guild_cache.add(guild_obj, id)
self.__modify_guild_cache(
name, data, guild_model or model, guild_obj or obj, id, ids
)
elif "_update" in name:
self._dispatch.dispatch(f"on_raw_{name}", obj)
if not id and ids is None:
return self._dispatch.dispatch(f"on_{name}", obj)
self.__modify_guild_cache(
name, data, guild_model or model, guild_obj or obj, id, ids
)
if ids is not None:
# Not cached but it needed for guild_emojis_update and guild_stickers_update events
return self._dispatch.dispatch(f"on_{name}", obj)
if id is None:
return
if guild_obj:
old_guild_obj = _guild_cache.get(id)
if old_guild_obj:
old_guild_obj.update(**guild_obj._json)
else:
_guild_cache.add(guild_obj, id)
old_obj = _cache.get(id)
if old_obj:
before = model(**old_obj._json)
old_obj.update(**data)
else:
before = None
old_obj = obj
_cache.add(old_obj, id)
if event == "VOICE_STATE_UPDATE" and not obj.channel_id: # user left
del _cache[obj.user_id]
self._dispatch.dispatch(
f"on_{name}", before, old_obj
) # give previously stored and new one
elif "_remove" in name or "_delete" in name:
self._dispatch.dispatch(
f"on_raw_{name}", obj
) # Deprecated. Remove this in the future.
old_obj = None
if id:
_guild_cache.pop(id)
self.__modify_guild_cache(
name, data, guild_model or model, guild_obj or obj, id, ids
)
old_obj = _cache.pop(id)
elif ids is not None and "message" in name:
# currently only message has '_delete_bulk' event but ig better keep this condition for future.
_message_cache: "Storage" = self._http.cache[Message]
for message_id in ids:
_message_cache.pop(message_id)
self._dispatch.dispatch(f"on_{name}", old_obj or obj)
elif "guild_members_chunk" in name:
self.__modify_guild_cache(name, data, model, obj, ids=ids)
_member_cache: "Storage" = self._http.cache[Member]
obj: GuildMembers
for member in obj.members:
member._guild_id = obj.guild_id
_member_cache.add(member, (obj.guild_id, member.id))
self._dispatch.dispatch(f"on_{name}", obj)
else:
self._dispatch.dispatch(f"on_{name}", obj)
except AttributeError as error:
log.warning(f"An error occurred dispatching {name}: {error}")
def __get_object_id(
self, data: dict, obj: Any, model: type
) -> Optional[Union[Snowflake, Tuple[Snowflake, Snowflake]]]:
"""
Gets an ID from object.
:param dict data: The data for the event.
:param Any obj: The object of the event.
:param type model: The model of the event.
:return: Object ID
:rtype: Optional[Union[Snowflake, Tuple[Snowflake, Snowflake]]]
"""
if isinstance(obj, (Member, GuildMember)):
id = (Snowflake(data["guild_id"]), obj.id)
if isinstance(obj, VoiceState):
id = obj.user_id
else:
id = getattr(obj, "id", None)
if id is not None:
return id
if model.__name__ == "GuildScheduledEventUser":
id = obj.guild_scheduled_event_id
elif model.__name__ == "Presence":
id = obj.user.id
elif model.__name__ in [
"GuildBan",
# Extend this for everything that starts with 'Guild' and should not be cached
]:
id = None
elif model.__name__.startswith("Guild"):
model_name = model.__name__[5:].lower()
if (_data := getattr(obj, model_name, None)) and not isinstance(_data, list):
id = getattr(_data, "id") if not isinstance(_data, dict) else Snowflake(_data["id"])
elif hasattr(obj, f"{model_name}_id"):
id = getattr(obj, f"{model_name}_id", None)
return id
def __get_object_ids(self, obj: Any, model: type) -> Optional[List[Snowflake]]:
"""
Gets a list of ids of object.
:param Any obj: The object of the event.
:param type model: The model of the event.
:return: Object IDs
:rtype: Optional[Union[Snowflake, Tuple[Snowflake, Snowflake]]]
"""
ids = getattr(obj, "ids", None)
if ids is not None:
return ids
if model.__name__.startswith("Guild"):
model_name = model.__name__[5:].lower()
if (_data := getattr(obj, model_name, None)) is not None:
ids = [
getattr(_obj, "id") if not isinstance(_obj, dict) else Snowflake(_obj["id"])
for _obj in _data
]
return ids
def __modify_guild_cache(
self,
name: str,
data: dict,
model: Any,
obj: Any,
id: Optional[Snowflake] = None,
ids: Optional[List[Snowflake]] = None,
):
"""
Modifies guild cache.
:param str event: The name of the event.
:param dict data: The data for the event.
:param Any obj: The object of the event.
:param Any model: The model of the event.
"""
if not (
(guild_id := data.get("guild_id"))
and not isinstance(obj, Guild)
and "message" not in name
and (id is not None or ids is not None)
and (guild := self._http.cache[Guild].get(Snowflake(guild_id)))
):
return
attr: str = model.__name__.lower()
if attr.startswith("guild"):
attr = attr[5:]
if attr == "threadmembers": # TODO: Figure out why this here
return
if not attr.endswith("s"):
attr = f"{attr}s"
iterable = getattr(guild, attr, None)
if iterable is not None and isinstance(iterable, list):
if "_create" in name or "_add" in name:
iterable.append(obj)
elif id:
_id = id[1] if isinstance(id, tuple) else id
for index, __obj in enumerate(iterable):
if __obj.id == _id:
if "_remove" in name or "_delete" in name:
iterable.remove(__obj)
elif "_update" in name and hasattr(obj, "id"):
iterable[index] = obj
break
elif ids is not None and (objs := getattr(obj, attr, None)) is not None:
if "_update" in name:
iterable.clear()
iterable.extend(objs)
elif "_chunk" in name:
for _obj in objs:
for index, __obj in enumerate(iterable):
if __obj.id == _obj.id:
iterable[index] = _obj
break
else:
iterable.append(_obj)
setattr(guild, attr, iterable)
self._http.cache[Guild].add(guild)
def __contextualize(self, data: dict) -> "_Context":
"""
Takes raw data given back from the Gateway
and gives "context" based off of what it is.
:param dict data: The data from the Gateway.
:return: The context object.
:rtype: Any
"""
if data["type"] != InteractionType.PING:
_context: str = ""
if data["type"] in (
InteractionType.APPLICATION_COMMAND,
InteractionType.APPLICATION_COMMAND_AUTOCOMPLETE,
InteractionType.MODAL_SUBMIT,
):
_context = "CommandContext"
elif data["type"] == InteractionType.MESSAGE_COMPONENT:
_context = "ComponentContext"
data["_client"] = self._http
context: Type["_Context"] = getattr(__import__("interactions.client.context"), _context)
return context(**data)
def __sub_command_context(self, option: Option, context: "_Context") -> Union[Tuple[str], dict]:
"""
Checks if an application command schema has sub commands
needed for argument collection.
:param Option option: The option object
:param _Context context: The context to refer subcommands from.
:return: A dictionary of the collected options, if any.
:rtype: Union[Tuple[str], dict]
"""
__kwargs: dict = {}
def _check_auto(_option: Option) -> Optional[Tuple[str]]:
return (_option.name, _option.value) if _option.focused else None
check = _check_auto(option)
if check:
return check
if options := option.options:
if option.type == OptionType.SUB_COMMAND:
__kwargs["sub_command"] = option.name
for sub_option in options:
_check = _check_auto(sub_option)
_type = self.__option_type_context(
context,
sub_option.type,
)
if _type:
_type[sub_option.value]._client = self._http
sub_option.value = _type[sub_option.value]
if _check:
return _check
__kwargs[sub_option.name] = sub_option.value
elif option.type == OptionType.SUB_COMMAND_GROUP:
__kwargs["sub_command_group"] = option.name
for _group_option in option.options:
_check_auto(_group_option)
__kwargs["sub_command"] = _group_option.name
for sub_option in _group_option.options:
_check = _check_auto(sub_option)
_type = self.__option_type_context(
context,
sub_option.type,
)
if _type:
_type[sub_option.value]._client = self._http
sub_option.value = _type[sub_option.value]
if _check:
return _check
__kwargs[sub_option.name] = sub_option.value
elif option.type == OptionType.SUB_COMMAND:
# sub_command_groups must have options so there is no extra check needed for those
__kwargs["sub_command"] = option.name
elif (name := option.name) is not None and (value := option.value) is not None:
__kwargs[name] = value
return __kwargs
def __option_type_context(self, context: "_Context", type: int) -> dict:
"""
Looks up the type of option respective to the existing
option types.
:param _Context context: The context to refer types from.
:param int type: The option type.
:return: The option type context.
:rtype: dict
"""
_resolved = {}
if type == OptionType.USER.value:
_resolved = (
context.data.resolved.members if context.guild_id else context.data.resolved.users
)
if context.guild_id:
with suppress(AttributeError): # edge-case
for key in _resolved.keys():
_resolved[key]._extras["guild_id"] = context.guild_id
elif type == OptionType.CHANNEL.value:
_resolved = context.data.resolved.channels
elif type == OptionType.ROLE.value:
_resolved = context.data.resolved.roles
elif type == OptionType.ATTACHMENT.value:
_resolved = context.data.resolved.attachments
elif type == OptionType.MENTIONABLE.value:
_roles = context.data.resolved.roles if context.data.resolved.roles is not None else {}
_members = (
context.data.resolved.members if context.guild_id else context.data.resolved.users
)
if context.guild_id:
with suppress(AttributeError): # edge-case
for key in _members.keys():
_members[key]._extras["guild_id"] = context.guild_id
_resolved = {
**(_members if _members is not None else {}),
**_roles,
}
return _resolved
def __select_option_type_context(self, context: "_Context", type: int) -> dict:
"""
Looks up the type of select menu respective to the existing option types. This is applicable for non-string
select menus.
:param context: The context to refer types from.
:type context: object
:param type: The option type.
:type type: int
:return: The select menu type context.
:rtype: dict
"""
_resolved = {}
if type == ComponentType.USER_SELECT.value:
_resolved = (
context.data.resolved.members if context.guild_id else context.data.resolved.users
)
if context.guild_id:
with suppress(AttributeError): # edge-case
for key in _resolved.keys():
_resolved[key]._extras["guild_id"] = context.guild_id
elif type == ComponentType.CHANNEL_SELECT.value:
_resolved = context.data.resolved.channels
elif type == ComponentType.ROLE_SELECT.value:
_resolved = context.data.resolved.roles
elif type == ComponentType.MENTIONABLE_SELECT.value:
if (
users := context.data.resolved.members
if context.guild_id
else context.data.resolved.users
):
if context.guild_id:
with suppress(AttributeError): # edge-case
for key in users.keys():
users[key]._extras["guild_id"] = context.guild_id
_resolved.update(**users)
if roles := context.data.resolved.roles:
_resolved.update(**roles)
return _resolved
async def _reconnect(self, to_resume: bool, code: Optional[int] = 1012) -> None:
"""
Restarts the client's connection and heartbeat with the Gateway.
"""
self.ready.clear()
async with self.reconnect_lock:
self.__closed.clear()
if self._client is not None:
await self._client.close(code=code)
self._client = None
self._zlib = decompressobj()
# We need to check about existing heartbeater tasks for edge cases.
if self._task:
self._task.cancel()
if self.__heartbeat_event.is_set():
self.__heartbeat_event.clear() # Because we're hardresetting the process
if not to_resume:
url = self.ws_url if self.ws_url else await self._http.get_gateway()
else:
url = f"{self.resume_url}?v=10&encoding=json&compress=zlib-stream"
self._client = await self._http._req._session.ws_connect(url, **self._options)
data = await self.__receive_packet(True) # First data is the hello packet.
self.__heartbeater.delay = data["d"]["heartbeat_interval"]
self._task = create_task(self.run_heartbeat())
if not to_resume:
await self.__identify(self.__shard, self.__presence)
else:
await self.__resume()
self.__closed.set()
self.__heartbeat_event.set()
async def __receive_packet(self, ignore_lock: bool = False) -> Optional[Dict[str, Any]]:
"""
Receives a stream of packets sent from the Gateway in an async process.
:return: The packet stream.
:rtype: Optional[Dict[str, Any]]
"""
buffer = bytearray()
while True:
if not ignore_lock:
# meaning if we're reconnecting or something because of tasks
await self.__closed.wait()
packet: WSMessage = await self._client.receive()
if packet.type == WSMsgType.CLOSE:
log.debug(f"Disconnecting from gateway = {packet.data}::{packet.extra}")
if packet.data >= 4000:
# This means that the error code is 4000+, which may signify Discord-provided error codes.
raise LibraryException(packet.data)
if ignore_lock:
raise LibraryException(
message="Discord unexpectedly wants to close the WS on receiving by force.",
severity=50,
)
await self._reconnect(packet.data != 1000, packet.data)
continue
elif packet.type == WSMsgType.CLOSED:
# We need to wait/reconnect depending about other event holders.
if ignore_lock:
raise LibraryException(
message="Discord unexpectedly closed on receiving by force.", severity=50
)
if not self.__closed.is_set():
await self.__closed.wait()
# Edge case on force reconnecting if we dont
else:
await self._reconnect(True)
elif packet.type == WSMsgType.CLOSING:
if ignore_lock:
raise LibraryException(
message="Discord unexpectedly closing on receiving by force.", severity=50
)