-
-
Notifications
You must be signed in to change notification settings - Fork 475
/
Copy pathcore.py
2133 lines (1796 loc) · 77.9 KB
/
core.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
"""
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-present Pycord Development
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
import asyncio
import datetime
import functools
import inspect
import re
import sys
import types
from collections import OrderedDict
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Generator,
Generic,
TypeVar,
Union,
)
from ..channel import PartialMessageable, _threaded_guild_channel_factory
from ..enums import Enum as DiscordEnum
from ..enums import (
IntegrationType,
InteractionContextType,
MessageType,
SlashCommandOptionType,
try_enum,
)
from ..errors import (
ApplicationCommandError,
ApplicationCommandInvokeError,
CheckFailure,
ClientException,
InvalidArgument,
ValidationError,
)
from ..member import Member
from ..message import Attachment, Message
from ..object import Object
from ..role import Role
from ..threads import Thread
from ..user import User
from ..utils import MISSING, async_all, find, maybe_coroutine, utcnow, warn_deprecated
from .context import ApplicationContext, AutocompleteContext
from .options import Option, OptionChoice
if sys.version_info >= (3, 11):
from typing import Annotated, get_args, get_origin
else:
from typing_extensions import Annotated, get_args, get_origin
__all__ = (
"_BaseCommand",
"ApplicationCommand",
"SlashCommand",
"slash_command",
"application_command",
"user_command",
"message_command",
"command",
"SlashCommandGroup",
"ContextMenuCommand",
"UserCommand",
"MessageCommand",
)
if TYPE_CHECKING:
from typing_extensions import Concatenate, ParamSpec
from .. import Permissions
from ..cog import Cog
from ..ext.commands.cooldowns import CooldownMapping, MaxConcurrency
T = TypeVar("T")
CogT = TypeVar("CogT", bound="Cog")
Coro = TypeVar("Coro", bound=Callable[..., Coroutine[Any, Any, Any]])
if TYPE_CHECKING:
P = ParamSpec("P")
else:
P = TypeVar("P")
def wrap_callback(coro):
from ..ext.commands.errors import CommandError
@functools.wraps(coro)
async def wrapped(*args, **kwargs):
try:
ret = await coro(*args, **kwargs)
except ApplicationCommandError:
raise
except CommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise ApplicationCommandInvokeError(exc) from exc
return ret
return wrapped
def hooked_wrapped_callback(command, ctx, coro):
from ..ext.commands.errors import CommandError
@functools.wraps(coro)
async def wrapped(arg):
try:
ret = await coro(arg)
except ApplicationCommandError:
raise
except CommandError:
raise
except asyncio.CancelledError:
return
except Exception as exc:
raise ApplicationCommandInvokeError(exc) from exc
finally:
if (
hasattr(command, "_max_concurrency")
and command._max_concurrency is not None
):
await command._max_concurrency.release(ctx)
await command.call_after_hooks(ctx)
return ret
return wrapped
def unwrap_function(function: Callable[..., Any]) -> Callable[..., Any]:
partial = functools.partial
while True:
if hasattr(function, "__wrapped__"):
function = function.__wrapped__
elif isinstance(function, partial):
function = function.func
else:
return function
def _validate_names(obj):
validate_chat_input_name(obj.name)
if obj.name_localizations:
for locale, string in obj.name_localizations.items():
validate_chat_input_name(string, locale=locale)
def _validate_descriptions(obj):
validate_chat_input_description(obj.description)
if obj.description_localizations:
for locale, string in obj.description_localizations.items():
validate_chat_input_description(string, locale=locale)
class _BaseCommand:
__slots__ = ()
class ApplicationCommand(_BaseCommand, Generic[CogT, P, T]):
__original_kwargs__: dict[str, Any]
cog = None
def __init__(self, func: Callable, **kwargs) -> None:
from ..ext.commands.cooldowns import BucketType, CooldownMapping, MaxConcurrency
cooldown = getattr(func, "__commands_cooldown__", kwargs.get("cooldown"))
if cooldown is None:
buckets = CooldownMapping(cooldown, BucketType.default)
elif isinstance(cooldown, CooldownMapping):
buckets = cooldown
else:
raise TypeError(
"Cooldown must be a an instance of CooldownMapping or None."
)
self._buckets: CooldownMapping = buckets
max_concurrency = getattr(
func, "__commands_max_concurrency__", kwargs.get("max_concurrency")
)
self._max_concurrency: MaxConcurrency | None = max_concurrency
self._callback = None
self.module = None
self.name: str = kwargs.get("name", func.__name__)
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks = checks
self.id: int | None = kwargs.get("id")
self.guild_ids: list[int] | None = kwargs.get("guild_ids", None)
self.parent = kwargs.get("parent")
# Permissions
self.default_member_permissions: Permissions | None = getattr(
func,
"__default_member_permissions__",
kwargs.get("default_member_permissions", None),
)
self.nsfw: bool | None = getattr(func, "__nsfw__", kwargs.get("nsfw", None))
integration_types = getattr(
func, "__integration_types__", kwargs.get("integration_types", None)
)
contexts = getattr(func, "__contexts__", kwargs.get("contexts", None))
guild_only = getattr(func, "__guild_only__", kwargs.get("guild_only", MISSING))
if guild_only is not MISSING:
warn_deprecated(
"guild_only",
"contexts",
"2.6",
reference="https://discord.com/developers/docs/change-log#userinstallable-apps-preview",
)
if contexts and guild_only:
raise InvalidArgument(
"cannot pass both 'contexts' and 'guild_only' to ApplicationCommand"
)
if self.guild_ids and (
(contexts is not None) or guild_only or integration_types
):
raise InvalidArgument(
"the 'contexts' and 'integration_types' parameters are not available for guild commands"
)
if guild_only:
contexts = {InteractionContextType.guild}
self.contexts: set[InteractionContextType] | None = contexts
self.integration_types: set[IntegrationType] | None = integration_types
def __repr__(self) -> str:
return f"<discord.commands.{self.__class__.__name__} name={self.name}>"
def __eq__(self, other) -> bool:
return (
isinstance(other, self.__class__)
and self.qualified_name == other.qualified_name
and self.guild_ids == other.guild_ids
)
async def __call__(self, ctx, *args, **kwargs):
"""|coro|
Calls the command's callback.
This method bypasses all checks that a command has and does not
convert the arguments beforehand, so take care to pass the correct
arguments in.
"""
if self.cog is not None:
return await self.callback(self.cog, ctx, *args, **kwargs)
return await self.callback(ctx, *args, **kwargs)
@property
def callback(
self,
) -> (
Callable[Concatenate[CogT, ApplicationContext, P], Coro[T]]
| Callable[Concatenate[ApplicationContext, P], Coro[T]]
):
return self._callback
@callback.setter
def callback(
self,
function: (
Callable[Concatenate[CogT, ApplicationContext, P], Coro[T]]
| Callable[Concatenate[ApplicationContext, P], Coro[T]]
),
) -> None:
self._callback = function
unwrap = unwrap_function(function)
self.module = unwrap.__module__
@property
def guild_only(self) -> bool:
warn_deprecated(
"guild_only",
"contexts",
"2.6",
reference="https://discord.com/developers/docs/change-log#userinstallable-apps-preview",
)
return InteractionContextType.guild in self.contexts and len(self.contexts) == 1
@guild_only.setter
def guild_only(self, value: bool) -> None:
warn_deprecated(
"guild_only",
"contexts",
"2.6",
reference="https://discord.com/developers/docs/change-log#userinstallable-apps-preview",
)
if value:
self.contexts = {InteractionContextType.guild}
else:
self.contexts = {
InteractionContextType.guild,
InteractionContextType.bot_dm,
InteractionContextType.private_channel,
}
def _prepare_cooldowns(self, ctx: ApplicationContext):
if self._buckets.valid:
current = datetime.datetime.now().timestamp()
bucket = self._buckets.get_bucket(ctx, current) # type: ignore # ctx instead of non-existent message
if bucket is not None:
retry_after = bucket.update_rate_limit(current)
if retry_after:
from ..ext.commands.errors import CommandOnCooldown
raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
async def prepare(self, ctx: ApplicationContext) -> None:
# This should be same across all 3 types
ctx.command = self
if not await self.can_run(ctx):
raise CheckFailure(
f"The check functions for the command {self.name} failed"
)
if self._max_concurrency is not None:
# For this application, context can be duck-typed as a Message
await self._max_concurrency.acquire(ctx) # type: ignore # ctx instead of non-existent message
try:
self._prepare_cooldowns(ctx)
await self.call_before_hooks(ctx)
except:
if self._max_concurrency is not None:
await self._max_concurrency.release(ctx) # type: ignore # ctx instead of non-existent message
raise
def is_on_cooldown(self, ctx: ApplicationContext) -> bool:
"""Checks whether the command is currently on cooldown.
.. note::
This uses the current time instead of the interaction time.
Parameters
----------
ctx: :class:`.ApplicationContext`
The invocation context to use when checking the command's cooldown status.
Returns
-------
:class:`bool`
A boolean indicating if the command is on cooldown.
"""
if not self._buckets.valid:
return False
bucket = self._buckets.get_bucket(ctx) # type: ignore
current = utcnow().timestamp()
return bucket.get_tokens(current) == 0
def reset_cooldown(self, ctx: ApplicationContext) -> None:
"""Resets the cooldown on this command.
Parameters
----------
ctx: :class:`.ApplicationContext`
The invocation context to reset the cooldown under.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx) # type: ignore # ctx instead of non-existent message
bucket.reset()
def get_cooldown_retry_after(self, ctx: ApplicationContext) -> float:
"""Retrieves the amount of seconds before this command can be tried again.
.. note::
This uses the current time instead of the interaction time.
Parameters
----------
ctx: :class:`.ApplicationContext`
The invocation context to retrieve the cooldown from.
Returns
-------
:class:`float`
The amount of time left on this command's cooldown in seconds.
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx) # type: ignore
current = utcnow().timestamp()
return bucket.get_retry_after(current)
return 0.0
async def invoke(self, ctx: ApplicationContext) -> None:
await self.prepare(ctx)
injected = hooked_wrapped_callback(self, ctx, self._invoke)
await injected(ctx)
async def can_run(self, ctx: ApplicationContext) -> bool:
if not await ctx.bot.can_run(ctx):
raise CheckFailure(
f"The global check functions for command {self.name} failed."
)
predicates = self.checks
if self.parent is not None:
# parent checks should be run first
predicates = self.parent.checks + predicates
cog = self.cog
if cog is not None:
local_check = cog._get_overridden_method(cog.cog_check)
if local_check is not None:
ret = await maybe_coroutine(local_check, ctx)
if not ret:
return False
if not predicates:
# since we have no checks, then we just return True.
return True
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
async def dispatch_error(self, ctx: ApplicationContext, error: Exception) -> None:
ctx.command_failed = True
cog = self.cog
try:
coro = self.on_error
except AttributeError:
pass
else:
injected = wrap_callback(coro)
if cog is not None:
await injected(cog, ctx, error)
else:
await injected(ctx, error)
try:
if cog is not None:
local = cog.__class__._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch("application_command_error", ctx, error)
def _get_signature_parameters(self):
return OrderedDict(inspect.signature(self.callback).parameters)
def error(self, coro):
"""A decorator that registers a coroutine as a local error handler.
A local error handler is an :func:`.on_command_error` event limited to
a single command. However, the :func:`.on_command_error` is still
invoked afterwards as the catch-all.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the local error handler.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The error handler must be a coroutine.")
self.on_error = coro
return coro
def has_error_handler(self) -> bool:
"""Checks whether the command has an error handler registered."""
return hasattr(self, "on_error")
def before_invoke(self, coro):
"""A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is
called. This makes it a useful function to set up database
connections or any type of set up required.
This pre-invoke hook takes a sole parameter, an :class:`.ApplicationContext`.
See :meth:`.Bot.before_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the pre-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The pre-invoke hook must be a coroutine.")
self._before_invoke = coro
return coro
def after_invoke(self, coro):
"""A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is
called. This makes it a useful function to clean-up database
connections or any type of clean up required.
This post-invoke hook takes a sole parameter, an :class:`.ApplicationContext`.
See :meth:`.Bot.after_invoke` for more info.
Parameters
----------
coro: :ref:`coroutine <coroutine>`
The coroutine to register as the post-invoke hook.
Raises
------
TypeError
The coroutine passed is not actually a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError("The post-invoke hook must be a coroutine.")
self._after_invoke = coro
return coro
async def call_before_hooks(self, ctx: ApplicationContext) -> None:
# now that we're done preparing we can call the pre-command hooks
# first, call the command local hook:
cog = self.cog
if self._before_invoke is not None:
# should be cog if @commands.before_invoke is used
instance = getattr(self._before_invoke, "__self__", cog)
# __self__ only exists for methods, not functions
# however, if @command.before_invoke is used, it will be a function
if instance:
await self._before_invoke(instance, ctx) # type: ignore
else:
await self._before_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = cog.__class__._get_overridden_method(cog.cog_before_invoke)
if hook is not None:
await hook(ctx)
# call the bot global hook if necessary
hook = ctx.bot._before_invoke
if hook is not None:
await hook(ctx)
async def call_after_hooks(self, ctx: ApplicationContext) -> None:
cog = self.cog
if self._after_invoke is not None:
instance = getattr(self._after_invoke, "__self__", cog)
if instance:
await self._after_invoke(instance, ctx) # type: ignore
else:
await self._after_invoke(ctx) # type: ignore
# call the cog local hook if applicable:
if cog is not None:
hook = cog.__class__._get_overridden_method(cog.cog_after_invoke)
if hook is not None:
await hook(ctx)
hook = ctx.bot._after_invoke
if hook is not None:
await hook(ctx)
@property
def cooldown(self):
return self._buckets._cooldown
@property
def full_parent_name(self) -> str:
"""Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example,
in ``/one two three`` the parent name would be ``one two``.
"""
entries = []
command = self
while command.parent is not None and hasattr(command.parent, "name"):
command = command.parent
entries.append(command.name)
return " ".join(reversed(entries))
@property
def qualified_name(self) -> str:
"""Retrieves the fully qualified command name.
This is the full parent name with the command name as well.
For example, in ``/one two three`` the qualified name would be
``one two three``.
"""
parent = self.full_parent_name
if parent:
return f"{parent} {self.name}"
else:
return self.name
@property
def qualified_id(self) -> int:
"""Retrieves the fully qualified command ID.
This is the root parent ID. For example, in ``/one two three``
the qualified ID would return ``one.id``.
"""
if self.id is None:
return self.parent.qualified_id
return self.id
def to_dict(self) -> dict[str, Any]:
raise NotImplementedError
def __str__(self) -> str:
return self.qualified_name
def _set_cog(self, cog):
self.cog = cog
class SlashCommand(ApplicationCommand):
r"""A class that implements the protocol for a slash command.
These are not created manually, instead they are created via the
decorator or functional interface.
.. versionadded:: 2.0
Attributes
-----------
name: :class:`str`
The name of the command.
callback: :ref:`coroutine <coroutine>`
The coroutine that is executed when the command is called.
description: Optional[:class:`str`]
The description for the command.
guild_ids: Optional[List[:class:`int`]]
The ids of the guilds where this command will be registered.
options: List[:class:`Option`]
The parameters for this command.
parent: Optional[:class:`SlashCommandGroup`]
The parent group that this command belongs to. ``None`` if there
isn't one.
mention: :class:`str`
Returns a string that allows you to mention the slash command.
guild_only: :class:`bool`
Whether the command should only be usable inside a guild.
.. deprecated:: 2.6
Use the :attr:`contexts` parameter instead.
nsfw: :class:`bool`
Whether the command should be restricted to 18+ channels and users.
Apps intending to be listed in the App Directory cannot have NSFW commands.
default_member_permissions: :class:`~discord.Permissions`
The default permissions a member needs to be able to run the command.
cog: Optional[:class:`Cog`]
The cog that this command belongs to. ``None`` if there isn't one.
checks: List[Callable[[:class:`.ApplicationContext`], :class:`bool`]]
A list of predicates that verifies if the command could be executed
with the given :class:`.ApplicationContext` as the sole parameter. If an exception
is necessary to be thrown to signal failure, then one inherited from
:exc:`.ApplicationCommandError` should be used. Note that if the checks fail then
:exc:`.CheckFailure` exception is raised to the :func:`.on_application_command_error`
event.
cooldown: Optional[:class:`~discord.ext.commands.Cooldown`]
The cooldown applied when the command is invoked. ``None`` if the command
doesn't have a cooldown.
name_localizations: Dict[:class:`str`, :class:`str`]
The name localizations for this command. The values of this should be ``"locale": "name"``. See
`here <https://discord.com/developers/docs/reference#locales>`_ for a list of valid locales.
description_localizations: Dict[:class:`str`, :class:`str`]
The description localizations for this command. The values of this should be ``"locale": "description"``.
See `here <https://discord.com/developers/docs/reference#locales>`_ for a list of valid locales.
integration_types: Set[:class:`IntegrationType`]
The type of installation this command should be available to. For instance, if set to
:attr:`IntegrationType.user_install`, the command will only be available to users with
the application installed on their account. Unapplicable for guild commands.
contexts: Set[:class:`InteractionContextType`]
The location where this command can be used. Cannot be set if this is a guild command.
"""
type = 1
def __new__(cls, *args, **kwargs) -> SlashCommand:
self = super().__new__(cls)
self.__original_kwargs__ = kwargs.copy()
return self
def __init__(self, func: Callable, *args, **kwargs) -> None:
super().__init__(func, **kwargs)
if not asyncio.iscoroutinefunction(func):
raise TypeError("Callback must be a coroutine.")
self.callback = func
self.name_localizations: dict[str, str] = kwargs.get(
"name_localizations", MISSING
)
_validate_names(self)
description = kwargs.get("description") or (
inspect.cleandoc(func.__doc__).splitlines()[0]
if func.__doc__ is not None
else "No description provided"
)
self.description: str = description
self.description_localizations: dict[str, str] = kwargs.get(
"description_localizations", MISSING
)
_validate_descriptions(self)
self.attached_to_group: bool = False
self._options_kwargs = kwargs.get("options", [])
self.options: list[Option] = []
self._validate_parameters()
try:
checks = func.__commands_checks__
checks.reverse()
except AttributeError:
checks = kwargs.get("checks", [])
self.checks = checks
self._before_invoke = None
self._after_invoke = None
def _validate_parameters(self):
params = self._get_signature_parameters()
if kwop := self._options_kwargs:
self.options = self._match_option_param_names(params, kwop)
else:
self.options = self._parse_options(params)
def _check_required_params(self, params):
params = iter(params.items())
required_params = (
["self", "context"] if self.attached_to_group or self.cog else ["context"]
)
for p in required_params:
try:
next(params)
except StopIteration:
raise ClientException(
f'Callback for {self.name} command is missing "{p}" parameter.'
)
return params
def _parse_options(self, params, *, check_params: bool = True) -> list[Option]:
if check_params:
params = self._check_required_params(params)
else:
params = iter(params.items())
final_options = []
for p_name, p_obj in params:
option = p_obj.annotation
if option == inspect.Parameter.empty:
option = str
if self._is_typing_annotated(option):
type_hint = get_args(option)[0]
metadata = option.__metadata__
# If multiple Options in metadata, the first will be used.
option_gen = (elem for elem in metadata if isinstance(elem, Option))
option = next(option_gen, Option())
# Handle Optional
if self._is_typing_optional(type_hint):
option.input_type = SlashCommandOptionType.from_datatype(
get_args(type_hint)[0]
)
option.default = None
else:
option.input_type = SlashCommandOptionType.from_datatype(type_hint)
if self._is_typing_union(option):
if self._is_typing_optional(option):
option = Option(option.__args__[0], default=None)
else:
option = Option(option.__args__)
if not isinstance(option, Option):
if isinstance(p_obj.default, Option):
if p_obj.default.input_type is None:
p_obj.default.input_type = SlashCommandOptionType.from_datatype(
option
)
option = p_obj.default
else:
option = Option(option)
if option.default is None and not p_obj.default == inspect.Parameter.empty:
if isinstance(p_obj.default, Option):
pass
elif isinstance(p_obj.default, type) and issubclass(
p_obj.default, (DiscordEnum, Enum)
):
option = Option(p_obj.default)
else:
option.default = p_obj.default
option.required = False
if option.name is None:
option.name = p_name
if option.name != p_name or option._parameter_name is None:
option._parameter_name = p_name
_validate_names(option)
_validate_descriptions(option)
final_options.append(option)
return final_options
def _match_option_param_names(self, params, options):
options = list(options)
params = self._check_required_params(params)
check_annotations: list[Callable[[Option, type], bool]] = [
lambda o, a: o.input_type == SlashCommandOptionType.string
and o.converter is not None, # pass on converters
lambda o, a: isinstance(
o.input_type, SlashCommandOptionType
), # pass on slash cmd option type enums
lambda o, a: isinstance(o._raw_type, tuple) and a == Union[o._raw_type], # type: ignore # union types
lambda o, a: self._is_typing_optional(a)
and not o.required
and o._raw_type in a.__args__, # optional
lambda o, a: isinstance(a, type)
and issubclass(a, o._raw_type), # 'normal' types
]
for o in options:
_validate_names(o)
_validate_descriptions(o)
try:
p_name, p_obj = next(params)
except StopIteration: # not enough params for all the options
raise ClientException("Too many arguments passed to the options kwarg.")
p_obj = p_obj.annotation
if not any(check(o, p_obj) for check in check_annotations):
raise TypeError(
f"Parameter {p_name} does not match input type of {o.name}."
)
o._parameter_name = p_name
left_out_params = OrderedDict()
for k, v in params:
left_out_params[k] = v
options.extend(self._parse_options(left_out_params, check_params=False))
return options
def _is_typing_union(self, annotation):
return getattr(annotation, "__origin__", None) is Union or type(
annotation
) is getattr(
types, "UnionType", Union
) # type: ignore
def _is_typing_optional(self, annotation):
return self._is_typing_union(annotation) and type(None) in annotation.__args__ # type: ignore
def _is_typing_annotated(self, annotation):
return get_origin(annotation) is Annotated
@property
def cog(self):
return getattr(self, "_cog", None)
@cog.setter
def cog(self, value):
old_cog = self.cog
self._cog = value
if (
old_cog is None
and value is not None
or value is None
and old_cog is not None
):
self._validate_parameters()
@property
def is_subcommand(self) -> bool:
return self.parent is not None
@property
def mention(self) -> str:
return f"</{self.qualified_name}:{self.qualified_id}>"
def to_dict(self) -> dict:
as_dict = {
"name": self.name,
"description": self.description,
"options": [o.to_dict() for o in self.options],
}
if self.name_localizations is not MISSING:
as_dict["name_localizations"] = self.name_localizations
if self.description_localizations is not MISSING:
as_dict["description_localizations"] = self.description_localizations
if self.is_subcommand:
as_dict["type"] = SlashCommandOptionType.sub_command.value
if self.nsfw is not None:
as_dict["nsfw"] = self.nsfw
if self.default_member_permissions is not None:
as_dict["default_member_permissions"] = (
self.default_member_permissions.value
)
if not self.guild_ids and not self.is_subcommand:
as_dict["integration_types"] = [it.value for it in self.integration_types]
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
return as_dict
async def _invoke(self, ctx: ApplicationContext) -> None:
# TODO: Parse the args better
kwargs = {}
for arg in ctx.interaction.data.get("options", []):
op = find(lambda x: x.name == arg["name"], self.options)
if op is None:
continue
arg = arg["value"]
# Checks if input_type is user, role or channel
if op.input_type in (
SlashCommandOptionType.user,
SlashCommandOptionType.role,
SlashCommandOptionType.channel,
SlashCommandOptionType.attachment,
SlashCommandOptionType.mentionable,
):
resolved = ctx.interaction.data.get("resolved", {})
if (
op.input_type
in (SlashCommandOptionType.user, SlashCommandOptionType.mentionable)
and (_data := resolved.get("members", {}).get(arg)) is not None
):
# The option type is a user, we resolved a member from the snowflake and assigned it to _data
if (_user_data := resolved.get("users", {}).get(arg)) is not None:
# We resolved the user from the user id
_data["user"] = _user_data
cache_flag = ctx.interaction._state.member_cache_flags.interaction
arg = ctx.guild._get_and_update_member(_data, int(arg), cache_flag)
elif op.input_type is SlashCommandOptionType.mentionable:
if (_data := resolved.get("users", {}).get(arg)) is not None:
arg = User(state=ctx.interaction._state, data=_data)
elif (_data := resolved.get("roles", {}).get(arg)) is not None:
arg = Role(
state=ctx.interaction._state, data=_data, guild=ctx.guild