-
Notifications
You must be signed in to change notification settings - Fork 139
/
client.py
3213 lines (2574 loc) · 106 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
# SPDX-License-Identifier: MIT
from __future__ import annotations
import asyncio
import logging
import signal
import sys
import traceback
import types
import warnings
from datetime import datetime, timedelta
from errno import ECONNRESET
from typing import (
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Dict,
Generator,
List,
Literal,
Mapping,
NamedTuple,
Optional,
Sequence,
Tuple,
TypedDict,
TypeVar,
Union,
overload,
)
import aiohttp
from . import abc, utils
from .activity import ActivityTypes, BaseActivity, create_activity
from .app_commands import (
APIMessageCommand,
APISlashCommand,
APIUserCommand,
ApplicationCommand,
GuildApplicationCommandPermissions,
)
from .appinfo import AppInfo
from .application_role_connection import ApplicationRoleConnectionMetadata
from .backoff import ExponentialBackoff
from .channel import PartialMessageable, _threaded_channel_factory
from .emoji import Emoji
from .entitlement import Entitlement
from .enums import ApplicationCommandType, ChannelType, Event, Status
from .errors import (
ConnectionClosed,
GatewayNotFound,
HTTPException,
InvalidData,
PrivilegedIntentsRequired,
SessionStartLimitReached,
)
from .flags import ApplicationFlags, Intents, MemberCacheFlags
from .gateway import DiscordWebSocket, ReconnectWebSocket
from .guild import Guild, GuildBuilder
from .guild_preview import GuildPreview
from .http import HTTPClient
from .i18n import LocalizationProtocol, LocalizationStore
from .invite import Invite
from .iterators import EntitlementIterator, GuildIterator
from .mentions import AllowedMentions
from .object import Object
from .sku import SKU
from .stage_instance import StageInstance
from .state import ConnectionState
from .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factory
from .template import Template
from .threads import Thread
from .ui.view import View
from .user import ClientUser, User
from .utils import MISSING, deprecated
from .voice_client import VoiceClient
from .voice_region import VoiceRegion
from .webhook import Webhook
from .widget import Widget
if TYPE_CHECKING:
from typing_extensions import NotRequired
from .abc import GuildChannel, PrivateChannel, Snowflake, SnowflakeTime
from .app_commands import APIApplicationCommand, MessageCommand, SlashCommand, UserCommand
from .asset import AssetBytes
from .channel import DMChannel
from .member import Member
from .message import Message
from .types.application_role_connection import (
ApplicationRoleConnectionMetadata as ApplicationRoleConnectionMetadataPayload,
)
from .types.gateway import SessionStartLimit as SessionStartLimitPayload
from .voice_client import VoiceProtocol
__all__ = (
"Client",
"SessionStartLimit",
"GatewayParams",
)
T = TypeVar("T")
Coro = Coroutine[Any, Any, T]
CoroFunc = Callable[..., Coro[Any]]
CoroT = TypeVar("CoroT", bound=Callable[..., Coroutine[Any, Any, Any]])
_log = logging.getLogger(__name__)
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}
if not tasks:
return
_log.info("Cleaning up after %d tasks.", len(tasks))
for task in tasks:
task.cancel()
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
_log.info("All tasks finished cancelling.")
for task in tasks:
if task.cancelled():
continue
if task.exception() is not None:
loop.call_exception_handler(
{
"message": "Unhandled exception during Client.run shutdown.",
"exception": task.exception(),
"task": task,
}
)
def _cleanup_loop(loop: asyncio.AbstractEventLoop) -> None:
try:
_cancel_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
_log.info("Closing the event loop.")
loop.close()
class SessionStartLimit:
"""A class that contains information about the current session start limit,
at the time when the client connected for the first time.
.. versionadded:: 2.5
Attributes
----------
total: :class:`int`
The total number of allowed session starts.
remaining: :class:`int`
The remaining number of allowed session starts.
reset_after: :class:`int`
The number of milliseconds after which the :attr:`.remaining` limit resets,
relative to when the client connected.
See also :attr:`reset_time`.
max_concurrency: :class:`int`
The number of allowed ``IDENTIFY`` requests per 5 seconds.
reset_time: :class:`datetime.datetime`
The approximate time at which which the :attr:`.remaining` limit resets.
"""
__slots__: Tuple[str, ...] = (
"total",
"remaining",
"reset_after",
"max_concurrency",
"reset_time",
)
def __init__(self, data: SessionStartLimitPayload) -> None:
self.total: int = data["total"]
self.remaining: int = data["remaining"]
self.reset_after: int = data["reset_after"]
self.max_concurrency: int = data["max_concurrency"]
self.reset_time: datetime = utils.utcnow() + timedelta(milliseconds=self.reset_after)
def __repr__(self) -> str:
return (
f"<SessionStartLimit total={self.total!r} remaining={self.remaining!r} "
f"reset_after={self.reset_after!r} max_concurrency={self.max_concurrency!r} reset_time={self.reset_time!s}>"
)
class GatewayParams(NamedTuple):
"""Container type for configuring gateway connections.
.. versionadded:: 2.6
Parameters
----------
encoding: :class:`str`
The payload encoding (``json`` is currently the only supported encoding).
Defaults to ``"json"``.
zlib: :class:`bool`
Whether to enable transport compression.
Defaults to ``True``.
"""
encoding: Literal["json"] = "json"
zlib: bool = True
# used for typing the ws parameter dict in the connect() loop
class _WebSocketParams(TypedDict):
initial: bool
shard_id: Optional[int]
gateway: Optional[str]
sequence: NotRequired[Optional[int]]
resume: NotRequired[bool]
session: NotRequired[Optional[str]]
class Client:
"""Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the :class:`Client`.
Parameters
----------
max_messages: Optional[:class:`int`]
The maximum number of messages to store in the internal message cache.
This defaults to ``1000``. Passing in ``None`` disables the message cache.
.. versionchanged:: 1.3
Allow disabling the message cache and change the default size to ``1000``.
loop: Optional[:class:`asyncio.AbstractEventLoop`]
The :class:`asyncio.AbstractEventLoop` to use for asynchronous operations.
Defaults to ``None``, in which case the default event loop is used via
:func:`asyncio.get_event_loop()`.
asyncio_debug: :class:`bool`
Whether to enable asyncio debugging when the client starts.
Defaults to False.
connector: Optional[:class:`aiohttp.BaseConnector`]
The connector to use for connection pooling.
proxy: Optional[:class:`str`]
Proxy URL.
proxy_auth: Optional[:class:`aiohttp.BasicAuth`]
An object that represents proxy HTTP Basic Authorization.
shard_id: Optional[:class:`int`]
Integer starting at ``0`` and less than :attr:`.shard_count`.
shard_count: Optional[:class:`int`]
The total number of shards.
application_id: :class:`int`
The client's application ID.
intents: Optional[:class:`Intents`]
The intents that you want to enable for the session. This is a way of
disabling and enabling certain gateway events from triggering and being sent.
If not given, defaults to a regularly constructed :class:`Intents` class.
.. versionadded:: 1.5
member_cache_flags: :class:`MemberCacheFlags`
Allows for finer control over how the library caches members.
If not given, defaults to cache as much as possible with the
currently selected intents.
.. versionadded:: 1.5
chunk_guilds_at_startup: :class:`bool`
Indicates if :func:`.on_ready` should be delayed to chunk all guilds
at start-up if necessary. This operation is incredibly slow for large
amounts of guilds. The default is ``True`` if :attr:`Intents.members`
is ``True``.
.. versionadded:: 1.5
status: Optional[Union[class:`str`, :class:`.Status`]]
A status to start your presence with upon logging on to Discord.
activity: Optional[:class:`.BaseActivity`]
An activity to start your presence with upon logging on to Discord.
allowed_mentions: Optional[:class:`AllowedMentions`]
Control how the client handles mentions by default on every message sent.
.. versionadded:: 1.4
heartbeat_timeout: :class:`float`
The maximum numbers of seconds before timing out and restarting the
WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if
processing the initial packets take too long to the point of disconnecting
you. The default timeout is 60 seconds.
guild_ready_timeout: :class:`float`
The maximum number of seconds to wait for the GUILD_CREATE stream to end before
preparing the member cache and firing READY. The default timeout is 2 seconds.
.. versionadded:: 1.4
assume_unsync_clock: :class:`bool`
Whether to assume the system clock is unsynced. This applies to the ratelimit handling
code. If this is set to ``True``, the default, then the library uses the time to reset
a rate limit bucket given by Discord. If this is ``False`` then your system clock is
used to calculate how long to sleep for. If this is set to ``False`` it is recommended to
sync your system clock to Google's NTP server.
.. versionadded:: 1.3
enable_debug_events: :class:`bool`
Whether to enable events that are useful only for debugging gateway related information.
Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. If
this is ``False`` then those events will not be dispatched (due to performance considerations).
To enable these events, this must be set to ``True``. Defaults to ``False``.
.. versionadded:: 2.0
enable_gateway_error_handler: :class:`bool`
Whether to enable the :func:`disnake.on_gateway_error` event.
Defaults to ``True``.
If this is disabled, exceptions that occur while parsing (known) gateway events
won't be handled and the pre-v2.6 behavior of letting the exception propagate up to
the :func:`connect`/:func:`start`/:func:`run` call is used instead.
.. versionadded:: 2.6
localization_provider: :class:`.LocalizationProtocol`
An implementation of :class:`.LocalizationProtocol` to use for localization of
application commands.
If not provided, the default :class:`.LocalizationStore` implementation is used.
.. versionadded:: 2.5
.. versionchanged:: 2.6
Can no longer be provided together with ``strict_localization``, as it does
not apply to the custom localization provider entered in this parameter.
strict_localization: :class:`bool`
Whether to raise an exception when localizations for a specific key couldn't be found.
This is mainly useful for testing/debugging, consider disabling this eventually
as missing localized names will automatically fall back to the default/base name without it.
Only applicable if the ``localization_provider`` parameter is not provided.
Defaults to ``False``.
.. versionadded:: 2.5
.. versionchanged:: 2.6
Can no longer be provided together with ``localization_provider``, as this parameter is
ignored for custom localization providers.
gateway_params: :class:`.GatewayParams`
Allows configuring parameters used for establishing gateway connections,
notably enabling/disabling compression (enabled by default).
Encodings other than JSON are not supported.
.. versionadded:: 2.6
Attributes
----------
ws
The websocket gateway the client is currently connected to. Could be ``None``.
loop: :class:`asyncio.AbstractEventLoop`
The event loop that the client uses for asynchronous operations.
session_start_limit: Optional[:class:`SessionStartLimit`]
Information about the current session start limit.
Only available after initiating the connection.
.. versionadded:: 2.5
i18n: :class:`.LocalizationProtocol`
An implementation of :class:`.LocalizationProtocol` used for localization of
application commands.
.. versionadded:: 2.5
"""
def __init__(
self,
*,
asyncio_debug: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None,
shard_id: Optional[int] = None,
shard_count: Optional[int] = None,
enable_debug_events: bool = False,
enable_gateway_error_handler: bool = True,
localization_provider: Optional[LocalizationProtocol] = None,
strict_localization: bool = False,
gateway_params: Optional[GatewayParams] = None,
connector: Optional[aiohttp.BaseConnector] = None,
proxy: Optional[str] = None,
proxy_auth: Optional[aiohttp.BasicAuth] = None,
assume_unsync_clock: bool = True,
max_messages: Optional[int] = 1000,
application_id: Optional[int] = None,
heartbeat_timeout: float = 60.0,
guild_ready_timeout: float = 2.0,
allowed_mentions: Optional[AllowedMentions] = None,
activity: Optional[BaseActivity] = None,
status: Optional[Union[Status, str]] = None,
intents: Optional[Intents] = None,
chunk_guilds_at_startup: Optional[bool] = None,
member_cache_flags: Optional[MemberCacheFlags] = None,
) -> None:
# self.ws is set in the connect method
self.ws: DiscordWebSocket = None # type: ignore
if loop is None:
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.loop: asyncio.AbstractEventLoop = asyncio.get_event_loop()
else:
self.loop: asyncio.AbstractEventLoop = loop
self.loop.set_debug(asyncio_debug)
self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {}
self.session_start_limit: Optional[SessionStartLimit] = None
self.http: HTTPClient = HTTPClient(
connector,
proxy=proxy,
proxy_auth=proxy_auth,
unsync_clock=assume_unsync_clock,
loop=self.loop,
)
self._handlers: Dict[str, Callable] = {
"ready": self._handle_ready,
"connect_internal": self._handle_first_connect,
}
self._hooks: Dict[str, Callable] = {"before_identify": self._call_before_identify_hook}
self._enable_debug_events: bool = enable_debug_events
self._enable_gateway_error_handler: bool = enable_gateway_error_handler
self._connection: ConnectionState = self._get_state(
max_messages=max_messages,
application_id=application_id,
heartbeat_timeout=heartbeat_timeout,
guild_ready_timeout=guild_ready_timeout,
allowed_mentions=allowed_mentions,
activity=activity,
status=status,
intents=intents,
chunk_guilds_at_startup=chunk_guilds_at_startup,
member_cache_flags=member_cache_flags,
)
self.shard_id: Optional[int] = shard_id
self.shard_count: Optional[int] = shard_count
self._connection.shard_count = shard_count
self._closed: bool = False
self._ready: asyncio.Event = asyncio.Event()
self._first_connect: asyncio.Event = asyncio.Event()
self._connection._get_websocket = self._get_websocket
self._connection._get_client = lambda: self
if VoiceClient.warn_nacl:
VoiceClient.warn_nacl = False
_log.warning("PyNaCl is not installed, voice will NOT be supported")
if strict_localization and localization_provider is not None:
raise ValueError(
"Providing both `localization_provider` and `strict_localization` is not supported."
" If strict localization is desired for a customized localization provider, this"
" should be implemented by that custom provider."
)
self.i18n: LocalizationProtocol = (
LocalizationStore(strict=strict_localization)
if localization_provider is None
else localization_provider
)
self.gateway_params: GatewayParams = gateway_params or GatewayParams()
if self.gateway_params.encoding != "json":
raise ValueError("Gateway encodings other than `json` are currently not supported.")
self.extra_events: Dict[str, List[CoroFunc]] = {}
# internals
def _get_websocket(
self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None
) -> DiscordWebSocket:
return self.ws
def _get_state(
self,
*,
max_messages: Optional[int],
application_id: Optional[int],
heartbeat_timeout: float,
guild_ready_timeout: float,
allowed_mentions: Optional[AllowedMentions],
activity: Optional[BaseActivity],
status: Optional[Union[str, Status]],
intents: Optional[Intents],
chunk_guilds_at_startup: Optional[bool],
member_cache_flags: Optional[MemberCacheFlags],
) -> ConnectionState:
return ConnectionState(
dispatch=self.dispatch,
handlers=self._handlers,
hooks=self._hooks,
http=self.http,
loop=self.loop,
max_messages=max_messages,
application_id=application_id,
heartbeat_timeout=heartbeat_timeout,
guild_ready_timeout=guild_ready_timeout,
allowed_mentions=allowed_mentions,
activity=activity,
status=status,
intents=intents,
chunk_guilds_at_startup=chunk_guilds_at_startup,
member_cache_flags=member_cache_flags,
)
def _handle_ready(self) -> None:
self._ready.set()
def _handle_first_connect(self) -> None:
if self._first_connect.is_set():
return
self._first_connect.set()
@property
def latency(self) -> float:
""":class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
"""
ws = self.ws
return float("nan") if not ws else ws.latency
def is_ws_ratelimited(self) -> bool:
"""Whether the websocket is currently rate limited.
This can be useful to know when deciding whether you should query members
using HTTP or via the gateway.
.. versionadded:: 1.6
:return type: :class:`bool`
"""
if self.ws:
return self.ws.is_ratelimited()
return False
@property
def user(self) -> ClientUser:
"""Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in."""
return self._connection.user
@property
def guilds(self) -> List[Guild]:
"""List[:class:`.Guild`]: The guilds that the connected client is a member of."""
return self._connection.guilds
@property
def emojis(self) -> List[Emoji]:
"""List[:class:`.Emoji`]: The emojis that the connected client has."""
return self._connection.emojis
@property
def stickers(self) -> List[GuildSticker]:
"""List[:class:`.GuildSticker`]: The stickers that the connected client has.
.. versionadded:: 2.0
"""
return self._connection.stickers
@property
def cached_messages(self) -> Sequence[Message]:
"""Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached.
.. versionadded:: 1.1
"""
return utils.SequenceProxy(self._connection._messages or [])
@property
def private_channels(self) -> List[PrivateChannel]:
"""List[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on.
.. note::
This returns only up to 128 most recent private channels due to an internal working
on how Discord deals with private channels.
"""
return self._connection.private_channels
@property
def voice_clients(self) -> List[VoiceProtocol]:
"""List[:class:`.VoiceProtocol`]: Represents a list of voice connections.
These are usually :class:`.VoiceClient` instances.
"""
return self._connection.voice_clients
@property
def application_id(self) -> int:
"""Optional[:class:`int`]: The client's application ID.
If this is not passed via ``__init__`` then this is retrieved
through the gateway when an event contains the data. Usually
after :func:`~disnake.on_connect` is called.
.. versionadded:: 2.0
"""
return self._connection.application_id # type: ignore
@property
def application_flags(self) -> ApplicationFlags:
""":class:`~disnake.ApplicationFlags`: The client's application flags.
.. versionadded:: 2.0
"""
return self._connection.application_flags
@property
def global_application_commands(self) -> List[APIApplicationCommand]:
"""List[Union[:class:`.APIUserCommand`, :class:`.APIMessageCommand`, :class:`.APISlashCommand`]: The client's global application commands."""
return list(self._connection._global_application_commands.values())
@property
def global_slash_commands(self) -> List[APISlashCommand]:
"""List[:class:`.APISlashCommand`]: The client's global slash commands."""
return [
cmd
for cmd in self._connection._global_application_commands.values()
if isinstance(cmd, APISlashCommand)
]
@property
def global_user_commands(self) -> List[APIUserCommand]:
"""List[:class:`.APIUserCommand`]: The client's global user commands."""
return [
cmd
for cmd in self._connection._global_application_commands.values()
if isinstance(cmd, APIUserCommand)
]
@property
def global_message_commands(self) -> List[APIMessageCommand]:
"""List[:class:`.APIMessageCommand`]: The client's global message commands."""
return [
cmd
for cmd in self._connection._global_application_commands.values()
if isinstance(cmd, APIMessageCommand)
]
def get_message(self, id: int) -> Optional[Message]:
"""Gets the message with the given ID from the bot's message cache.
Parameters
----------
id: :class:`int`
The ID of the message to look for.
Returns
-------
Optional[:class:`.Message`]
The corresponding message.
"""
return utils.get(self.cached_messages, id=id)
@overload
async def get_or_fetch_user(
self, user_id: int, *, strict: Literal[False] = ...
) -> Optional[User]:
...
@overload
async def get_or_fetch_user(self, user_id: int, *, strict: Literal[True]) -> User:
...
async def get_or_fetch_user(self, user_id: int, *, strict: bool = False) -> Optional[User]:
"""|coro|
Tries to get the user from the cache. If it fails,
fetches the user from the API.
This only propagates exceptions when the ``strict`` parameter is enabled.
Parameters
----------
user_id: :class:`int`
The ID to search for.
strict: :class:`bool`
Whether to propagate exceptions from :func:`fetch_user`
instead of returning ``None`` in case of failure
(e.g. if the user wasn't found).
Defaults to ``False``.
Returns
-------
Optional[:class:`~disnake.User`]
The user with the given ID, or ``None`` if not found and ``strict`` is set to ``False``.
"""
user = self.get_user(user_id)
if user is not None:
return user
try:
user = await self.fetch_user(user_id)
except Exception:
if strict:
raise
return None
return user
getch_user = get_or_fetch_user
def is_ready(self) -> bool:
"""Whether the client's internal cache is ready for use.
:return type: :class:`bool`
"""
return self._ready.is_set()
async def _run_event(
self,
coro: Callable[..., Coroutine[Any, Any, Any]],
event_name: str,
*args: Any,
**kwargs: Any,
) -> None:
try:
await coro(*args, **kwargs)
except asyncio.CancelledError:
pass
except Exception:
try:
await self.on_error(event_name, *args, **kwargs)
except asyncio.CancelledError:
pass
def _schedule_event(
self,
coro: Callable[..., Coroutine[Any, Any, Any]],
event_name: str,
*args: Any,
**kwargs: Any,
) -> asyncio.Task:
wrapped = self._run_event(coro, event_name, *args, **kwargs)
# Schedules the task
return asyncio.create_task(wrapped, name=f"disnake: {event_name}")
def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None:
_log.debug("Dispatching event %s", event)
method = "on_" + event
listeners = self._listeners.get(event)
if listeners:
removed = []
for i, (future, condition) in enumerate(listeners):
if future.cancelled():
removed.append(i)
continue
try:
result = condition(*args)
except Exception as exc:
future.set_exception(exc)
removed.append(i)
else:
if result:
if len(args) == 0:
future.set_result(None)
elif len(args) == 1:
future.set_result(args[0])
else:
future.set_result(args)
removed.append(i)
if len(removed) == len(listeners):
self._listeners.pop(event)
else:
for idx in reversed(removed):
del listeners[idx]
try:
coro = getattr(self, method)
except AttributeError:
pass
else:
self._schedule_event(coro, method, *args, **kwargs)
for event_ in self.extra_events.get(method, []):
self._schedule_event(event_, method, *args, **kwargs)
def add_listener(self, func: CoroFunc, name: Union[str, Event] = MISSING) -> None:
"""The non decorator alternative to :meth:`.listen`.
.. versionchanged:: 2.10
The definition of this method was moved from :class:`.ext.commands.Bot`
to the :class:`.Client` class.
Parameters
----------
func: :ref:`coroutine <coroutine>`
The function to call.
name: Union[:class:`str`, :class:`.Event`]
The name of the event to listen for. Defaults to ``func.__name__``.
Example
--------
.. code-block:: python
async def on_ready(): pass
async def my_message(message): pass
async def another_message(message): pass
client.add_listener(on_ready)
client.add_listener(my_message, 'on_message')
client.add_listener(another_message, Event.message)
Raises
------
TypeError
The function is not a coroutine or a string or an :class:`.Event` was not passed
as the name.
"""
if name is not MISSING and not isinstance(name, (str, Event)):
raise TypeError(
f"add_listener expected str or Enum but received {name.__class__.__name__!r} instead."
)
name_ = (
func.__name__
if name is MISSING
else (name if isinstance(name, str) else f"on_{name.value}")
)
if not asyncio.iscoroutinefunction(func):
raise TypeError("Listeners must be coroutines")
if name_ in self.extra_events:
self.extra_events[name_].append(func)
else:
self.extra_events[name_] = [func]
def remove_listener(self, func: CoroFunc, name: Union[str, Event] = MISSING) -> None:
"""Removes a listener from the pool of listeners.
.. versionchanged:: 2.10
The definition of this method was moved from :class:`.ext.commands.Bot`
to the :class:`.Client` class.
Parameters
----------
func
The function that was used as a listener to remove.
name: Union[:class:`str`, :class:`.Event`]
The name of the event we want to remove. Defaults to
``func.__name__``.
Raises
------
TypeError
The name passed was not a string or an :class:`.Event`.
"""
if name is not MISSING and not isinstance(name, (str, Event)):
raise TypeError(
f"remove_listener expected str or Enum but received {name.__class__.__name__!r} instead."
)
name = (
func.__name__
if name is MISSING
else (name if isinstance(name, str) else f"on_{name.value}")
)
if name in self.extra_events:
try:
self.extra_events[name].remove(func)
except ValueError:
pass
def listen(self, name: Union[str, Event] = MISSING) -> Callable[[CoroT], CoroT]:
"""A decorator that registers another function as an external
event listener. Basically this allows you to listen to multiple
events from different places e.g. such as :func:`.on_ready`
The functions being listened to must be a :ref:`coroutine <coroutine>`.
.. versionchanged:: 2.10
The definition of this method was moved from :class:`.ext.commands.Bot`
to the :class:`.Client` class.
Example
-------
.. code-block:: python3
@client.listen()
async def on_message(message):
print('one')
# in some other file...
@client.listen('on_message')
async def my_message(message):
print('two')
# in yet another file
@client.listen(Event.message)
async def another_message(message):
print('three')
Would print one, two and three in an unspecified order.
Raises
------
TypeError
The function being listened to is not a coroutine or a string or an :class:`.Event` was not passed
as the name.
"""
if name is not MISSING and not isinstance(name, (str, Event)):
raise TypeError(
f"listen expected str or Enum but received {name.__class__.__name__!r} instead."
)
def decorator(func: CoroT) -> CoroT:
self.add_listener(func, name)
return func
return decorator
def get_listeners(self) -> Mapping[str, List[CoroFunc]]:
"""Mapping[:class:`str`, List[Callable]]: A read-only mapping of event names to listeners.
.. note::
To add or remove a listener you should use :meth:`.add_listener` and
:meth:`.remove_listener`.
.. versionchanged:: 2.10
The definition of this method was moved from :class:`.ext.commands.Bot`
to the :class:`.Client` class.
"""
return types.MappingProxyType(self.extra_events)
async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None:
"""|coro|
The default error handler provided by the client.
By default this prints to :data:`sys.stderr` however it could be
overridden to have a different implementation.
Check :func:`~disnake.on_error` for more details.
"""
print(f"Ignoring exception in {event_method}", file=sys.stderr)
traceback.print_exc()
async def _dispatch_gateway_error(
self, event: str, data: Any, shard_id: Optional[int], exc: Exception, /
) -> None:
# This is an internal hook that calls the public one,
# enabling additional handling while still allowing users to
# overwrite `on_gateway_error`.
# Even though this is always meant to be an async func, we use `maybe_coroutine`
# just in case the client gets subclassed and the method is overwritten with a sync one.
await utils.maybe_coroutine(self.on_gateway_error, event, data, shard_id, exc)
async def on_gateway_error(
self, event: str, data: Any, shard_id: Optional[int], exc: Exception, /
) -> None:
"""|coro|
The default gateway error handler provided by the client.
By default this prints to :data:`sys.stderr` however it could be
overridden to have a different implementation.
Check :func:`~disnake.on_gateway_error` for more details.
.. versionadded:: 2.6
.. note::
Unlike :func:`on_error`, the exception is available as the ``exc``
parameter and cannot be obtained through :func:`sys.exc_info`.
"""
print(
f"Ignoring exception in {event} gateway event handler (shard ID {shard_id})",
file=sys.stderr,
)
traceback.print_exception(type(exc), exc, exc.__traceback__)
# hooks
async def _call_before_identify_hook(
self, shard_id: Optional[int], *, initial: bool = False
) -> None:
# This hook is an internal hook that actually calls the public one.
# It allows the library to have its own hook without stepping on the
# toes of those who need to override their own hook.
await self.before_identify_hook(shard_id, initial=initial)
async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None:
"""|coro|
A hook that is called before IDENTIFYing a session. This is useful