-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapplication_commands.py
2492 lines (2189 loc) · 102 KB
/
application_commands.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
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2021-present mccoderpy
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
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
Dict,
List,
Optional,
Type,
TYPE_CHECKING,
Union,
Set,
)
from typing_extensions import Literal
import re
import copy
import asyncio
import inspect
import warnings
from enum import Enum
from types import FunctionType
from .utils import async_all, find, get, snowflake_time, copy_doc, SupportsStr
from .channel import PartialMessageable
from .enums import (
Enum as DiscordEnum,
ApplicationCommandType,
AppCommandPermissionType,
AppIntegrationType,
ChannelType,
EntryPointHandlerType,
InteractionContextType,
Locale,
OptionType,
try_enum,
)
from .permissions import Permissions
from .abc import GuildChannel
if TYPE_CHECKING:
from datetime import datetime
from .guild import Guild
from .state import ConnectionState
from .ext.commands import Cog, Greedy, Converter
from .interactions import ApplicationCommandInteraction, AutocompleteInteraction, BaseInteraction
from .types import (
app_command
)
from .channel import ThreadChannel
from .abc import GuildChannel, Mentionable
from .member import Member
from .user import User
from .message import Attachment
from .role import Role
ValidOptionType = Union[
Type[str],
Type[bool],
Type[int],
Type[float],
Type[GuildChannel],
Type[ThreadChannel],
Type[Member],
Type[User],
Type[Attachment],
Type[Role],
Type[Mentionable],
OptionType,
Converter,
Type[Converter],
Type[Enum],
Type[DiscordEnum],
]
__all__ = (
'Localizations',
'ApplicationCommand',
'GuildAppCommandPermissions',
'AppCommandPermission',
'SlashCommand',
'GuildOnlySlashCommand',
'SlashCommandOption',
'SlashCommandOptionChoice',
'SubCommandGroup',
'GuildOnlySubCommandGroup',
'SubCommand',
'GuildOnlySubCommand',
'UserCommand',
'MessageCommand',
'generate_options'
)
api_docs = 'https://discord.com/developers/docs/'
CHAT_COMMAND_NAME_REGEX = re.compile(r'^[-_\w0-9\u0901-\u097D\u0E00-\u0E7F]{1,32}$', flags=re.RegexFlag.UNICODE)
# TODO: Add a (optional) feature for auto generated localizations by a translator
class Localizations:
"""
Represents a :class:`dict` with localized values.
These are used for application-commands, options and choices ``name_localizations`` and ``description_localizations``
See :class:`~discord.Locale` for a list of available locals.
Example
-------
.. code-block:: python3
Localizations(
en_US='Hello World!',
de='Hallo Welt!',
fr='Bonjour le monde!'
uk='Привіт світ!'
)
Using the full language name is also possible.
.. code-block:: python3
Localizations(
english_us='Hello World!',
german='Hallo Welt!',
french='Bonjour le monde!'
ukrainian='Привіт світ!'
)
Parameters
----------
kwargs: Any
Keyword only arguments in format ``language='Value'``
As `language` you could use any of :class:`discord.Locale` s members. See table above.
.. note::
Values follow the same restrictions as the target they are used for. e.g. description, name, etc.
"""
__slots__ = tuple([locale_name for locale_name in Locale._enum_member_map_] + ['__languages_dict__']
) # type: ignore
def __init__(self, **localizations) -> None:
self.__languages_dict__ = {}
for locale, localized_text in localizations.items():
try:
setattr(self, locale, localized_text)
except AttributeError:
raise ValueError(f'Unknown locale "{locale}". See {api_docs}reference#locales for a list of locales.')
else:
self.__languages_dict__[Locale[locale].value] = localized_text
def __repr__(self) -> str:
return '<Localizations: %s>' % (", ".join([Locale.try_value(locale).name for locale in self.__languages_dict__]
) if self.__languages_dict__ else 'None')
def __getitem__(self, item) -> Optional[str]:
if isinstance(item, Locale):
locale = Locale[item.name]
else:
locale = try_enum(Locale, str(item))
try:
return self.__languages_dict__[locale.value]
except KeyError:
# TODO: Find a better solution for this.
try:
maybe_them = (locale.name, locale.name.replace('_', '-'), locale.value.replace('_', '-'))
for i in maybe_them:
try:
return self.__languages_dict__[i]
except KeyError:
continue
raise KeyError
except:
raise
except (KeyError, AttributeError):
if (locale.value not in self.__slots__) if isinstance(locale, Locale) else (locale not in self.__slots__):
raise KeyError(f'Unknown locale "{locale}". See {api_docs}/reference#locales for a list of locales.')
raise KeyError(f'There is no locale value set for {locale.name}.')
def __setitem__(self, key: Union[Locale, str], value: str) -> None:
self.__languages_dict__[Locale[key].value] = value
def __bool__(self) -> bool:
return bool(self.__languages_dict__)
def to_dict(self) -> Dict[str, str]:
return self.__languages_dict__ if self.__languages_dict__ else None
@classmethod
def from_dict(cls, data: Optional[Dict[str, str]]) -> Localizations:
if not data:
return cls()
_data = {}
for key, value in data.items():
k: Union[Locale | str] = try_enum(Locale, key)
_data[k.name if isinstance(k, Locale) else k] = value
return cls(**_data)
def update(self, __m: Localizations) -> None:
"""Similar to :meth:`dict.update`"""
self.__languages_dict__.update(__m.__languages_dict__)
def from_target(self, target: Union[Guild, BaseInteraction], *, default: Any = None):
"""
Returns the value for the local of the object (if it's set), or :attr:`default`(:class:`None`)
Parameters
----------
target: Union[:class:`~discord.Guild`, :class:`~discord.BaseInteraction`]
The target witch locale to use.
If it is of type :obj:`~discord.BaseInteraction` (or any subclass) it returns takes the local of the author.
default: Optional[Any]
The value or an object to return by default if there is no value for the locale of :attr:`target` set.
Default to :class:`None` or :class:`~discord.Locale.english_US`/:class:`~discord.Locale.english_GB`
Returns
-------
Union[:class:`str`, None]
The value of the locale or :obj:`None` if there is no value for the locale set.
Raises
------
:exc:`TypeError`
If :attr:`target` is of the wrong type.
"""
if hasattr(target, 'preferred_locale'):
try:
return self[target.preferred_locale.value]
except KeyError as exc:
# just the first letter because it's enough to identify which one it is
if exc.args and exc.args[0].startswith('U'):
pass
return_default = True
elif hasattr(target, 'author_locale'):
try:
return self[target.author_locale.value]
except KeyError as exc:
# just the first letter because it's enough to identify which one it is
if exc.args and exc.args[0].startswith('U'):
pass
return_default = True
else:
raise TypeError(
f'target must be either of type discord.Guild or discord.BaseInteraction, not {target.__class__.__name__}'
)
if return_default:
try:
return self[default.value if default is Locale else default]
except KeyError:
if default is None:
return self.__languages_dict__.get('en-US', self.__languages_dict__.get('en-GB', None))
else:
if (default.value if default is Locale else default) not in self.__slots__:
return default
else:
try:
self[default.value if default is Locale else default]
except KeyError: # not a locale so return it
return default
class ApplicationCommand:
"""The base class for application commands"""
def __init__(self, type: int, *args, **kwargs):
self._type = type
self.name: str = kwargs.get('name', '')
self.is_nsfw: bool = kwargs.get('is_nsfw', False)
self._guild_ids = kwargs.get('guild_ids', None)
self._guild_id = kwargs.get('guild_id', None)
self._state_ = kwargs.get('state', None)
self._disabled = False
self.func = kwargs.pop('func', None)
self.cog = kwargs.get('cog', None)
self.integration_types: Optional[Set[AppIntegrationType]] = {
try_enum(AppIntegrationType, it) for it in i_types
} if (i_types := kwargs.get('integration_types')) else None
self.contexts: Set[InteractionContextType] = {
try_enum(InteractionContextType, ct) for ct in (kwargs.get('contexts', []) or [])
}
dp = kwargs.get('default_permission', None)
if dp is not None:
warnings.warn(
'default_permission is deprecated, use default_member_permissions and contexts instead.',
stacklevel=3,
category=DeprecationWarning
)
dmp = kwargs.get('default_member_permissions', None)
self.default_member_permissions: Optional[Permissions] = (
(Permissions(int(dmp)) if dmp is not None else None) if not isinstance(dmp, Permissions) else dmp
)
if (ad := kwargs.get('allow_dm', None)) is not None:
warnings.warn(
'allow_dm is deprecated, use default_member_permissions and contexts instead.',
stacklevel=3,
category=DeprecationWarning
)
self.allow_dm = ad or (InteractionContextType.bot_dm in self.contexts)
self.name_localizations: Localizations = kwargs.get('name_localizations', Localizations())
self.description_localizations: Localizations = kwargs.get('description_localizations', Localizations())
def __getitem__(self, item) -> Any:
return getattr(self, item)
@property
def _state(self):
return self._state_
@_state.setter
def _state(self, value):
setattr(self, '_state_', value)
@property
def type(self) -> ApplicationCommandType:
return try_enum(ApplicationCommandType, self._type)
@property
def cog(self) -> Optional[Cog]:
"""Optional[:class:`~discord.ext.commands.Cog`]: The cog associated with this command if any."""
return getattr(self, '_cog', None)
@cog.setter
def cog(self, __cog: Cog) -> None:
setattr(self, '_cog', __cog)
@property
def disabled(self) -> bool:
return self._disabled
@disabled.setter
def disabled(self, value: bool) -> None:
self._disabled = value
if hasattr(self, 'sub_commands'):
for cmd in self.sub_commands:
cmd.disabled = value
def _set_cog(self, cog: Cog, recursive: bool = False) -> None:
self.cog = cog
def __call__(self, *args, **kwargs):
return super().__init__(self, *args, **kwargs)
def __repr__(self) -> str:
return '<%s name=%s, id=%s, disabled=%s>' % (self.__class__.__name__, self.name, self.id, self.disabled)
def __eq__(self, other) -> bool:
if isinstance(other, self.__class__):
other = other.to_dict()
if isinstance(other, dict):
def check_options(_options: list, _other: list):
if not len(_options) and not len(_other):
return True
if len(_options) != len(_other):
return False
for index, option in enumerate(_other):
opt = find(lambda o: o['name'] == option['name'], _options)
if not opt:
return False
try:
if index != _options.index(opt) and opt['type'] not in (1, 2):
return False
except IndexError:
return False
for index, option in enumerate(_options):
opt = find(lambda o: option['name'] == o['name'], _other)
try:
if index != _other.index(opt) and opt['type'] not in (1, 2):
return False
except IndexError:
return False
if option['type'] in (1, 2):
if not check_options(option.get('options', []), opt.get('options', [])):
return False
for key in ('type', 'name', 'name_localizations', 'description', 'description_localizations',
'required', 'choices', 'min_value', 'max_value', 'min_length', 'max_length',
'autocomplete'):
current_value = option.get(key, None)
if current_value != opt.get(key, None):
return False
if sorted(opt.get('channel_types', [])) != sorted(option.get('channel_types', [])):
return False
return True
if hasattr(self, 'options') and self.options:
options = [o.to_dict() for o in self.options]
elif hasattr(self, 'sub_commands') and self.sub_commands:
options = [s.to_dict() for s in self.sub_commands]
else:
options = []
dmp = str(self.default_member_permissions.value) if self.default_member_permissions else None
return (
int(self.type) == other.get('type') and self.name == other.get('name', None)
and self.name_localizations.to_dict() == other.get('name_localizations', None)
and getattr(self, 'description', '') == other.get('description', '')
and self.description_localizations.to_dict() == other.get('description_localizations', None)
and dmp == other.get('default_member_permissions', None)
and self.allow_dm == other.get('dm_permission', True)
and (
not any((_other_ctxs := other.get('contexts'), self.contexts))
or not {ctx.value for ctx in self.contexts}.symmetric_difference(_other_ctxs)
)
and (
not any((_other_itg_tps := other.get('integration_types', set()), self.integration_types))
or not {itg_type.value for itg_type in (self.integration_types or set())}
.symmetric_difference(_other_itg_tps)
)
and check_options(options, other.get('options', []))
)
return False
def __ne__(self, other) -> bool:
return not self.__eq__(other)
def _fill_data(self, data) -> ApplicationCommand:
self._id = int(data.get('id', 0))
self._guild_id = int(data.get('guild_id', 0))
return self
async def can_run(self, *args, **kwargs) -> bool:
# if self.cog:
# args = (self.cog, *args)
check_func = kwargs.pop('__func', self)
checks = getattr(check_func, '__commands_checks__', getattr(self.func, '__commands_checks__', []))
if not checks:
return True
return await async_all(check(args[0]) for check in checks)
async def invoke(self, interaction, *args, **kwargs):
if not self.func:
return
args = (interaction, *args)
try:
if await self.can_run(*args):
if self.cog:
await self.func(self.cog, *args, **kwargs)
else:
await self.func(*args, **kwargs)
except Exception as exc:
if hasattr(self, 'on_error'):
if self.cog is not None:
await self.on_error(self.cog, interaction, exc)
else:
await self.on_error(interaction, exc)
else:
self._state.dispatch('application_command_error', self, interaction, exc)
def error(self, coro: Callable[[ApplicationCommandInteraction, Exception], Coroutine]):
"""A decorator to set an error handler for this command similar to :func:`on_application_command_error`
but only for this command
Parameters
----------
coro: Callable[[:class:`~discord.ApplicationCommandInteraction`, :class:`Exception`], Coroutine]
The |coroutine_link|_ to use as an error handler.
Raises
------
TypeError
If the error handler is not a coroutine.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('The error handler must be a coroutine.')
self.on_error = coro
return coro
def to_dict(self) -> dict:
base = {
'type': int(self.type),
'name': str(self.name),
'nsfw': self.is_nsfw,
'contexts': [ctx.value for ctx in self.contexts] if self.contexts else None,
'integration_types': [it.value for it in self.integration_types] if self.integration_types else None,
'name_localizations': self.name_localizations.to_dict(),
'description': getattr(self, 'description', ''),
'description_localizations': self.description_localizations.to_dict(),
'default_member_permissions': str(self.default_member_permissions.value
) if self.default_member_permissions else None
}
if not self.guild_id:
base['dm_permission'] = self.allow_dm
if hasattr(self, 'options'):
base['options'] = [o.to_dict() for o in self.options]
if hasattr(self, 'sub_commands') and self.sub_commands:
base['options'] = [sc.to_dict() for sc in self.sub_commands]
if hasattr(self, 'handler'):
base['handler'] = self.handler.value
return base
@property
def id(self) -> Optional[int]:
"""Optional[:class:`int`]: The id of the command, only set if the bot is running"""
return getattr(self, '_id', None)
@property
def created_at(self) -> Optional[datetime]:
"""
Optional[:class:`~datetime.datetime`]: The creation time of the command in UTC, only set if the bot is running
"""
if self.id:
return snowflake_time(self.id)
@property
def guild_id(self) -> Optional[int]:
"""Optional[:class:`int`]: Th id this command belongs to, if any"""
return self._guild_id
@property
def guild_ids(self) -> Optional[List[int]]:
return getattr(self, '_guild_ids', self.guild_id)
@property
def application_id(self) -> int:
return self._state._get_client().app.id
@classmethod
def _from_type(cls, state: ConnectionState, data: Dict[str, Any]):
command_type = data['type']
if command_type == 1:
return SlashCommand.from_dict(state, data)
elif command_type == 2:
return UserCommand.from_dict(state, data)
elif command_type == 3:
return MessageCommand.from_dict(state, data)
elif command_type == 4:
return ActivityEntryPointCommand.from_dict(state, data)
@staticmethod
def _sorted_by_type(commands):
sorted_dict = {'chat_input': [], 'user': [], 'message': []}
for cmd in commands:
if cmd['type'] == 1:
predicate = 'chat_input'
elif cmd['type'] == 2:
predicate = 'user'
elif cmd['type'] == 3:
predicate = 'message'
elif cmd['type'] == 4:
predicate = 'primary_entry_point'
sorted_dict[predicate] = [cmd]
else: # Should not be the case
continue
sorted_dict[predicate].append(cmd)
return sorted_dict
async def delete(self) -> None:
"""|coro|
Deletes the application command
"""
if self.guild_id != 0:
guild_id = self.guild_id
else:
guild_id = None
await self._state.http.delete_application_command(self.application_id, self.id, guild_id)
if guild_id:
self._state._get_client()._remove_application_command(self, from_cache=True)
class ActivityEntryPointCommand(ApplicationCommand):
"""
The primary entry point command is required for users to be able to launch your Activity from the
:sup-art:`App Launcher menu <21334461140375-Using-Apps-on-Discord>` in Discord.
When you enable Activities in your app's settings, discord will automatically create a
:ddocs:`default Entry Point command </interactions/application-commands#default-entry-point-command>`
.. note::
By default discord will handle the command and launch the activity.
However, if you want to handle the command yourself to deside the response you can register a handler using
the :meth:`discord.Client.activity_primary_entry_point_command` decorator.
If you want to update the name, description, etc. you can do this by calling
:meth:`discord.Client.update_primary_entry_point_command`.
.. seealso::
- :meth:`discord.Client.activity_primary_entry_point_command`
- :meth:`discord.Client.get_primary_entry_point_command`
- :meth:`discord.Client.update_primary_entry_point_command`
Parameters
-----------
name: :class:`str`
The 1-32 characters long name of the command shows up in discord.
description: :class:`str`
The 1-100 characters long description of the command shows up in discord.
integration_types: Optional[List[:class:`~discord.AppIntegrationType`]]
The integration type context this command is available for.
Defaults to the integration types set in the discord developer portal.
contexts: Optional[List[:class:`~discord.InteractionContextType`]]
The contexts this command is available for. Defaults to all contexts.
name_localizations: Optional[:class:`~Localizations`]
Localized names for the command.
description_localizations: Optional[:class:`~Localizations`]
Localized descriptions for the command.
handler: :class:`~discord.EntryPointHandlerType`
"""
def __init__(
self,
name: str,
description: str,
*,
integration_types: Optional[List[InteractionContextType]] = None,
contexts: Optional[List[InteractionContextType]] = None,
name_localizations: Optional[Localizations] = None,
description_localizations: Optional[Localizations] = None,
handler: EntryPointHandlerType = EntryPointHandlerType(2),
**kwargs
):
super().__init__(
type=4,
name=name,
description=description,
integration_types=integration_types,
contexts=contexts,
name_localizations=name_localizations,
description_localizations=description_localizations,
**kwargs
)
self.handler: EntryPointHandlerType = try_enum(EntryPointHandlerType, handler)
@classmethod
def from_dict(cls, state: ConnectionState, data: Dict[str, Any]) -> ActivityEntryPointCommand:
return cls(
name=data['name'],
description=data['description'],
integration_types=data.get('integration_types', None),
contexts=data.get('contexts', None),
name_localizations=Localizations.from_dict(data.get('name_localizations', {})),
description_localizations=Localizations.from_dict(data.get('description_localizations', {})),
handler=try_enum(EntryPointHandlerType, data.get('handler', 2)),
state=state
)._fill_data(data)
async def _parse_arguments(self, interaction: ApplicationCommandInteraction) -> Any:
interaction._command = self
return await self.invoke(interaction)
class SlashCommandOptionChoice:
"""
A class representing a choice for a :class:`SlashCommandOption` or to use in :meth:`AutocompleteInteraction.send_choices`
Parameters
-----------
name: Union[:class:`str`, :class:`int`, :class:`float`]
The 1-100 characters long name that will show in the client.
value: Union[:class:`str`, :class:`int`, :class:`float`, :obj:`None`]
The value that will send as the options value.
Must be of the type the :class:`SlashCommandOption` is of (:class:`str`, :class:`int` or :class:`float`).
.. note::
If this is left empty it takes the :attr:`~SlashCommandOption.name` as value.
name_localizations: Optional[:class:`Localizations`]
Localized names for the choice.
"""
def __init__(
self,
name: Union[str, int, float],
value: Union[str, int, float, None] = None,
name_localizations: Optional[Localizations] = Localizations()
):
if 100 < len(str(name)) < 1:
raise ValueError(f'The name of a choice must bee between 1 and 100 characters long, got {len(name)}.')
self.name: str = str(name)
self.value: Union[str, int, float] = value if value is not None else name
self.name_localizations: Optional[Localizations] = name_localizations
def __repr__(self):
return '<SlashCommandOptionChoice name=%s, value=%s>' % (self.name, self.value)
def to_dict(self) -> Dict[str, Any]:
return {
'name': str(self.name),
'value': self.value,
'name_localizations': self.name_localizations.to_dict(),
}
@classmethod
def from_dict(cls, data) -> SlashCommandOptionChoice:
name_localizations = data.pop('name_localizations', None) or {}
return cls(name=data['name'], value=data['value'], name_localizations=Localizations(**name_localizations))
class SlashCommandOption:
"""
Representing an option for a :class:`SlashCommand`/:class:`SubCommand`.
Parameters
-----------
option_type: Union[:class:`OptionType`, :class:`int`, :class:`type`]
Could be any of :class:`OptionType`'s attributes, an integer between 0 and 10 or a :class:`type` like
:class:`discord.Member`, :class:`discord.TextChannel` or :class:`str`.
.. note::
If the :attr:`option_type` is a :class:`type`, that subclasses :class:`~discord.abc.GuildChannel` the type of the
channel would set as the default :attr:`~SlashCommandOption.channel_types`.
name: :class:`str`
The 1-32 characters long name of the option shows up in discord.
The name must be the same as the one of the parameter for the slash-command
or connected using :attr:`~SlashCommand.connector` of :class:`SlashCommand`/:class:`SubCommand` or the method
that generates one of these.
description: :class:`str`
The 1-100 characters long description of the option shows up in discord.
required: Optional[:class:`bool`]
Weather this option must be provided by the user, default :obj:`True`.
If :obj:`False`, the parameter of the slash-command that takes this option needs a default value.
choices: Optional[List[Union[:class:`SlashCommandOptionChoice`, :class:`str`, :class:`int`, :class:`float`]]]
A list of up to 25 choices the user could select. Only valid if the :attr:`option_type` is one of
:attr:`~OptionType.string`, :attr:`~OptionType.integer` or :attr:`~OptionType.number`.
.. note::
If you want to have values that are not the same as their name, you can use :class:`SlashCommandOptionChoice`
The :attr:`~SlashCommandOptionChoice.value`'s of the choices must be of the :attr:`~SlashCommandOption.option_type` of this option
(e.g. :class:`str`, :class:`int` or :class:`float`).
If choices are set they are the only options a user could pass.
autocomplete: Optional[:class:`bool`]
Whether to enable
`autocomplete <https://discord.com/developers/docs/interactions/application-commands#autocomplete>`_
interactions for this option, default ``False``.
With autocomplete, you can check the user's input and send matching choices to the client.
.. note::
Autocomplete can only be used with options of the type :attr:`~OptionType.string`, :attr:`~OptionType.integer` or :attr:`~OptionType.number`.
**If autocomplete is activated, the option cannot have** :attr:`~SlashCommandOption.choices` **.**
min_value: Optional[Union[:class:`int`, :class:`float`]]
If the :attr:`~SlashCommandOption.option_type` is one of :attr:`~OptionType.integer` or :attr:`~OptionType.number`
this is the minimum value the users input must be of.
max_value: Optional[Union[:class:`int`, :class:`float`]]
If the :attr:`option_type` is one of :attr:`~OptionType.integer` or :attr:`~OptionType.number`
this is the maximum value the users input could be of.
min_length: Optional[:class:`int`]
If the :attr:`option_type` is :attr:`~OptionType.string`, this is the minimum length (minimum of ``0``, maximum of ``6000``)
max_length: Optional[:class:`int`]
If the :attr:`option_type` is :attr:`~OptionType.string`, this is the maximum length (minimum of ``1``, maximum of ``6000``)
channel_types: Optional[List[Union[:class:`abc.GuildChannel`, :class:`ChannelType`, :class:`int`]]]
A list of :class:`ChannelType` or the type itself like ``TextChannel`` or ``StageChannel`` the user could select.
Only valid if :attr:`~SlashCommandOption.option_type` is :attr:`~OptionType.channel`.
default: Optional[Any]
The default value that should be passed to the function if the option is not provided, default ``None``.
Usually used for autocomplete callback.
converter: Optional[Union[:class:`discord.ext.commands.Greedy`, :class:`discord.ext.commands.Converter`]]
A subclass of :class:`~discord.ext.commands.Converter` to use for converting the value.
Only valid for option_type :attr:`~OptionType.string` or :attr:`~OptionType.integer`
ignore_conversion_failures: Optional[:class:`bool`]
Whether conversion failures should be ignored and the value should be passed without conversion instead.
Default ``False``
"""
def __init__(
self,
option_type: ValidOptionType,
name: str,
description: str,
name_localizations: Optional[Localizations] = Localizations(),
description_localizations: Optional[Localizations] = Localizations(),
required: bool = True,
choices: Optional[List[Union[SlashCommandOptionChoice, str, int, float]]] = [],
autocomplete: bool = False,
min_value: Optional[Union[int, float]] = None,
max_value: Optional[Union[int, float]] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
channel_types: Optional[List[Union[type(GuildChannel), ChannelType, int]]] = None,
default: Optional[Any] = None,
converter: Optional[Union[Type[Converter], Greedy]] = None,
ignore_conversion_failures: Optional[bool] = False,
**kwargs
) -> None:
from .ext.commands import Converter, Greedy
if not isinstance(option_type, OptionType):
channel_type = None
option_type_is_class = isinstance(option_type, type)
if option_type_is_class and issubclass(option_type, (Enum, DiscordEnum)):
if description is None:
description = inspect.getdoc(option_type)
choices = [SlashCommandOptionChoice(e.name.translate({95: 0x20}), e.value) for e in option_type]
value_class = choices[0].value.__class__
if all(isinstance(elem.value, value_class) for elem in choices):
option_type, _ = OptionType.from_type(choices[0].value.__class__)
else:
choices = [SlashCommandOptionChoice(e.name.translate({95: 0x20}), str(e.value)) for e in option_type]
option_type = OptionType.string
try:
option_type, channel_type = OptionType.from_type(option_type)
except TypeError:
pass
else:
if issubclass(type(option_type), Converter) or converter is Greedy:
converter = copy.copy(option_type)
option_type = OptionType.string
if not isinstance(option_type, OptionType):
raise TypeError(f'Discord does not has a option_type for {option_type.__class__.__name__!r}.')
if channel_type and not channel_types:
channel_types = channel_type
self.type = option_type
if not CHAT_COMMAND_NAME_REGEX.match(name):
raise ValueError(
r'Command names and options must follow the regex "^[-_\w0-9\u0901-\u097D\u0E00-\u0E7F]{1,32}$"'
f'{api_docs}/interactions/application-commands#application-command-object-application-command-naming.'
f'Got "{name}" with length {len(name)}.'
)
self.name: str = name
self.name_localizations: Localizations = name_localizations
if 100 < len(description) < 1:
raise ValueError(
f'The description must be between 1 and 100 characters long, got {len(description)}.'
)
self.description: str = description
self.description_localizations: Localizations = description_localizations
self.required: bool = required
options = kwargs.get('__options', [])
if self.type == 2 and (not options):
raise ValueError('You need to pass __options if the option_type is subcommand_group.')
self._options = options
self.autocomplete: bool = autocomplete
self.min_value: Optional[Union[int, float]] = min_value
self.max_value: Optional[Union[int, float]] = max_value
self.min_length: int = min_length
self.max_length: int = max_length
for index, choice in enumerate(copy.copy(choices)): # TODO: find a more efficient way to do this
if not isinstance(choice, SlashCommandOptionChoice):
choices[index] = SlashCommandOptionChoice(choice)
self.choices: List[SlashCommandOptionChoice] = choices
self.channel_types: Optional[List[Union[GuildChannel, ChannelType, int]]] = channel_types
self.default: Optional[Any] = default
self.converter: Union[Greedy, Converter] = converter
self.ignore_conversion_failures: bool = ignore_conversion_failures
def __repr__(self) -> str:
return '<SlashCommandOption type=%s, name=%s, description=%s, required=%s, choices=%s>' \
% (self.type,
self.name,
self.description,
self.required,
self.choices)
@property
def autocomplete(self) -> bool:
"""
Whether to enable
`autocomplete <https://discord.com/developers/docs/interactions/application-commands#autocomplete>`_
interactions for this option.
With autocomplete, you can check the user's input and send matching choices to the client.
.. note::
Autocomplete can only be used with options of the type :attr:`~OptionType.string`,
:attr:`~OptionType.integer` or :attr:`~OptionType.number`.
If autocomplete is activated, the option cannot have :attr:`choices`.
"""
return getattr(self, '_autocomplete', False)
@autocomplete.setter
def autocomplete(self, value: bool) -> None:
if value:
if self.type not in (OptionType.string, OptionType.integer, OptionType.number):
raise TypeError('Only Options of type string, integer or number could have autocomplete.')
elif self.choices:
raise TypeError('Options with choices could not have autocomplete.')
self._autocomplete = value
@property
def choices(self) -> Optional[List[SlashCommandOptionChoice]]:
"""
The choices that are set for this option
Returns
-------
Optional[List[:class:`SlashCommandOptionChoice`]]
"""
return getattr(self, '_choices', None)
@choices.setter
def choices(self, value: Optional[List[SlashCommandOptionChoice]]) -> None:
if value:
if self.type not in (OptionType.string, OptionType.integer, OptionType.number):
raise TypeError('Only Options of type string, integer or number could have choices.')
elif self.autocomplete:
raise TypeError('Options with autocomplete could not have choices.')
if len(value) > 25:
raise ValueError('The maximum of choices per Option is 25, got %s.'
'It is recommended to use autocomplete if you have more than 25 options.' % len(value)
)
self._choices = value
@property
def min_value(self) -> Optional[Union[int, float]]:
"""
The minimum value a user could enter that is set
Returns
-------
Optional[Union[:class:`int`, :class:`float`]]
"""
return getattr(self, '_min_value', None)
@min_value.setter
def min_value(self, value) -> None:
if value is not None:
if self.type not in (OptionType.integer, OptionType.number):
raise TypeError('Only Options of type integer or number could have a min_value or/and max_value.')
self._min_value = value
@property
def max_value(self) -> Optional[Union[int, float]]:
"""
The maximum value a user could enter that is set.
Returns
-------
Optional[Union[:class:`int`, :class:`float`]]
"""
return getattr(self, '_max_value', None)
@max_value.setter
def max_value(self, value) -> None:
if value is not None:
if self.type not in (OptionType.integer, OptionType.number):
raise TypeError('Only Options of type integer or number could have a min_value or/and max_value.')
self._max_value = value
@property
def channel_types(self) -> Optional[List[ChannelType]]:
"""
The types of channels that could be selected.
Returns
-------
Optional[List[:class:`ChannelType`]]
"""
return getattr(self, '_channel_types')
@channel_types.setter
def channel_types(self, value) -> None:
if value is not None:
if self.type != OptionType.channel:
raise TypeError('Only options of type channel could have channel_types.')
for index, c in enumerate(value):
if not isinstance(c, ChannelType):
value[index] = ChannelType.from_type(c)
if not any([isinstance(c, ChannelType) for c in value]):
raise ValueError('Only ChannelType Enums, integers or Channel classes allowed.')
self._channel_types = value
def to_dict(self) -> dict:
base = {
'type': int(self.type),
'name': str(self.name),
'name_localizations': self.name_localizations.to_dict(),
'description': str(self.description),
'description_localizations': self.description_localizations.to_dict()
}