/
bot.py
1706 lines (1430 loc) · 70.8 KB
/
bot.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
import contextlib
import re
import sys
from asyncio import AbstractEventLoop, CancelledError, get_event_loop, iscoroutinefunction
from functools import wraps
from importlib import import_module
from importlib.util import resolve_name
from inspect import getmembers
from logging import Logger
from types import ModuleType
from typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple, Union
from ..api import WebSocketClient as WSClient
from ..api.error import LibraryException
from ..api.http.client import HTTPClient
from ..api.models.flags import Intents, Permissions
from ..api.models.guild import Guild
from ..api.models.misc import Image, Snowflake
from ..api.models.presence import ClientPresence
from ..api.models.team import Application
from ..api.models.user import User
from ..base import get_logger
from ..utils.attrs_utils import convert_list
from ..utils.missing import MISSING
from .decor import component as _component
from .enums import ApplicationCommandType, Locale, OptionType
from .models.command import ApplicationCommand, Choice, Command, Option
from .models.component import Button, Modal, SelectMenu
log: Logger = get_logger("client")
__all__ = (
"Client",
"Extension",
"extension_listener",
"extension_command",
"extension_component",
"extension_modal",
"extension_autocomplete",
"extension_user_command",
"extension_message_command",
)
class Client:
"""
A class representing the client connection to Discord's gateway and API via. WebSocket and HTTP.
:param token: The token of the application for authentication and connection.
:type token: str
:param intents?: Allows specific control of permissions the application has when connected. In order to use multiple intents, the | operator is recommended. Defaults to ``Intents.DEFAULT``.
:type intents?: Optional[Intents]
:param shards?: Dictates and controls the shards that the application connects under.
:type shards?: Optional[List[Tuple[int]]]
:param presence?: Sets an RPC-like presence on the application when connected to the Gateway.
:type presence?: Optional[ClientPresence]
:param default_scope?: Sets the default scope of all commands.
:type default_scope?: Optional[Union[int, Guild, List[int], List[Guild]]]
:param disable_sync?: Controls whether synchronization in the user-facing API should be automatic or not.
:type disable_sync?: Optional[bool]
:ivar AbstractEventLoop _loop: The asynchronous event loop of the client.
:ivar HTTPClient _http: The user-facing HTTP connection to the Web API, as its own separate client.
:ivar WebSocketClient _websocket: An object-orientation of a websocket server connection to the Gateway.
:ivar Intents _intents: The Gateway intents of the application. Defaults to ``Intents.DEFAULT``.
:ivar Optional[List[Tuple[int]]] _shard: The list of bucketed shards for the application's connection.
:ivar Optional[ClientPresence] _presence: The RPC-like presence shown on an application once connected.
:ivar str _token: The token of the application used for authentication when connecting.
:ivar Optional[Dict[str, ModuleType]] _extensions: The "extensions" or cog equivalence registered to the main client.
:ivar Application me?: The application representation of the client.
"""
def __init__(
self,
token: str,
**kwargs,
) -> None:
self._loop: AbstractEventLoop = get_event_loop()
self._http: HTTPClient = token
self._intents: Intents = kwargs.get("intents", Intents.DEFAULT)
self._websocket: WSClient = WSClient(token=token, intents=self._intents)
self._shards: List[Tuple[int]] = kwargs.get("shards", [])
self._commands: List[Command] = []
self._default_scope = kwargs.get("default_scope")
self._presence = kwargs.get("presence")
self._token = token
self._extensions = {}
self._scopes = set([])
self.__command_coroutines = []
self.__global_commands = {}
self.__guild_commands = {}
self.me: Optional[Application] = None
self.__id_autocomplete = {}
if self._default_scope:
if not isinstance(self._default_scope, list):
self._default_scope = [self._default_scope]
if any(isinstance(scope, Guild) for scope in self._default_scope):
self._default_scope = [
(scope.id if isinstance(scope, Guild) else scope)
for scope in self._default_scope
]
self._default_scope = convert_list(int)(self._default_scope)
if kwargs.get("disable_sync"):
self._automate_sync = False
log.warning(
"Automatic synchronization has been disabled. Interactions may need to be manually synchronized."
)
else:
self._automate_sync = True
@property
def guilds(self) -> List[Guild]:
"""Returns a list of guilds the bot is in."""
return list(self._http.cache[Guild].values.values())
@property
def latency(self) -> float:
"""Returns the connection latency in milliseconds."""
return self._websocket.latency * 1000
def start(self) -> None:
"""Starts the client session."""
try:
self._loop.run_until_complete(self._ready())
except (CancelledError, Exception) as e:
self._loop.run_until_complete(self._logout())
raise e from e
except KeyboardInterrupt:
log.error("KeyboardInterrupt detected, shutting down the bot.")
finally:
self._loop.run_until_complete(self._logout())
async def __register_id_autocomplete(self) -> None: # TODO: make this use ID and not name
for key in self.__id_autocomplete.keys():
if isinstance(key, str): # compatibility with the decorator from the Command obj
for _ in self.__id_autocomplete[key]:
# _ contains {"coro" : coro, "name": <name_as_string>}
self.event(
_["coro"],
name=f"autocomplete_{key}_{_['name']}",
)
else:
_command_obj = self._find_command(key)
_command: str = _command_obj.name
for _ in self.__id_autocomplete[key]:
# _ contains {"coro" : coro, "name": <name_as_string>}
self.event(
_["coro"],
name=f"autocomplete_{_command}_{_['name']}",
)
@staticmethod
async def __compare_sync(
data: dict, pool: List[dict]
) -> Tuple[bool, dict]: # sourcery no-metrics
"""
Compares an application command during the synchronization process.
:param data: The application command to compare.
:type data: dict
:param pool: The "pool" or list of commands to compare from.
:type pool: List[dict]
:return: Whether the command has changed or not.
:rtype: bool
"""
# sourcery skip: none-compare
attrs: List[str] = [
name
for name in ApplicationCommand.__slots__
if not name.startswith("_")
and not name.endswith("id")
and name not in {"version", "default_permission"}
]
option_attrs: List[str] = [name for name in Option.__slots__ if not name.startswith("_")]
choice_attrs: List[str] = [name for name in Choice.__slots__ if not name.startswith("_")]
log.info(f"Current attributes to compare: {', '.join(attrs)}.")
clean: bool = True
_command: dict = {}
def __check_options(command, data):
# sourcery skip: low-code-quality, none-compare
# sourcery no-metrics
_command_option_names = [option["name"] for option in command.get("options")]
_data_option_names = [option["name"] for option in data.get("options")]
if any(option not in _command_option_names for option in _data_option_names) or len(
_data_option_names
) != len(_command_option_names):
return False
for option in command.get("options"):
for _option in data.get("options"):
if _option["name"] == option["name"]:
for option_attr in option_attrs:
if (
option.get(option_attr)
and not _option.get(option_attr)
or not option.get(option_attr)
and _option.get(option_attr)
):
return False
elif option_attr == "choices":
if not option.get("choices") or not _option.get("choices"):
continue
_option_choice_names = [
choice["name"] for choice in option.get("choices")
]
_data_choice_names = [
choice["name"] for choice in _option.get("choices")
]
if any(
_ not in _option_choice_names for _ in _data_choice_names
) or len(_data_choice_names) != len(_option_choice_names):
return False
for choice in option.get("choices"):
for _choice in _option.get("choices"):
if choice["name"] == _choice["name"]:
for choice_attr in choice_attrs:
if (
choice.get(choice_attr)
and not _choice.get(choice_attr)
or not choice.get(choice_attr)
and _choice.get(choice_attr)
):
return False
elif choice.get(choice_attr) != _choice.get(
choice_attr
):
return False
else:
continue
for i, __name in enumerate(_option_choice_names):
if _data_choice_names[i] != __name:
return False
elif option_attr == "required":
if (
option.get(option_attr) == None # noqa: E711
and _option.get(option_attr) == False # noqa: E712
):
# API not including if False
continue
elif option_attr == "options":
if not option.get(option_attr) and not _option.get("options"):
continue
_clean = __check_options(option, _option)
if not _clean:
return _clean
elif option.get(option_attr) != _option.get(option_attr):
return False
else:
continue
return next(
(
False
for i, __name in enumerate(_command_option_names)
if _data_option_names[i] != __name
),
True,
)
for command in pool:
if command["name"] == data["name"]:
_command = command
# in case it continues looping
if not command.get("options"):
command["options"] = []
# this will ensure that the option will be an emtpy list, since discord returns `None`
# when no options are present, but they're in the data as `[]`
if command.get("guild_id") and not isinstance(command.get("guild_id"), int):
if isinstance(command.get("guild_id"), list):
command["guild_id"] = [int(_) for _ in command["guild_id"]]
else:
command["guild_id"] = int(command["guild_id"])
# ensure that IDs are present as integers since discord returns strings.
for attr in attrs:
if attr == "options":
if (
not command.get("options")
and data.get("options")
or command.get("options")
and not data.get("options")
):
clean = False
return clean, _command
elif command.get("options") and data.get("options"):
clean = __check_options(command, data)
if not clean:
return clean, _command
else:
continue
elif attr.endswith("localizations"):
if command.get(attr, None) is None and data.get(attr) == {}:
# This is an API/Version difference.
continue
elif (
attr == "dm_permission"
and data.get(attr) == True # noqa: E712
and command.get(attr) == None # noqa: E711
):
# idk, it encountered me and synced unintentionally
continue
# elif data.get(attr, None) and command.get(attr) == data.get(attr):
elif command.get(attr, None) == data.get(attr, None):
# hasattr checks `dict.attr` not `dict[attr]`
continue
clean = False
break
return clean, _command
async def _ready(self) -> None:
"""
Prepares the client with an internal "ready" check to ensure
that all conditions have been met in a chronological order:
.. code-block::
CLIENT START
|___ GATEWAY
| |___ READY
| |___ DISPATCH
|___ SYNCHRONIZE
| |___ CACHE
|___ DETECT DECORATOR
| |___ BUILD MODEL
| |___ SYNCHRONIZE
| |___ CALLBACK
LOOP
"""
ready: bool = False
if isinstance(self._http, str):
self._http = HTTPClient(self._http)
data = await self._http.get_current_bot_information()
self.me = Application(**data, _client=self._http)
try:
if self.me.flags is not None:
# This can be None.
if self._intents.GUILD_PRESENCES in self._intents and not (
self.me.flags.GATEWAY_PRESENCE in self.me.flags
or self.me.flags.GATEWAY_PRESENCE_LIMITED in self.me.flags
):
raise RuntimeError("Client not authorised for the GUILD_PRESENCES intent.")
if self._intents.GUILD_MEMBERS in self._intents and not (
self.me.flags.GATEWAY_GUILD_MEMBERS in self.me.flags
or self.me.flags.GATEWAY_GUILD_MEMBERS_LIMITED in self.me.flags
):
raise RuntimeError("Client not authorised for the GUILD_MEMBERS intent.")
if self._intents.GUILD_MESSAGES in self._intents and not (
self.me.flags.GATEWAY_MESSAGE_CONTENT in self.me.flags
or self.me.flags.GATEWAY_MESSAGE_CONTENT_LIMITED in self.me.flags
):
log.critical("Client not authorised for the MESSAGE_CONTENT intent.")
elif self._intents.value != Intents.DEFAULT.value:
raise RuntimeError("Client not authorised for any privileged intents.")
self.__resolve_commands()
if self._automate_sync:
await self.__sync()
else:
await self.__get_all_commands()
await self.__register_id_autocomplete()
ready = True
except Exception:
log.exception("Could not prepare the client:")
finally:
if ready:
log.debug("Client is now ready.")
await self._login()
async def _stop(self) -> None:
"""Stops the websocket connection gracefully."""
log.debug("Shutting down the client....")
self._websocket.ready.clear() # Clears ready state.
self._websocket._closing_lock.set() # Toggles the "ready-to-shutdown" state for the bot.
# And subsequently, the processes will close itself.
await self._http._req._session.close() # Closes the HTTP session associated with the client.
async def _login(self) -> None:
"""Makes a login with the Discord API."""
try:
await self._websocket.run()
except Exception:
log.exception("Websocket have raised an exception, closing.")
if self._websocket._closing_lock.is_set():
# signal for closing.
try:
if self._websocket._task is not None:
self._websocket.__heartbeat_event.set()
try:
# Wait for the keep-alive handler to finish so we can discard it gracefully
await self._websocket._task
finally:
self._websocket._task = None
finally: # then the overall WS client
if self._websocket._client is not None:
# This needs to be properly closed
try:
await self._websocket._client.close(code=1000)
finally:
self._websocket._client = None
async def wait_until_ready(self) -> None:
"""Helper method that waits until the websocket is ready."""
await self._websocket.wait_until_ready()
async def __get_all_commands(self) -> None:
# this method is just copied from the sync method
# I expect this to be changed in the sync rework
# until then this will deliver a cache if sync is off to make autocomplete work bug-free
# but even with sync off, we should cache all commands here always
_guilds = await self._http.get_self_guilds()
_guild_ids = [int(_["id"]) for _ in _guilds]
self._scopes.update(_guild_ids)
_cmds = await self._http.get_application_commands(
application_id=self.me.id, with_localizations=True
)
for command in _cmds:
if command.get("code"):
# Error exists.
raise LibraryException(command["code"], message=f'{command["message"]} |')
self.__global_commands = {"commands": _cmds, "clean": True}
# TODO: add to cache (later)
# responsible for checking if a command is in the cache but not a coro -> allowing removal
for _id in _guild_ids:
try:
_cmds = await self._http.get_application_commands(
application_id=self.me.id, guild_id=_id, with_localizations=True
)
except LibraryException as e:
if int(e.code) != 50001:
raise LibraryException(code=e.code, message=e.message)
log.warning(
f"Your bot is missing access to guild with corresponding id {_id}! "
"Syncing commands will not be possible until it is invited with "
"`application.commands` scope!"
)
continue
for command in _cmds:
if command.get("code"):
# Error exists.
raise LibraryException(command["code"], message=f'{command["message"]} |')
self.__guild_commands[_id] = {"commands": _cmds, "clean": True}
def __resolve_commands(self) -> None:
"""
Resolves all commands to the command coroutines.
.. warning::
This is an internal method. Do not call it unless you know what you are doing!
"""
for cmd in self._commands:
if cmd.resolved:
continue
cmd.listener = self._websocket._dispatch
if cmd.default_scope and self._default_scope:
cmd.scope = (
cmd.scope.extend(self._default_scope)
if isinstance(cmd.scope, list)
else self._default_scope
)
data: Union[dict, List[dict]] = cmd.full_data
coro = cmd.dispatcher
self.__check_command(
command=ApplicationCommand(**(data[0] if isinstance(data, list) else data)),
coro=coro,
)
if cmd.autocompletions:
self.__id_autocomplete.update(cmd.autocompletions)
coro = coro.__func__ if hasattr(coro, "__func__") else coro
coro._command_data = data
coro._name = cmd.name
coro._converters = cmd.converters
if (data["name"] if isinstance(data, dict) else data[0]["name"]) not in (
(
c._command_data["name"]
if isinstance(c._command_data, dict)
else c._command_data[0]["name"]
)
for c in self.__command_coroutines
):
self.__command_coroutines.append(coro)
if cmd.scope not in (MISSING, None):
if isinstance(cmd.scope, List):
[self._scopes.add(_ if isinstance(_, int) else _.id) for _ in cmd.scope]
else:
self._scopes.add(cmd.scope if isinstance(cmd.scope, int) else cmd.scope.id)
self.event(coro, name=f"command_{cmd.name}")
cmd.resolved = True
async def __sync(self) -> None: # sourcery no-metrics
"""
Synchronizes all commands to the API.
.. warning::
This is an internal method. Do not call it unless you know what you are doing!
"""
# sourcery skip: low-code-quality
log.debug("starting command sync")
_guilds = await self._http.get_self_guilds()
_guild_ids = [int(_["id"]) for _ in _guilds]
self._scopes.update(_guild_ids)
_cmds = await self._http.get_application_commands(
application_id=self.me.id, with_localizations=True
)
for command in _cmds:
if command.get("code"):
# Error exists.
raise LibraryException(command["code"], message=f'{command["message"]} |')
self.__global_commands = {"commands": _cmds, "clean": True}
# TODO: add to cache (later)
__check_global_commands: List[str] = [cmd["name"] for cmd in _cmds]
__check_guild_commands: Dict[int, List[str]] = {}
__blocked_guilds: set = set()
# responsible for checking if a command is in the cache but not a coro -> allowing removal
for _id in _guild_ids.copy():
try:
_cmds = await self._http.get_application_commands(
application_id=self.me.id, guild_id=_id, with_localizations=True
)
except LibraryException as e:
if int(e.code) != 50001:
raise LibraryException(code=e.code, message=e.message) from e
log.warning(
f"Your bot is missing access to guild with corresponding id {_id}! "
"Adding commands will not be possible until it is invited with "
"`application.commands` scope!"
)
__blocked_guilds.add(_id)
_guild_ids.remove(_id)
continue
self.__guild_commands[_id] = {"commands": _cmds, "clean": True}
__check_guild_commands[_id] = [cmd["name"] for cmd in _cmds] if _cmds else []
for coro in self.__command_coroutines:
if hasattr(coro, "_command_data"): # just so IDE knows it exists
if isinstance(coro._command_data, list):
_guild_command: dict
for _guild_command in coro._command_data:
_guild_id = _guild_command.get("guild_id")
if _guild_id in __blocked_guilds:
log.fatal(f"Cannot sync commands on guild with id {_guild_id}!")
raise LibraryException(50001, message="Missing Access |")
if _guild_command["name"] not in __check_guild_commands[_guild_id]:
self.__guild_commands[_guild_id]["clean"] = False
self.__guild_commands[_guild_id]["commands"].append(_guild_command)
else:
clean, _command = await self.__compare_sync(
_guild_command, self.__guild_commands[_guild_id]["commands"]
)
if not clean:
self.__guild_commands[_guild_id]["clean"] = False
# _pos = self.__guild_commands[_guild_id]["commands"].index(_command)
# self.__guild_commands[_guild_id]["commands"][_pos] = _guild_command
for _pos, _dict in enumerate(
self.__guild_commands[_guild_id]["commands"]
):
if _dict["name"] == _command["name"]:
self.__guild_commands[_guild_id]["commands"][
_pos
] = _guild_command
break
if __check_guild_commands[_guild_id]:
del __check_guild_commands[_guild_id][
__check_guild_commands[_guild_id].index(_guild_command["name"])
]
elif coro._command_data["name"] in __check_global_commands: # noqa
clean, _command = await self.__compare_sync(
coro._command_data, self.__global_commands["commands"]
)
if not clean:
self.__global_commands["clean"] = False
# _pos = self.__global_commands["commands"].index(_command)
# self.__global_commands["commands"][_pos] = coro._command_data
for _pos, _dict in enumerate(self.__global_commands["commands"]):
if _dict["name"] == _command["name"]:
self.__global_commands["commands"][_pos] = coro._command_data
break
if __check_global_commands:
del __check_global_commands[
__check_global_commands.index(coro._command_data["name"]) # noqa
]
else:
self.__global_commands["clean"] = False
self.__global_commands["commands"].append(coro._command_data)
if not self.__command_coroutines:
if self.__global_commands["commands"]:
self.__global_commands["clean"] = False
self.__global_commands["commands"] = []
__check_global_commands = []
for _id in _guild_ids:
if self.__guild_commands[_id]["commands"]:
__check_guild_commands[_id] = []
self.__guild_commands[_id]["clean"] = False
self.__guild_commands[_id]["commands"] = []
if __check_global_commands:
# names are present but not found in registered global command coroutines. Deleting.
self.__global_commands["clean"] = False
for name in __check_global_commands:
_pos = self.__global_commands["commands"].index(
[_ for _ in self.__global_commands["commands"] if _["name"] == name][0]
)
del self.__global_commands["commands"][_pos]
for _id in _guild_ids:
if __check_guild_commands[_id]:
self.__guild_commands[_id]["clean"] = False
for name in __check_guild_commands[_id]:
_pos = self.__guild_commands[_id]["commands"].index(
[_ for _ in self.__guild_commands[_id]["commands"] if _["name"] == name][0]
)
del self.__guild_commands[_id]["commands"][_pos]
if not self.__global_commands["clean"] or any(
not self.__guild_commands[_id]["clean"] for _id in _guild_ids
):
if not self.__global_commands["clean"]:
res = await self._http.overwrite_application_command(
application_id=int(self.me.id), data=self.__global_commands["commands"]
)
self.__global_commands["clean"] = True
self.__global_commands["commands"] = res
for _id in _guild_ids:
if not self.__guild_commands[_id]["clean"]:
res = await self._http.overwrite_application_command(
application_id=int(self.me.id),
data=self.__guild_commands[_id]["commands"],
guild_id=_id,
)
self.__guild_commands[_id]["clean"] = True
self.__guild_commands[_id]["commands"] = res
def event(
self, coro: Optional[Callable[..., Coroutine]] = MISSING, *, name: Optional[str] = MISSING
) -> Callable[..., Any]:
"""
A decorator for listening to events dispatched from the
Gateway.
:param coro: The coroutine of the event.
:type coro: Optional[Callable[..., Coroutine]]
:param name(?): The name of the event. If not given, this defaults to the coroutine's name.
:type name: Optional[str]
:return: A callable response.
:rtype: Callable[..., Any]
"""
def decorator(coro: Optional[Callable[..., Coroutine]]):
self._websocket._dispatch.register(
coro, name=name if name is not MISSING else coro.__name__
)
return coro
if coro is not MISSING:
self._websocket._dispatch.register(
coro, name=name if name is not MISSING else coro.__name__
)
return coro
return decorator
async def change_presence(self, presence: ClientPresence) -> None:
"""
A method that changes the current client's presence on runtime.
.. note::
There is a ratelimit to using this method (5 per minute).
As there's no gateway ratelimiter yet, breaking this ratelimit
will force your bot to disconnect.
:param presence: The presence to change the bot to on identify.
:type presence: ClientPresence
"""
await self._websocket._update_presence(presence)
def __check_command(
self,
command: ApplicationCommand,
coro: Callable[..., Coroutine],
regex: str = r"^[a-z0-9_-]{1,32}$",
) -> None: # sourcery no-metrics
"""
Checks if a command is valid.
"""
reg = re.compile(regex)
_options_names: List[str] = []
_sub_groups_present: bool = False
_sub_cmds_present: bool = False
def __check_sub_group(_sub_group: Option):
nonlocal _sub_groups_present
_sub_groups_present = True
if _sub_group.name is MISSING:
raise LibraryException(11, message="Sub command groups must have a name.")
__indent = 4
log.debug(
f"{' ' * __indent}checking sub command group '{_sub_group.name}' of command '{command.name}'"
)
if not re.fullmatch(reg, _sub_group.name):
raise LibraryException(
11,
message=f"The sub command group name does not match the regex for valid names ('{regex}')",
)
elif _sub_group.description is MISSING and not _sub_group.description:
raise LibraryException(11, message="A description is required.")
elif len(_sub_group.description) > 100:
raise LibraryException(11, message="Descriptions must be less than 100 characters.")
if not _sub_group.options:
raise LibraryException(11, message="sub command groups must have subcommands!")
if len(_sub_group.options) > 25:
raise LibraryException(
11, message="A sub command group cannot contain more than 25 sub commands!"
)
for _sub_command in _sub_group.options:
__check_sub_command(_sub_command, _sub_group)
def __check_sub_command(_sub_command: Option, _sub_group: Option = MISSING):
nonlocal _sub_cmds_present
_sub_cmds_present = True
if _sub_command.name is MISSING:
raise LibraryException(11, message="sub commands must have a name!")
if _sub_group is not MISSING:
__indent = 8
log.debug(
f"{' ' * __indent}checking sub command '{_sub_command.name}' of group '{_sub_group.name}'"
)
else:
__indent = 4
log.debug(
f"{' ' * __indent}checking sub command '{_sub_command.name}' of command '{command.name}'"
)
if not re.fullmatch(reg, _sub_command.name):
raise LibraryException(
11,
message=f"The sub command name does not match the regex for valid names ('{reg}')",
)
elif _sub_command.description is MISSING or not _sub_command.description:
raise LibraryException(11, message="A description is required.")
elif len(_sub_command.description) > 100:
raise LibraryException(11, message="Descriptions must be less than 100 characters.")
if _sub_command.options is not MISSING and _sub_command.options:
if len(_sub_command.options) > 25:
raise LibraryException(
11, message="Your sub command must have less than 25 options."
)
_sub_opt_names = []
for _opt in _sub_command.options:
__check_options(_opt, _sub_opt_names, _sub_command)
del _sub_opt_names
def __check_options(_option: Option, _names: list, _sub_command: Option = MISSING):
nonlocal _options_names
if getattr(_option, "autocomplete", False) and getattr(_option, "choices", False):
log.warning("Autocomplete may not be set to true if choices are present.")
if _option.name is MISSING:
raise LibraryException(11, message="Options must have a name.")
if _sub_command is not MISSING:
__indent = 12 if _sub_groups_present else 8
log.debug(
f"{' ' * __indent}checking option '{_option.name}' of sub command '{_sub_command.name}'"
)
else:
__indent = 4
log.debug(
f"{' ' * __indent}checking option '{_option.name}' of command '{command.name}'"
)
_options_names.append(_option.name)
if not re.fullmatch(reg, _option.name):
raise LibraryException(
11,
message=f"The option name ('{_option.name}') does not match the regex for valid names ('{regex}').",
)
if _option.description is MISSING or not _option.description:
raise LibraryException(
11,
message="A description is required.",
)
elif len(_option.description) > 100:
raise LibraryException(
11,
message="Descriptions must be less than 100 characters.",
)
if _option.name in _names:
raise LibraryException(
11, message="You must not have two options with the same name in a command!"
)
_names.append(_option.name)
def __check_coro():
__indent = 4
log.debug(f"{' ' * __indent}Checking coroutine: '{coro.__name__}'")
_ismethod = hasattr(coro, "__func__")
if not len(coro.__code__.co_varnames) ^ (
_ismethod and len(coro.__code__.co_varnames) == 1
):
raise LibraryException(
11, message="Your command needs at least one argument to return context."
)
elif "kwargs" in coro.__code__.co_varnames:
return
elif _sub_cmds_present and len(coro.__code__.co_varnames) < (3 if _ismethod else 2):
raise LibraryException(
11, message="Your command needs one argument for the sub_command."
)
elif _sub_groups_present and len(coro.__code__.co_varnames) < (4 if _ismethod else 3):
raise LibraryException(
11,
message="Your command needs one argument for the sub_command and one for the sub_command_group.",
)
add: int = (
1 + abs(_sub_cmds_present) + abs(_sub_groups_present) + 1 if _ismethod else +0
)
if len(coro.__code__.co_varnames) - add < len(set(_options_names)):
log.debug(
"Coroutine is missing arguments for options:"
f" {[_arg for _arg in _options_names if _arg not in coro.__code__.co_varnames]}"
)
raise LibraryException(
11, message="You need one argument for every option name in your command!"
)
if command.name is MISSING:
raise LibraryException(11, message="Your command must have a name.")
else:
log.debug(f"checking command '{command.name}':")
if (
not re.fullmatch(reg, command.name)
and command.type == ApplicationCommandType.CHAT_INPUT
):
raise LibraryException(
11,
message=f"Your command name ('{command.name}') does not match the regex for valid names ('{regex}').",
)
elif command.type == ApplicationCommandType.CHAT_INPUT and (
command.description is MISSING or not command.description
):
raise LibraryException(11, message="A description is required.")
elif command.type != ApplicationCommandType.CHAT_INPUT and (
command.description is not MISSING and command.description
):
raise LibraryException(11, message="Only chat-input commands can have a description.")
elif command.description is not MISSING and len(command.description) > 100:
raise LibraryException(11, message="Descriptions must be less than 100 characters.")
if command.options and command.options is not MISSING:
if len(command.options) > 25:
raise LibraryException(11, message="Your command must have less than 25 options.")
if command.type != ApplicationCommandType.CHAT_INPUT:
raise LibraryException(
11, message="Only CHAT_INPUT commands can have options/sub-commands!"
)
_opt_names = []
for _option in command.options:
if _option.type == OptionType.SUB_COMMAND_GROUP:
__check_sub_group(_option)
elif _option.type == OptionType.SUB_COMMAND:
__check_sub_command(_option)
else:
__check_options(_option, _opt_names)
del _opt_names
__check_coro()
def command(
self,
*,
type: Optional[Union[int, ApplicationCommandType]] = ApplicationCommandType.CHAT_INPUT,
name: Optional[str] = MISSING,
description: Optional[str] = MISSING,
scope: Optional[Union[int, Guild, List[int], List[Guild]]] = MISSING,
options: Optional[
Union[Dict[str, Any], List[Dict[str, Any]], Option, List[Option]]
] = MISSING,
name_localizations: Optional[Dict[Union[str, Locale], str]] = MISSING,
description_localizations: Optional[Dict[Union[str, Locale], str]] = MISSING,
default_member_permissions: Optional[Union[int, Permissions]] = MISSING,
dm_permission: Optional[bool] = MISSING,
default_scope: bool = True,
) -> Callable[[Callable[..., Coroutine]], Command]:
"""
A decorator for registering an application command to the Discord API,
as well as being able to listen for ``INTERACTION_CREATE`` dispatched
gateway events.
The structure of a chat-input command:
.. code-block:: python
@command(name="command-name", description="this is a command.")
async def command_name(ctx):
...
You are also able to establish it as a message or user command by simply passing
the ``type`` kwarg field into the decorator:
.. code-block:: python
@command(type=interactions.ApplicationCommandType.MESSAGE, name="Message Command")
async def message_command(ctx):
...
The ``scope`` kwarg field may also be used to designate the command in question
applicable to a guild or set of guilds.
To properly utilise the ``default_member_permissions`` kwarg, it requires OR'ing the permission values, similar to instantiating the client with Intents.
For example:
.. code-block:: python
@command(name="kick", description="Kick a user.", default_member_permissions=interactions.Permissions.BAN_MEMBERS | interactions.Permissions.KICK_MEMBERS)
async def kick(ctx, user: interactions.Member):
...
Another example below for instance is an admin-only command:
.. code-block:: python
@command(name="sudo", description="this is an admin-only command.", default_member_permissions=interactions.Permissions.ADMINISTRATOR)
async def sudo(ctx):
...
.. note::