Skip to content

Application commands

CallbackType

Bases: IntEnum

Types of callback supported by interaction response.

Source code in interactions/models/internal/application_commands.py
195
196
197
198
199
200
201
202
203
204
class CallbackType(IntEnum):
    """Types of callback supported by interaction response."""

    PONG = 1
    CHANNEL_MESSAGE_WITH_SOURCE = 4
    DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5
    DEFERRED_UPDATE_MESSAGE = 6
    UPDATE_MESSAGE = 7
    AUTOCOMPLETE_RESULT = 8
    MODAL = 9

ContextMenu

Bases: InteractionCommand

Represents a discord context menu.

Attributes:

Name Type Description
name LocalisedField

The name of this entry.

type CommandType

The type of entry (user or message).

Source code in interactions/models/internal/application_commands.py
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
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class ContextMenu(InteractionCommand):
    """
    Represents a discord context menu.

    Attributes:
        name: The name of this entry.
        type: The type of entry (user or message).

    """

    name: LocalisedField = attrs.field(
        repr=False, metadata=docs("1-32 character name"), converter=LocalisedField.converter
    )
    type: CommandType = attrs.field(repr=False, metadata=docs("The type of command, defaults to 1 if not specified"))

    @type.validator
    def _type_validator(self, attribute: str, value: int) -> None:
        if not isinstance(value, CommandType):
            if value not in CommandType.__members__.values():
                raise ValueError("Context Menu type not recognised, please consult the docs.")
        elif value == CommandType.CHAT_INPUT:
            raise ValueError(
                "The CHAT_INPUT type is basically slash commands. Please use the @slash_command() " "decorator instead."
            )

    def to_dict(self) -> dict:
        data = super().to_dict()

        data["name"] = str(self.name)
        return data

InteractionCommand

Bases: BaseCommand

Represents a discord abstract interaction command.

Attributes:

Name Type Description
scope

Denotes whether its global or for specific guild.

default_member_permissions Optional[Permissions]

What permissions members need to have by default to use this command.

dm_permission bool

Should this command be available in DMs.

cmd_id Dict[str, Snowflake_Type]

The id of this command given by discord.

callback Callable[..., Coroutine]

The coroutine to callback when this interaction is received.

Source code in interactions/models/internal/application_commands.py
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
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class InteractionCommand(BaseCommand):
    """
    Represents a discord abstract interaction command.

    Attributes:
        scope: Denotes whether its global or for specific guild.
        default_member_permissions: What permissions members need to have by default to use this command.
        dm_permission: Should this command be available in DMs.
        cmd_id: The id of this command given by discord.
        callback: The coroutine to callback when this interaction is received.

    """

    name: LocalisedName | str = attrs.field(
        repr=False,
        metadata=docs("1-32 character name") | no_export_meta,
        converter=LocalisedName.converter,
    )
    scopes: List["Snowflake_Type"] = attrs.field(
        factory=lambda: [GLOBAL_SCOPE],
        converter=to_snowflake_list,
        metadata=docs("The scopes of this interaction. Global or guild ids") | no_export_meta,
    )
    default_member_permissions: Optional["Permissions"] = attrs.field(
        repr=False,
        default=None,
        metadata=docs("What permissions members need to have by default to use this command"),
    )
    dm_permission: bool = attrs.field(
        repr=False, default=True, metadata=docs("Whether this command is enabled in DMs (deprecated)") | no_export_meta
    )
    cmd_id: Dict[str, "Snowflake_Type"] = attrs.field(
        repr=False, factory=dict, metadata=docs("The unique IDs of this commands") | no_export_meta
    )  # scope: cmd_id
    callback: Callable[..., Coroutine] = attrs.field(
        repr=False,
        default=None,
        metadata=docs("The coroutine to call when this interaction is received") | no_export_meta,
    )
    auto_defer: "AutoDefer" = attrs.field(
        default=MISSING,
        metadata=docs("A system to automatically defer this command after a set duration") | no_export_meta,
    )
    nsfw: bool = attrs.field(repr=False, default=False, metadata=docs("This command should only work in NSFW channels"))
    integration_types: list[Union[IntegrationType, int]] = attrs.field(
        factory=lambda: [IntegrationType.GUILD_INSTALL],
        repr=False,
        metadata=docs("Installation context(s) where the command is available, only for globally-scoped commands."),
    )
    contexts: list[Union[ContextType, int]] = attrs.field(
        factory=lambda: [ContextType.GUILD, ContextType.BOT_DM, ContextType.PRIVATE_CHANNEL],
        repr=False,
        metadata=docs("Interaction context(s) where the command can be used, only for globally-scoped commands."),
    )
    _application_id: "Snowflake_Type" = attrs.field(repr=False, default=None, converter=optional(to_snowflake))

    def __attrs_post_init__(self) -> None:
        if self.callback is not None:
            if hasattr(self.callback, "auto_defer"):
                self.auto_defer = self.callback.auto_defer
            if hasattr(self.callback, "integration_types"):
                self.integration_types = self.callback.integration_types
            if hasattr(self.callback, "contexts"):
                self.contexts = self.callback.contexts

        super().__attrs_post_init__()

    @dm_permission.validator
    def _dm_permission_validator(self, attribute: str, value: bool) -> None:
        # since dm_permission is deprecated, ipy transforms it into something that isn't
        if not value:
            try:
                self.contexts.remove(ContextType.PRIVATE_CHANNEL)
            except ValueError:
                pass

            try:
                self.contexts.remove(ContextType.BOT_DM)
            except ValueError:
                pass

    def to_dict(self) -> dict:
        data = super().to_dict()

        data["name_localizations"] = self.name.to_locale_dict()

        if self.default_member_permissions is not None:
            data["default_member_permissions"] = str(int(self.default_member_permissions))
        else:
            data["default_member_permissions"] = None

        return data

    def mention(self, scope: Optional["Snowflake_Type"] = None) -> str:
        """
        Returns a string that would mention the interaction.

        Args:
            scope: If the command is available in multiple scope, specify which scope to get the mention for. Defaults to the first available one if not specified.

        Returns:
            The markdown mention.

        """
        if scope:
            cmd_id = self.get_cmd_id(scope=scope)
        else:
            cmd_id = next(iter(self.cmd_id.values()))

        return f"</{self.resolved_name}:{cmd_id}>"

    @property
    def resolved_name(self) -> str:
        """A representation of this interaction's name."""
        return str(self.name)

    def get_localised_name(self, locale: str) -> str:
        return self.name.get_locale(locale)

    def get_cmd_id(self, scope: "Snowflake_Type") -> "Snowflake_Type":
        return self.cmd_id.get(scope, self.cmd_id.get(GLOBAL_SCOPE, None))

    @property
    def is_subcommand(self) -> bool:
        return False

    async def _permission_enforcer(self, ctx: "BaseContext") -> bool:
        """A check that enforces Discord permissions."""
        # I wish this wasn't needed, but unfortunately Discord permissions cant be trusted to actually prevent usage
        return ctx.guild is not None if self.dm_permission is False else True

    def is_enabled(self, ctx: "BaseContext") -> bool:
        """
        Check if this command is enabled in the given context.

        Args:
            ctx: The context to check.

        Returns:
            Whether this command is enabled in the given context.

        """
        if not self.dm_permission and ctx.guild is None:
            return False
        if self.dm_permission and ctx.guild is None:
            # remaining checks are impossible if this is a DM and DMs are enabled
            return True

        if self.nsfw and not ctx.channel.is_nsfw():
            return False
        if cmd_perms := ctx.guild.command_permissions.get(self.get_cmd_id(ctx.guild.id)):
            if not cmd_perms.is_enabled_in_context(ctx):
                return False
        if self.default_member_permissions is not None:
            channel_perms = ctx.author.channel_permissions(ctx.channel)
            if any(perm not in channel_perms for perm in self.default_member_permissions):
                return False
        return True

resolved_name: str property

A representation of this interaction's name.

is_enabled(ctx)

Check if this command is enabled in the given context.

Parameters:

Name Type Description Default
ctx BaseContext

The context to check.

required

Returns:

Type Description
bool

Whether this command is enabled in the given context.

Source code in interactions/models/internal/application_commands.py
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
def is_enabled(self, ctx: "BaseContext") -> bool:
    """
    Check if this command is enabled in the given context.

    Args:
        ctx: The context to check.

    Returns:
        Whether this command is enabled in the given context.

    """
    if not self.dm_permission and ctx.guild is None:
        return False
    if self.dm_permission and ctx.guild is None:
        # remaining checks are impossible if this is a DM and DMs are enabled
        return True

    if self.nsfw and not ctx.channel.is_nsfw():
        return False
    if cmd_perms := ctx.guild.command_permissions.get(self.get_cmd_id(ctx.guild.id)):
        if not cmd_perms.is_enabled_in_context(ctx):
            return False
    if self.default_member_permissions is not None:
        channel_perms = ctx.author.channel_permissions(ctx.channel)
        if any(perm not in channel_perms for perm in self.default_member_permissions):
            return False
    return True

mention(scope=None)

Returns a string that would mention the interaction.

Parameters:

Name Type Description Default
scope Optional[Snowflake_Type]

If the command is available in multiple scope, specify which scope to get the mention for. Defaults to the first available one if not specified.

None

Returns:

Type Description
str

The markdown mention.

Source code in interactions/models/internal/application_commands.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def mention(self, scope: Optional["Snowflake_Type"] = None) -> str:
    """
    Returns a string that would mention the interaction.

    Args:
        scope: If the command is available in multiple scope, specify which scope to get the mention for. Defaults to the first available one if not specified.

    Returns:
        The markdown mention.

    """
    if scope:
        cmd_id = self.get_cmd_id(scope=scope)
    else:
        cmd_id = next(iter(self.cmd_id.values()))

    return f"</{self.resolved_name}:{cmd_id}>"

LocalisedDesc

Bases: LocalisedField

A localisation object for descriptions.

Source code in interactions/models/internal/application_commands.py
120
121
122
123
124
125
126
127
128
129
130
@attrs.define(
    eq=False,
    order=False,
    hash=False,
    field_transformer=attrs_validator(desc_validator, skip_fields=["default_locale"]),
)
class LocalisedDesc(LocalisedField):
    """A localisation object for descriptions."""

    def __repr__(self) -> str:
        return super().__repr__()

LocalisedName

Bases: LocalisedField

A localisation object for names.

Source code in interactions/models/internal/application_commands.py
107
108
109
110
111
112
113
114
115
116
117
@attrs.define(
    eq=False,
    order=False,
    hash=False,
    field_transformer=attrs_validator(name_validator, skip_fields=["default_locale"]),
)
class LocalisedName(LocalisedField):
    """A localisation object for names."""

    def __repr__(self) -> str:
        return super().__repr__()

OptionType

Bases: IntEnum

Option types supported by slash commands.

Source code in interactions/models/internal/application_commands.py
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
class OptionType(IntEnum):
    """Option types supported by slash commands."""

    SUB_COMMAND = 1
    SUB_COMMAND_GROUP = 2
    STRING = 3
    INTEGER = 4
    BOOLEAN = 5
    USER = 6
    CHANNEL = 7
    ROLE = 8
    MENTIONABLE = 9
    NUMBER = 10
    ATTACHMENT = 11

    @classmethod
    def resolvable_types(cls) -> tuple["OptionType", ...]:
        """A tuple of all resolvable types."""
        return cls.USER, cls.CHANNEL, cls.ROLE, cls.MENTIONABLE, cls.ATTACHMENT

    @classmethod
    def static_types(cls) -> tuple["OptionType", ...]:
        """A tuple of all static types."""
        return cls.STRING, cls.INTEGER, cls.BOOLEAN, cls.NUMBER

    @classmethod
    def command_types(cls) -> tuple["OptionType", ...]:
        """A tuple of all command types."""
        return cls.SUB_COMMAND, cls.SUB_COMMAND_GROUP

    @classmethod
    def from_type(cls, t: type) -> "OptionType | None":
        """
        Convert data types to their corresponding OptionType.

        Args:
            t: The datatype to convert

        Returns:
            OptionType or None

        """
        if issubclass(t, str):
            return cls.STRING
        if issubclass(t, int):
            return cls.INTEGER
        if issubclass(t, bool):
            return cls.BOOLEAN
        if issubclass(t, BaseUser):
            return cls.USER
        if issubclass(t, channel.BaseChannel):
            return cls.CHANNEL
        if issubclass(t, Role):
            return cls.ROLE
        if issubclass(t, float):
            return cls.NUMBER

command_types() classmethod

A tuple of all command types.

Source code in interactions/models/internal/application_commands.py
162
163
164
165
@classmethod
def command_types(cls) -> tuple["OptionType", ...]:
    """A tuple of all command types."""
    return cls.SUB_COMMAND, cls.SUB_COMMAND_GROUP

from_type(t) classmethod

Convert data types to their corresponding OptionType.

Parameters:

Name Type Description Default
t type

The datatype to convert

required

Returns:

Type Description
OptionType | None

OptionType or None

Source code in interactions/models/internal/application_commands.py
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
@classmethod
def from_type(cls, t: type) -> "OptionType | None":
    """
    Convert data types to their corresponding OptionType.

    Args:
        t: The datatype to convert

    Returns:
        OptionType or None

    """
    if issubclass(t, str):
        return cls.STRING
    if issubclass(t, int):
        return cls.INTEGER
    if issubclass(t, bool):
        return cls.BOOLEAN
    if issubclass(t, BaseUser):
        return cls.USER
    if issubclass(t, channel.BaseChannel):
        return cls.CHANNEL
    if issubclass(t, Role):
        return cls.ROLE
    if issubclass(t, float):
        return cls.NUMBER

resolvable_types() classmethod

A tuple of all resolvable types.

Source code in interactions/models/internal/application_commands.py
152
153
154
155
@classmethod
def resolvable_types(cls) -> tuple["OptionType", ...]:
    """A tuple of all resolvable types."""
    return cls.USER, cls.CHANNEL, cls.ROLE, cls.MENTIONABLE, cls.ATTACHMENT

static_types() classmethod

A tuple of all static types.

Source code in interactions/models/internal/application_commands.py
157
158
159
160
@classmethod
def static_types(cls) -> tuple["OptionType", ...]:
    """A tuple of all static types."""
    return cls.STRING, cls.INTEGER, cls.BOOLEAN, cls.NUMBER

SlashCommand

Bases: InteractionCommand

Source code in interactions/models/internal/application_commands.py
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
@attrs.define(eq=False, order=False, hash=False, kw_only=True)
class SlashCommand(InteractionCommand):
    name: LocalisedName | str = attrs.field(repr=False, converter=LocalisedName.converter)
    description: LocalisedDesc | str = attrs.field(
        repr=False, default="No Description Set", converter=LocalisedDesc.converter
    )

    group_name: LocalisedName | str = attrs.field(
        repr=False, default=None, metadata=no_export_meta, converter=LocalisedName.converter
    )
    group_description: LocalisedDesc | str = attrs.field(
        repr=False,
        default="No Description Set",
        metadata=no_export_meta,
        converter=LocalisedDesc.converter,
    )

    sub_cmd_name: LocalisedName | str = attrs.field(
        repr=False, default=None, metadata=no_export_meta, converter=LocalisedName.converter
    )
    sub_cmd_description: LocalisedDesc | str = attrs.field(
        repr=False,
        default="No Description Set",
        metadata=no_export_meta,
        converter=LocalisedDesc.converter,
    )

    options: List[Union[SlashCommandOption, Dict]] = attrs.field(repr=False, factory=list)
    autocomplete_callbacks: dict = attrs.field(repr=False, factory=dict, metadata=no_export_meta)

    parameters: dict[str, SlashCommandParameter] = attrs.field(
        repr=False,
        factory=dict,
        metadata=no_export_meta,
    )
    _uses_arg: bool = attrs.field(repr=False, default=False, metadata=no_export_meta)

    @property
    def resolved_name(self) -> str:
        return (
            f"{self.name}"
            f"{f' {self.group_name}' if bool(self.group_name) else ''}"
            f"{f' {self.sub_cmd_name}' if bool(self.sub_cmd_name) else ''}"
        )

    def get_localised_name(self, locale: str) -> str:
        return (
            f"{self.name.get_locale(locale)}"
            f"{f' {self.group_name.get_locale(locale)}' if bool(self.group_name) else ''}"
            f"{f' {self.sub_cmd_name.get_locale(locale)}' if bool(self.sub_cmd_name) else ''}"
        )

    @property
    def is_subcommand(self) -> bool:
        return bool(self.sub_cmd_name)

    def __attrs_post_init__(self) -> None:
        if self.callback is not None and hasattr(self.callback, "options"):
            if not self.options:
                self.options = []
            self.options += self.callback.options

        super().__attrs_post_init__()

    def _add_option_from_anno_method(self, name: str, option: SlashCommandOption) -> None:
        if not self.options:
            self.options = []

        if option.name.default is None:
            option.name = LocalisedName.converter(name)
        else:
            option.argument_name = name

        self.options.append(option)

    def _parse_parameters(self) -> None:  # noqa: C901
        """
        Parses the parameters that this command has into a form i.py can use.

        This is purposely separated like this to allow "lazy parsing" - parsing
        as the command is added to a bot rather than being parsed immediately.
        This allows variables like "self" to be filtered out, and is useful for
        potential future additions.

        For slash commands, it is also much faster than inspecting the parameters
        each time the command is called.
        It also allows for us to deal with the "annotation method", where users
        put their options in the annotations itself.
        """
        if self.callback is None or self.parameters:
            return

        if self.has_binding:
            callback = functools.partial(self.callback, None, None)
        else:
            callback = functools.partial(self.callback, None)

        for param in get_parameters(callback).values():
            if param.kind == inspect._ParameterKind.VAR_POSITIONAL:
                self._uses_arg = True
                continue

            if param.kind == inspect._ParameterKind.VAR_KEYWORD:
                # in case it was set before
                # we prioritize **kwargs over *args
                self._uses_arg = False
                continue

            our_param = SlashCommandParameter(param.name, param.annotation, param.kind)
            our_param.default = param.default if param.default is not inspect._empty else MISSING

            if param.annotation is not inspect._empty:
                anno = param.annotation
                converter = None

                if _is_optional(anno):
                    anno = _remove_optional(anno)

                if isinstance(anno, SlashCommandOption):
                    # annotation method, get option and add it in
                    self._add_option_from_anno_method(param.name, anno)

                if isinstance(anno, Converter):
                    converter = anno
                elif typing.get_origin(anno) == Annotated:
                    if option := _get_option_from_annotated(anno):
                        # also annotation method
                        self._add_option_from_anno_method(param.name, option)

                    converter = _get_converter_from_annotated(anno)

                if converter:
                    our_param.converter = self._get_converter_function(converter, our_param.name)

            self.parameters[param.name] = our_param

        if self.options:
            for option in self.options:
                maybe_argument_name = (
                    option.argument_name if isinstance(option, SlashCommandOption) else option.get("argument_name")
                )
                if maybe_argument_name:
                    name = option.name if isinstance(option, SlashCommandOption) else option["name"]
                    try:
                        self.parameters[maybe_argument_name]._option_name = str(name)
                    except KeyError:
                        raise ValueError(
                            f'Argument name "{maybe_argument_name}" for "{name}" does not match any parameter in {self.resolved_name}\'s function.'
                        ) from None

    def to_dict(self) -> dict:
        data = super().to_dict()

        if self.is_subcommand:
            data["name"] = str(self.sub_cmd_name)
            data["description"] = str(self.sub_cmd_description)
            data["name_localizations"] = self.sub_cmd_name.to_locale_dict()
            data["description_localizations"] = self.sub_cmd_description.to_locale_dict()
            data.pop("default_member_permissions", None)
            data.pop("dm_permission", None)
            data.pop("nsfw", None)
        else:
            data["name_localizations"] = self.name.to_locale_dict()
            data["description_localizations"] = self.description.to_locale_dict()
        return data

    @options.validator
    def options_validator(self, attribute: str, value: List) -> None:
        if value:
            if not isinstance(value, list):
                raise TypeError("Options attribute must be either None or a list of options")
            if len(value) > SLASH_CMD_MAX_OPTIONS:
                raise ValueError(f"Slash commands can only hold {SLASH_CMD_MAX_OPTIONS} options")
            if value != sorted(
                value,
                key=lambda x: x.required if isinstance(x, SlashCommandOption) else x["required"],
                reverse=True,
            ):
                raise ValueError("Required options must go before optional options")

    def autocomplete(self, option_name: str) -> Callable[..., Coroutine]:
        """A decorator to declare a coroutine as an option autocomplete."""

        def wrapper(call: Callable[..., Coroutine]) -> Callable[..., Coroutine]:
            if not asyncio.iscoroutinefunction(call):
                raise TypeError("autocomplete must be coroutine")
            self.autocomplete_callbacks[option_name] = call

            if self.options:
                # automatically set the option's autocomplete attribute to True
                for opt in self.options:
                    if isinstance(opt, dict) and str(opt["name"]) == option_name:
                        opt["autocomplete"] = True
                    elif isinstance(opt, SlashCommandOption) and str(opt.name) == option_name:
                        opt.autocomplete = True

            return call

        option_name = option_name.lower()
        return wrapper

    def group(
        self, name: str | None = None, description: str = "No Description Set", inherit_checks: bool = True
    ) -> "SlashCommand":
        return SlashCommand(
            name=self.name,
            description=self.description,
            group_name=name,
            group_description=description,
            scopes=self.scopes,
            default_member_permissions=self.default_member_permissions,
            integration_types=self.integration_types,
            contexts=self.contexts,
            dm_permission=self.dm_permission,
            checks=self.checks.copy() if inherit_checks else [],
        )

    def subcommand(
        self,
        sub_cmd_name: Absent[LocalisedName | str] = MISSING,
        group_name: LocalisedName | str = None,
        sub_cmd_description: Absent[LocalisedDesc | str] = MISSING,
        group_description: Absent[LocalisedDesc | str] = MISSING,
        options: List[Union[SlashCommandOption, Dict]] | None = None,
        nsfw: bool = False,
        inherit_checks: bool = True,
    ) -> Callable[..., "SlashCommand"]:
        def wrapper(call: Callable[..., Coroutine]) -> "SlashCommand":
            nonlocal sub_cmd_name, sub_cmd_description

            if not asyncio.iscoroutinefunction(call):
                raise TypeError("Subcommand must be coroutine")

            if sub_cmd_description is MISSING:
                sub_cmd_description = call.__doc__ or "No Description Set"
            if sub_cmd_name is MISSING:
                sub_cmd_name = call.__name__

            return SlashCommand(
                name=self.name,
                description=self.description,
                group_name=group_name or self.group_name,
                group_description=group_description or self.group_description,
                sub_cmd_name=sub_cmd_name,
                sub_cmd_description=sub_cmd_description,
                default_member_permissions=self.default_member_permissions,
                integration_types=self.integration_types,
                contexts=self.contexts,
                dm_permission=self.dm_permission,
                options=options,
                callback=call,
                scopes=self.scopes,
                nsfw=nsfw,
                checks=self.checks.copy() if inherit_checks else [],
            )

        return wrapper

    async def call_callback(self, callback: typing.Callable, ctx: "InteractionContext") -> None:
        if not self.parameters:
            if self._uses_arg:
                return await self.call_with_binding(callback, ctx, *ctx.args)
            return await self.call_with_binding(callback, ctx)

        kwargs_copy = ctx.kwargs.copy()

        new_args = []
        new_kwargs = {}

        for param in self.parameters.values():
            value = kwargs_copy.pop(param.option_name, MISSING)
            if value is MISSING:
                continue

            if converter := param.converter:
                value = await maybe_coroutine(converter, ctx, value)

            if param.kind == inspect.Parameter.POSITIONAL_ONLY:
                new_args.append(value)
            else:
                new_kwargs[param.name] = value

        # i do want to address one thing: what happens if you have both *args and **kwargs
        # in your argument?
        # i would say passing in values for both makes sense... but they're very likely
        # going to overlap and cause issues and confusion
        # for the sake of simplicty, i.py assumes kwargs takes priority over args
        if kwargs_copy:
            if self._uses_arg:
                new_args.extend(kwargs_copy.values())
            else:
                new_kwargs |= kwargs_copy

        return await self.call_with_binding(callback, ctx, *new_args, **new_kwargs)

autocomplete(option_name)

A decorator to declare a coroutine as an option autocomplete.

Source code in interactions/models/internal/application_commands.py
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def autocomplete(self, option_name: str) -> Callable[..., Coroutine]:
    """A decorator to declare a coroutine as an option autocomplete."""

    def wrapper(call: Callable[..., Coroutine]) -> Callable[..., Coroutine]:
        if not asyncio.iscoroutinefunction(call):
            raise TypeError("autocomplete must be coroutine")
        self.autocomplete_callbacks[option_name] = call

        if self.options:
            # automatically set the option's autocomplete attribute to True
            for opt in self.options:
                if isinstance(opt, dict) and str(opt["name"]) == option_name:
                    opt["autocomplete"] = True
                elif isinstance(opt, SlashCommandOption) and str(opt.name) == option_name:
                    opt.autocomplete = True

        return call

    option_name = option_name.lower()
    return wrapper

SlashCommandChoice

Bases: DictSerializationMixin

Represents a discord slash command choice.

Attributes:

Name Type Description
name LocalisedField | str

The name the user will see

value Union[str, int, float]

The data sent to your code when this choice is used

Source code in interactions/models/internal/application_commands.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
@attrs.define(eq=False, order=False, hash=False, kw_only=False)
class SlashCommandChoice(DictSerializationMixin):
    """
    Represents a discord slash command choice.

    Attributes:
        name: The name the user will see
        value: The data sent to your code when this choice is used

    """

    name: LocalisedField | str = attrs.field(repr=False, converter=LocalisedField.converter)
    value: Union[str, int, float] = attrs.field(
        repr=False,
    )

    def as_dict(self) -> dict:
        return {
            "name": str(self.name),
            "value": self.value,
            "name_localizations": self.name.to_locale_dict(),
        }

SlashCommandOption

Bases: DictSerializationMixin

Represents a discord slash command option.

Attributes:

Name Type Description
name LocalisedName | str

The name of this option

type Union[OptionType, int]

The type of option

description LocalisedDesc | str | str

The description of this option

required bool

"This option must be filled to use the command"

choices List[Union[SlashCommandChoice, Dict]]

A list of choices the user has to pick between

channel_types Optional[list[Union[ChannelType, int]]]

The channel types permitted. The option needs to be a channel

min_value Optional[float]

The minimum value permitted. The option needs to be an integer or float

max_value Optional[float]

The maximum value permitted. The option needs to be an integer or float

min_length Optional[int]

The minimum length of text a user can input. The option needs to be a string

max_length Optional[int]

The maximum length of text a user can input. The option needs to be a string

argument_name Optional[str]

The name of the argument to be used in the function. If not given, assumed to be the same as the name of the option

Source code in interactions/models/internal/application_commands.py
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
@attrs.define(eq=False, order=False, hash=False, kw_only=False)
class SlashCommandOption(DictSerializationMixin):
    """
    Represents a discord slash command option.

    Attributes:
        name: The name of this option
        type: The type of option
        description: The description of this option
        required: "This option must be filled to use the command"
        choices: A list of choices the user has to pick between
        channel_types: The channel types permitted. The option needs to be a channel
        min_value: The minimum value permitted. The option needs to be an integer or float
        max_value: The maximum value permitted. The option needs to be an integer or float
        min_length: The minimum length of text a user can input. The option needs to be a string
        max_length: The maximum length of text a user can input. The option needs to be a string
        argument_name: The name of the argument to be used in the function. If not given, assumed to be the same as the name of the option

    """

    name: LocalisedName | str = attrs.field(repr=False, converter=LocalisedName.converter)
    type: Union[OptionType, int] = attrs.field(
        repr=False,
    )
    description: LocalisedDesc | str | str = attrs.field(
        repr=False, default="No Description Set", converter=LocalisedDesc.converter
    )
    required: bool = attrs.field(repr=False, default=True)
    autocomplete: bool = attrs.field(repr=False, default=False)
    choices: List[Union[SlashCommandChoice, Dict]] = attrs.field(repr=False, factory=list)
    channel_types: Optional[list[Union[ChannelType, int]]] = attrs.field(repr=False, default=None)
    min_value: Optional[float] = attrs.field(repr=False, default=None)
    max_value: Optional[float] = attrs.field(repr=False, default=None)
    min_length: Optional[int] = attrs.field(repr=False, default=None)
    max_length: Optional[int] = attrs.field(repr=False, default=None)
    argument_name: Optional[str] = attrs.field(repr=False, default=None)

    @type.validator
    def _type_validator(self, attribute: str, value: int) -> None:
        if value in (OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP):
            raise ValueError(
                "Options cannot be SUB_COMMAND or SUB_COMMAND_GROUP. If you want to use subcommands, "
                "see the @sub_command() decorator."
            )

    @channel_types.validator
    def _channel_types_validator(self, attribute: str, value: Optional[list[OptionType]]) -> None:
        if value is not None:
            if self.type != OptionType.CHANNEL:
                raise ValueError("The option needs to be CHANNEL to use this")

            allowed_int = [channel_type.value for channel_type in ChannelType]
            for item in value:
                if (item not in allowed_int) and (item not in ChannelType):
                    raise ValueError(f"{value} is not allowed here")

    @min_value.validator
    def _min_value_validator(self, attribute: str, value: Optional[float]) -> None:
        if value is not None:
            if self.type not in [OptionType.INTEGER, OptionType.NUMBER]:
                raise ValueError("`min_value` can only be supplied with int or float options")

            if self.type == OptionType.INTEGER and isinstance(value, float):
                raise ValueError("`min_value` needs to be an int in an int option")

            if self.max_value is not None and self.min_value is not None and self.max_value < self.min_value:
                raise ValueError("`min_value` needs to be <= than `max_value`")

    @max_value.validator
    def _max_value_validator(self, attribute: str, value: Optional[float]) -> None:
        if value is not None:
            if self.type not in (OptionType.INTEGER, OptionType.NUMBER):
                raise ValueError("`max_value` can only be supplied with int or float options")

            if self.type == OptionType.INTEGER and isinstance(value, float):
                raise ValueError("`max_value` needs to be an int in an int option")

            if self.max_value and self.min_value and self.max_value < self.min_value:
                raise ValueError("`min_value` needs to be <= than `max_value`")

    @min_length.validator
    def _min_length_validator(self, attribute: str, value: Optional[int]) -> None:
        if value is not None:
            if self.type != OptionType.STRING:
                raise ValueError("`min_length` can only be supplied with string options")

            if self.max_length is not None and self.min_length is not None and self.max_length < self.min_length:
                raise ValueError("`min_length` needs to be <= than `max_length`")

            if self.min_length < 0:
                raise ValueError("`min_length` needs to be >= 0")

    @max_length.validator
    def _max_length_validator(self, attribute: str, value: Optional[int]) -> None:
        if value is not None:
            if self.type != OptionType.STRING:
                raise ValueError("`max_length` can only be supplied with string options")

            if self.min_length is not None and self.max_length is not None and self.max_length < self.min_length:
                raise ValueError("`min_length` needs to be <= than `max_length`")

            if self.max_length < 1:
                raise ValueError("`max_length` needs to be >= 1")

    def as_dict(self) -> dict:
        data = attrs.asdict(self)
        data.pop("argument_name", None)
        data["name"] = str(self.name)
        data["description"] = str(self.description)
        data["choices"] = [
            choice.as_dict() if isinstance(choice, SlashCommandChoice) else choice for choice in self.choices
        ]
        data["name_localizations"] = self.name.to_locale_dict()
        data["description_localizations"] = self.description.to_locale_dict()

        return data

application_commands_to_dict(commands, client)

Convert the command list into a format that would be accepted by discord.

Client.interactions should be the variable passed to this

Source code in interactions/models/internal/application_commands.py
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
def application_commands_to_dict(  # noqa: C901
    commands: Dict["Snowflake_Type", Dict[str, InteractionCommand]], client: "Client"
) -> dict:
    """
    Convert the command list into a format that would be accepted by discord.

    `Client.interactions` should be the variable passed to this

    """
    cmd_bases: defaultdict[str, list[InteractionCommand]] = defaultdict(list)  # {cmd_base: [commands]}
    """A store of commands organised by their base command"""
    output: defaultdict["Snowflake_Type", list[dict]] = defaultdict(list)
    """The output dictionary"""

    def squash_subcommand(subcommands: List) -> Dict:
        output_data = {}
        groups = {}
        sub_cmds = []
        for subcommand in subcommands:
            if not output_data:
                output_data = {
                    "name": str(subcommand.name),
                    "description": str(subcommand.description),
                    "options": [],
                    "default_member_permissions": (
                        str(int(subcommand.default_member_permissions))
                        if subcommand.default_member_permissions
                        else None
                    ),
                    "integration_types": subcommand.integration_types,
                    "contexts": subcommand.contexts,
                    "name_localizations": subcommand.name.to_locale_dict(),
                    "description_localizations": subcommand.description.to_locale_dict(),
                    "nsfw": subcommand.nsfw,
                }
            if bool(subcommand.group_name):
                if str(subcommand.group_name) not in groups:
                    groups[str(subcommand.group_name)] = {
                        "name": str(subcommand.group_name),
                        "description": str(subcommand.group_description),
                        "type": int(OptionType.SUB_COMMAND_GROUP),
                        "options": [],
                        "name_localizations": subcommand.group_name.to_locale_dict(),
                        "description_localizations": subcommand.group_description.to_locale_dict(),
                    }
                groups[str(subcommand.group_name)]["options"].append(
                    subcommand.to_dict() | {"type": int(OptionType.SUB_COMMAND)}
                )
            elif subcommand.is_subcommand:
                sub_cmds.append(subcommand.to_dict() | {"type": int(OptionType.SUB_COMMAND)})
        options = list(groups.values()) + sub_cmds
        output_data["options"] = options
        return output_data

    for _scope, cmds in commands.items():
        for cmd in cmds.values():
            cmd_name = str(cmd.name)
            if cmd not in cmd_bases[cmd_name]:
                cmd_bases[cmd_name].append(cmd)

    for cmd_list in cmd_bases.values():
        if any(c.is_subcommand for c in cmd_list):
            # validate all commands share required attributes
            scopes: list[Snowflake_Type] = list({s for c in cmd_list for s in c.scopes})
            base_description = next(
                (
                    c.description
                    for c in cmd_list
                    if str(c.description) is not None and str(c.description) != "No Description Set"
                ),
                "No Description Set",
            )
            nsfw = cmd_list[0].nsfw

            if any(str(c.description) not in (str(base_description), "No Description Set") for c in cmd_list):
                client.logger.warning(
                    f"Conflicting descriptions found in `{cmd_list[0].name}` subcommands; `{base_description!s}` will be used"
                )
            if any(c.default_member_permissions != cmd_list[0].default_member_permissions for c in cmd_list):
                raise ValueError(f"Conflicting `default_member_permissions` values found in `{cmd_list[0].name}`")
            if any(c.contexts != cmd_list[0].contexts for c in cmd_list):
                raise ValueError(f"Conflicting `contexts` values found in `{cmd_list[0].name}`")
            if any(c.integration_types != cmd_list[0].integration_types for c in cmd_list):
                raise ValueError(f"Conflicting `integration_types` values found in `{cmd_list[0].name}`")
            if any(c.dm_permission != cmd_list[0].dm_permission for c in cmd_list):
                raise ValueError(f"Conflicting `dm_permission` values found in `{cmd_list[0].name}`")
            if any(c.nsfw != nsfw for c in cmd_list):
                client.logger.warning(f"Conflicting `nsfw` values found in {cmd_list[0].name} - `True` will be used")
                nsfw = True

            for cmd in cmd_list:
                cmd.scopes = list(scopes)
                cmd.description = base_description
                cmd.nsfw = nsfw
            # end validation of attributes
            cmd_data = squash_subcommand(cmd_list)

            for s in scopes:
                output[s].append(cmd_data)
        else:
            for cmd in cmd_list:
                for s in cmd.scopes:
                    output[s].append(cmd.to_dict())
    return dict(output)

auto_defer(enabled=True, ephemeral=False, time_until_defer=0.0)

A decorator to add an auto defer to a application command.

Parameters:

Name Type Description Default
enabled bool

Should the command be deferred automatically

True
ephemeral bool

Should the command be deferred as ephemeral

False
time_until_defer float

How long to wait before deferring automatically

0.0
Source code in interactions/models/internal/application_commands.py
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
def auto_defer(
    enabled: bool = True, ephemeral: bool = False, time_until_defer: float = 0.0
) -> Callable[[InterCommandT], InterCommandT]:
    """
    A decorator to add an auto defer to a application command.

    Args:
        enabled: Should the command be deferred automatically
        ephemeral: Should the command be deferred as ephemeral
        time_until_defer: How long to wait before deferring automatically

    """

    def wrapper(func: InterCommandT) -> InterCommandT:
        if hasattr(func, "cmd_id"):
            raise ValueError("auto_defer decorators must be positioned under a slash_command decorator")
        func.auto_defer = AutoDefer(enabled=enabled, ephemeral=ephemeral, time_until_defer=time_until_defer)
        return func

    return wrapper

component_callback(*custom_id)

Register a coroutine as a component callback.

Component callbacks work the same way as commands, just using components as a way of invoking, instead of messages. Your callback will be given a single argument, ComponentContext

Note

This can optionally take a regex pattern, which will be used to match against the custom ID of the component.

If you do not supply a custom_id, the name of the coroutine will be used instead.

Parameters:

Name Type Description Default
*custom_id str | re.Pattern

The custom ID of the component to wait for

()
Source code in interactions/models/internal/application_commands.py
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
def component_callback(*custom_id: str | re.Pattern) -> Callable[[AsyncCallable], ComponentCommand]:
    """
    Register a coroutine as a component callback.

    Component callbacks work the same way as commands, just using components as a way of invoking, instead of messages.
    Your callback will be given a single argument, `ComponentContext`

    Note:
        This can optionally take a regex pattern, which will be used to match against the custom ID of the component.

        If you do not supply a `custom_id`, the name of the coroutine will be used instead.

    Args:
        *custom_id: The custom ID of the component to wait for

    """

    def wrapper(func: AsyncCallable) -> ComponentCommand:
        resolved_custom_id = custom_id or [func.__name__]

        if not asyncio.iscoroutinefunction(func):
            raise ValueError("Commands must be coroutines")

        return ComponentCommand(
            name=f"ComponentCallback::{resolved_custom_id}", callback=func, listeners=resolved_custom_id
        )

    custom_id = _unpack_helper(custom_id)
    custom_ids_validator(*custom_id)
    return wrapper

context_menu(name=MISSING, *, context_type, scopes=MISSING, default_member_permissions=None, integration_types=None, contexts=None, dm_permission=True)

A decorator to declare a coroutine as a Context Menu.

Parameters:

Name Type Description Default
name Absent[str | LocalisedName]

1-32 character name of the context menu, defaults to the name of the coroutine.

MISSING
context_type CommandType

The type of context menu

required
scopes Absent[List[Snowflake_Type]]

The scope this command exists within

MISSING
default_member_permissions Optional[Permissions]

What permissions members need to have by default to use this command.

None
integration_types Optional[List[Union[IntegrationType, int]]]

Installation context(s) where the command is available, only for globally-scoped commands.

None
contexts Optional[List[Union[ContextType, int]]]

Interaction context(s) where the command can be used, only for globally-scoped commands.

None
dm_permission bool

Should this command be available in DMs (deprecated).

True

Returns:

Type Description
Callable[[AsyncCallable], ContextMenu]

ContextMenu object

Source code in interactions/models/internal/application_commands.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
def context_menu(
    name: Absent[str | LocalisedName] = MISSING,
    *,
    context_type: "CommandType",
    scopes: Absent[List["Snowflake_Type"]] = MISSING,
    default_member_permissions: Optional["Permissions"] = None,
    integration_types: Optional[List[Union[IntegrationType, int]]] = None,
    contexts: Optional[List[Union[ContextType, int]]] = None,
    dm_permission: bool = True,
) -> Callable[[AsyncCallable], ContextMenu]:
    """
    A decorator to declare a coroutine as a Context Menu.

    Args:
        name: 1-32 character name of the context menu, defaults to the name of the coroutine.
        context_type: The type of context menu
        scopes: The scope this command exists within
        default_member_permissions: What permissions members need to have by default to use this command.
        integration_types: Installation context(s) where the command is available, only for globally-scoped commands.
        contexts: Interaction context(s) where the command can be used, only for globally-scoped commands.
        dm_permission: Should this command be available in DMs (deprecated).

    Returns:
        ContextMenu object

    """

    def wrapper(func: AsyncCallable) -> ContextMenu:
        if not asyncio.iscoroutinefunction(func):
            raise ValueError("Commands must be coroutines")

        perm = default_member_permissions
        if hasattr(func, "default_member_permissions"):
            if perm:
                perm = perm | func.default_member_permissions
            else:
                perm = func.default_member_permissions

        _name = name
        if _name is MISSING:
            _name = func.__name__

        cmd = ContextMenu(
            name=_name,
            type=context_type,
            scopes=scopes or [GLOBAL_SCOPE],
            default_member_permissions=perm,
            integration_types=integration_types or [IntegrationType.GUILD_INSTALL],
            contexts=contexts or [ContextType.GUILD, ContextType.BOT_DM, ContextType.PRIVATE_CHANNEL],
            dm_permission=dm_permission,
            callback=func,
        )
        return cmd

    return wrapper

contexts(guild=True, bot_dm=True, private_channel=True)

A decorator to set contexts where the command can be used for a application command.

Parameters:

Name Type Description Default
guild bool

Should the command be available in guilds

True
bot_dm bool

Should the command be available in bot DMs

True
private_channel bool

Should the command be available in private channels

True
Source code in interactions/models/internal/application_commands.py
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
def contexts(
    guild: bool = True, bot_dm: bool = True, private_channel: bool = True
) -> Callable[[InterCommandT], InterCommandT]:
    """
    A decorator to set contexts where the command can be used for a application command.

    Args:
        guild: Should the command be available in guilds
        bot_dm: Should the command be available in bot DMs
        private_channel: Should the command be available in private channels

    """
    kwargs = locals()

    def wrapper(func: InterCommandT) -> InterCommandT:
        if hasattr(func, "cmd_id"):
            raise ValueError("contexts decorators must be positioned under a command decorator")

        func.contexts = []
        for key in kwargs:
            if kwargs[key]:
                func.contexts.append(ContextType[key.upper()])

        return func

    return wrapper

global_autocomplete(option_name)

Decorator for global autocomplete functions

Parameters:

Name Type Description Default
option_name str

The name of the option to register the autocomplete function for

required

Returns:

Type Description
Callable[[AsyncCallable], GlobalAutoComplete]

The decorator

Source code in interactions/models/internal/application_commands.py
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
def global_autocomplete(option_name: str) -> Callable[[AsyncCallable], GlobalAutoComplete]:
    """
    Decorator for global autocomplete functions

    Args:
        option_name: The name of the option to register the autocomplete function for

    Returns:
        The decorator

    """

    def decorator(func: Callable) -> GlobalAutoComplete:
        if not asyncio.iscoroutinefunction(func):
            raise TypeError("Autocomplete functions must be coroutines")
        return GlobalAutoComplete(option_name, func)

    return decorator

integration_types(guild=True, user=False)

A decorator to set integration types for an application command.

Parameters:

Name Type Description Default
guild bool

Should the command be available for guilds

True
user bool

Should the command be available for individual users

False
Source code in interactions/models/internal/application_commands.py
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
def integration_types(guild: bool = True, user: bool = False) -> Callable[[InterCommandT], InterCommandT]:
    """
    A decorator to set integration types for an application command.

    Args:
        guild: Should the command be available for guilds
        user: Should the command be available for individual users

    """
    kwargs = locals()

    def wrapper(func: InterCommandT) -> InterCommandT:
        if hasattr(func, "cmd_id"):
            raise ValueError("integration_types decorators must be positioned under a command decorator")

        func.integration_types = []
        for key in kwargs:
            if kwargs[key]:
                func.integration_types.append(IntegrationType[key.upper() + "_INSTALL"])

        return func

    return wrapper

message_context_menu(name=MISSING, *, scopes=MISSING, default_member_permissions=None, integration_types=None, contexts=None, dm_permission=True)

A decorator to declare a coroutine as a Message Context Menu.

Parameters:

Name Type Description Default
name Absent[str | LocalisedName]

1-32 character name of the context menu, defaults to the name of the coroutine.

MISSING
scopes Absent[List[Snowflake_Type]]

The scope this command exists within

MISSING
default_member_permissions Optional[Permissions]

What permissions members need to have by default to use this command.

None
integration_types Optional[List[Union[IntegrationType, int]]]

Installation context(s) where the command is available, only for globally-scoped commands.

None
contexts Optional[List[Union[ContextType, int]]]

Interaction context(s) where the command can be used, only for globally-scoped commands.

None
dm_permission bool

Should this command be available in DMs (deprecated).

True

Returns:

Type Description
Callable[[AsyncCallable], ContextMenu]

ContextMenu object

Source code in interactions/models/internal/application_commands.py
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
def message_context_menu(
    name: Absent[str | LocalisedName] = MISSING,
    *,
    scopes: Absent[List["Snowflake_Type"]] = MISSING,
    default_member_permissions: Optional["Permissions"] = None,
    integration_types: Optional[List[Union[IntegrationType, int]]] = None,
    contexts: Optional[List[Union[ContextType, int]]] = None,
    dm_permission: bool = True,
) -> Callable[[AsyncCallable], ContextMenu]:
    """
    A decorator to declare a coroutine as a Message Context Menu.

    Args:
        name: 1-32 character name of the context menu, defaults to the name of the coroutine.
        scopes: The scope this command exists within
        default_member_permissions: What permissions members need to have by default to use this command.
        integration_types: Installation context(s) where the command is available, only for globally-scoped commands.
        contexts: Interaction context(s) where the command can be used, only for globally-scoped commands.
        dm_permission: Should this command be available in DMs (deprecated).

    Returns:
        ContextMenu object

    """
    return context_menu(
        name,
        context_type=CommandType.MESSAGE,
        scopes=scopes,
        default_member_permissions=default_member_permissions,
        integration_types=integration_types or [IntegrationType.GUILD_INSTALL],
        contexts=contexts or [ContextType.GUILD, ContextType.BOT_DM, ContextType.PRIVATE_CHANNEL],
        dm_permission=dm_permission,
    )

modal_callback(*custom_id)

Register a coroutine as a modal callback.

Modal callbacks work the same way as commands, just using modals as a way of invoking, instead of messages. Your callback will be given a single argument, ModalContext

Note

This can optionally take a regex pattern, which will be used to match against the custom ID of the modal.

If you do not supply a custom_id, the name of the coroutine will be used instead.

Parameters:

Name Type Description Default
*custom_id str | re.Pattern

The custom ID of the modal to wait for

()
Source code in interactions/models/internal/application_commands.py
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
def modal_callback(*custom_id: str | re.Pattern) -> Callable[[AsyncCallable], ModalCommand]:
    """
    Register a coroutine as a modal callback.

    Modal callbacks work the same way as commands, just using modals as a way of invoking, instead of messages.
    Your callback will be given a single argument, `ModalContext`

    Note:
        This can optionally take a regex pattern, which will be used to match against the custom ID of the modal.

        If you do not supply a `custom_id`, the name of the coroutine will be used instead.


    Args:
        *custom_id: The custom ID of the modal to wait for

    """

    def wrapper(func: AsyncCallable) -> ModalCommand:
        resolved_custom_id = custom_id or [func.__name__]

        if not asyncio.iscoroutinefunction(func):
            raise ValueError("Commands must be coroutines")

        return ModalCommand(name=f"ModalCallback::{resolved_custom_id}", callback=func, listeners=resolved_custom_id)

    custom_id = _unpack_helper(custom_id)
    custom_ids_validator(*custom_id)
    return wrapper

slash_command(name=MISSING, *, description=MISSING, scopes=MISSING, options=None, default_member_permissions=None, integration_types=None, contexts=None, dm_permission=True, sub_cmd_name=None, group_name=None, sub_cmd_description='No Description Set', group_description='No Description Set', nsfw=False)

A decorator to declare a coroutine as a slash command.

Note

While the base and group descriptions arent visible in the discord client, currently. We strongly advise defining them anyway, if you're using subcommands, as Discord has said they will be visible in one of the future ui updates.

Parameters:

Name Type Description Default
name Absent[str | LocalisedName]

1-32 character name of the command, defaults to the name of the coroutine.

MISSING
description Absent[str | LocalisedDesc]

1-100 character description of the command

MISSING
scopes Absent[List[Snowflake_Type]]

The scope this command exists within

MISSING
options Optional[List[Union[SlashCommandOption, Dict]]]

The parameters for the command, max 25

None
default_member_permissions Optional[Permissions]

What permissions members need to have by default to use this command.

None
integration_types Optional[List[Union[IntegrationType, int]]]

Installation context(s) where the command is available, only for globally-scoped commands.

None
contexts Optional[List[Union[ContextType, int]]]

Interaction context(s) where the command can be used, only for globally-scoped commands.

None
dm_permission bool

Should this command be available in DMs (deprecated).

True
sub_cmd_name str | LocalisedName

1-32 character name of the subcommand

None
sub_cmd_description str | LocalisedDesc

1-100 character description of the subcommand

'No Description Set'
group_name str | LocalisedName

1-32 character name of the group

None
group_description str | LocalisedDesc

1-100 character description of the group

'No Description Set'
nsfw bool

This command should only work in NSFW channels

False

Returns:

Type Description
Callable[[AsyncCallable], SlashCommand]

SlashCommand Object

Source code in interactions/models/internal/application_commands.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
def slash_command(
    name: Absent[str | LocalisedName] = MISSING,
    *,
    description: Absent[str | LocalisedDesc] = MISSING,
    scopes: Absent[List["Snowflake_Type"]] = MISSING,
    options: Optional[List[Union[SlashCommandOption, Dict]]] = None,
    default_member_permissions: Optional["Permissions"] = None,
    integration_types: Optional[List[Union[IntegrationType, int]]] = None,
    contexts: Optional[List[Union[ContextType, int]]] = None,
    dm_permission: bool = True,
    sub_cmd_name: str | LocalisedName = None,
    group_name: str | LocalisedName = None,
    sub_cmd_description: str | LocalisedDesc = "No Description Set",
    group_description: str | LocalisedDesc = "No Description Set",
    nsfw: bool = False,
) -> Callable[[AsyncCallable], SlashCommand]:
    """
    A decorator to declare a coroutine as a slash command.

    !!! note
        While the base and group descriptions arent visible in the discord client, currently.
        We strongly advise defining them anyway, if you're using subcommands, as Discord has said they will be visible in
        one of the future ui updates.

    Args:
        name: 1-32 character name of the command, defaults to the name of the coroutine.
        description: 1-100 character description of the command
        scopes: The scope this command exists within
        options: The parameters for the command, max 25
        default_member_permissions: What permissions members need to have by default to use this command.
        integration_types: Installation context(s) where the command is available, only for globally-scoped commands.
        contexts: Interaction context(s) where the command can be used, only for globally-scoped commands.
        dm_permission: Should this command be available in DMs (deprecated).
        sub_cmd_name: 1-32 character name of the subcommand
        sub_cmd_description: 1-100 character description of the subcommand
        group_name: 1-32 character name of the group
        group_description: 1-100 character description of the group
        nsfw: This command should only work in NSFW channels

    Returns:
        SlashCommand Object

    """

    def wrapper(func: AsyncCallable) -> SlashCommand:
        if not asyncio.iscoroutinefunction(func):
            raise ValueError("Commands must be coroutines")

        perm = default_member_permissions
        if hasattr(func, "default_member_permissions"):
            if perm:
                perm = perm | func.default_member_permissions
            else:
                perm = func.default_member_permissions

        _name = name
        if _name is MISSING:
            _name = func.__name__

        _description = description
        if _description is MISSING:
            _description = func.__doc__ or "No Description Set"

        cmd = SlashCommand(
            name=_name,
            group_name=group_name,
            group_description=group_description,
            sub_cmd_name=sub_cmd_name,
            sub_cmd_description=sub_cmd_description,
            description=_description,
            scopes=scopes or [GLOBAL_SCOPE],
            default_member_permissions=perm,
            integration_types=integration_types or [IntegrationType.GUILD_INSTALL],
            contexts=contexts or [ContextType.GUILD, ContextType.BOT_DM, ContextType.PRIVATE_CHANNEL],
            dm_permission=dm_permission,
            callback=func,
            options=options,
            nsfw=nsfw,
        )

        return cmd

    return wrapper

slash_default_member_permission(permission)

A decorator to permissions members need to have by default to use a command.

Parameters:

Name Type Description Default
permission Permissions

The permissions to require for to this command

required
Source code in interactions/models/internal/application_commands.py
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
def slash_default_member_permission(
    permission: "Permissions",
) -> Callable[[SlashCommandT], SlashCommandT]:
    """
    A decorator to permissions members need to have by default to use a command.

    Args:
        permission: The permissions to require for to this command

    """

    def wrapper(func: SlashCommandT) -> SlashCommandT:
        if hasattr(func, "cmd_id"):
            raise ValueError(
                "slash_default_member_permission decorators must be positioned under a slash_command decorator"
            )

        if not hasattr(func, "default_member_permissions") or func.default_member_permissions is None:
            func.default_member_permissions = permission
        else:
            func.default_member_permissions = func.default_member_permissions | permission
        return func

    return wrapper

slash_option(name, description, opt_type, required=False, autocomplete=False, choices=None, channel_types=None, min_value=None, max_value=None, min_length=None, max_length=None, argument_name=None)

A decorator to add an option to a slash command.

Parameters:

Name Type Description Default
name str

1-32 lowercase character name matching ^[\w-]{1,32}$

required
opt_type Union[OptionType, int]

The type of option

required
description str

1-100 character description of option

required
required bool

If the parameter is required or optional--default false

False
autocomplete bool

If autocomplete interactions are enabled for this STRING, INTEGER, or NUMBER type option

False
choices List[Union[SlashCommandChoice, dict]] | None

A list of choices the user has to pick between (max 25)

None
channel_types Optional[list[Union[ChannelType, int]]]

The channel types permitted. The option needs to be a channel

None
min_value Optional[float]

The minimum value permitted. The option needs to be an integer or float

None
max_value Optional[float]

The maximum value permitted. The option needs to be an integer or float

None
min_length Optional[int]

The minimum length of text a user can input. The option needs to be a string

None
max_length Optional[int]

The maximum length of text a user can input. The option needs to be a string

None
argument_name Optional[str]

The name of the argument to be used in the function. If not given, assumed to be the same as the name of the option

None
Source code in interactions/models/internal/application_commands.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
def slash_option(
    name: str,
    description: str,
    opt_type: Union[OptionType, int],
    required: bool = False,
    autocomplete: bool = False,
    choices: List[Union[SlashCommandChoice, dict]] | None = None,
    channel_types: Optional[list[Union[ChannelType, int]]] = None,
    min_value: Optional[float] = None,
    max_value: Optional[float] = None,
    min_length: Optional[int] = None,
    max_length: Optional[int] = None,
    argument_name: Optional[str] = None,
) -> Callable[[SlashCommandT], SlashCommandT]:
    r"""
    A decorator to add an option to a slash command.

    Args:
        name: 1-32 lowercase character name matching ^[\w-]{1,32}$
        opt_type: The type of option
        description: 1-100 character description of option
        required: If the parameter is required or optional--default false
        autocomplete: If autocomplete interactions are enabled for this STRING, INTEGER, or NUMBER type option
        choices: A list of choices the user has to pick between (max 25)
        channel_types: The channel types permitted. The option needs to be a channel
        min_value: The minimum value permitted. The option needs to be an integer or float
        max_value: The maximum value permitted. The option needs to be an integer or float
        min_length: The minimum length of text a user can input. The option needs to be a string
        max_length: The maximum length of text a user can input. The option needs to be a string
        argument_name: The name of the argument to be used in the function. If not given, assumed to be the same as the name of the option

    """

    def wrapper(func: SlashCommandT) -> SlashCommandT:
        if hasattr(func, "cmd_id"):
            raise ValueError("slash_option decorators must be positioned under a slash_command decorator")

        option = SlashCommandOption(
            name=name,
            type=opt_type,
            description=description,
            required=required,
            autocomplete=autocomplete,
            choices=choices or [],
            channel_types=channel_types,
            min_value=min_value,
            max_value=max_value,
            min_length=min_length,
            max_length=max_length,
            argument_name=argument_name,
        )
        if not hasattr(func, "options"):
            func.options = []
        func.options.insert(0, option)
        return func

    return wrapper

subcommand(base, *, subcommand_group=None, name=MISSING, description=MISSING, base_description=None, base_desc=None, base_default_member_permissions=None, base_integration_types=None, base_contexts=None, base_dm_permission=True, subcommand_group_description=None, sub_group_desc=None, scopes=None, options=None, nsfw=False)

A decorator specifically tailored for creating subcommands.

Parameters:

Name Type Description Default
base str | LocalisedName

The name of the base command

required
subcommand_group Optional[str | LocalisedName]

The name of the subcommand group, if any.

None
name Absent[str | LocalisedName]

The name of the subcommand, defaults to the name of the coroutine.

MISSING
description Absent[str | LocalisedDesc]

The description of the subcommand

MISSING
base_description Optional[str | LocalisedDesc]

The description of the base command

None
base_desc Optional[str | LocalisedDesc]

An alias of base_description

None
base_default_member_permissions Optional[Permissions]

What permissions members need to have by default to use this command.

None
base_integration_types Optional[List[Union[IntegrationType, int]]]

Installation context(s) where the command is available, only for globally-scoped commands.

None
base_contexts Optional[List[Union[ContextType, int]]]

Interaction context(s) where the command can be used, only for globally-scoped commands.

None
base_dm_permission bool

Should this command be available in DMs (deprecated).

True
subcommand_group_description Optional[str | LocalisedDesc]

Description of the subcommand group

None
sub_group_desc Optional[str | LocalisedDesc]

An alias for subcommand_group_description

None
scopes List[Snowflake_Type] | None

The scopes of which this command is available, defaults to GLOBAL_SCOPE

None
options List[dict] | None

The options for this command

None
nsfw bool

This command should only work in NSFW channels

False

Returns:

Type Description
Callable[[AsyncCallable], SlashCommand]

A SlashCommand object

Source code in interactions/models/internal/application_commands.py
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
def subcommand(
    base: str | LocalisedName,
    *,
    subcommand_group: Optional[str | LocalisedName] = None,
    name: Absent[str | LocalisedName] = MISSING,
    description: Absent[str | LocalisedDesc] = MISSING,
    base_description: Optional[str | LocalisedDesc] = None,
    base_desc: Optional[str | LocalisedDesc] = None,
    base_default_member_permissions: Optional["Permissions"] = None,
    base_integration_types: Optional[List[Union[IntegrationType, int]]] = None,
    base_contexts: Optional[List[Union[ContextType, int]]] = None,
    base_dm_permission: bool = True,
    subcommand_group_description: Optional[str | LocalisedDesc] = None,
    sub_group_desc: Optional[str | LocalisedDesc] = None,
    scopes: List["Snowflake_Type"] | None = None,
    options: List[dict] | None = None,
    nsfw: bool = False,
) -> Callable[[AsyncCallable], SlashCommand]:
    """
    A decorator specifically tailored for creating subcommands.

    Args:
        base: The name of the base command
        subcommand_group: The name of the subcommand group, if any.
        name: The name of the subcommand, defaults to the name of the coroutine.
        description: The description of the subcommand
        base_description: The description of the base command
        base_desc: An alias of `base_description`
        base_default_member_permissions: What permissions members need to have by default to use this command.
        base_integration_types: Installation context(s) where the command is available, only for globally-scoped commands.
        base_contexts: Interaction context(s) where the command can be used, only for globally-scoped commands.
        base_dm_permission: Should this command be available in DMs (deprecated).
        subcommand_group_description: Description of the subcommand group
        sub_group_desc: An alias for `subcommand_group_description`
        scopes: The scopes of which this command is available, defaults to GLOBAL_SCOPE
        options: The options for this command
        nsfw: This command should only work in NSFW channels

    Returns:
        A SlashCommand object

    """

    def wrapper(func: AsyncCallable) -> SlashCommand:
        if not asyncio.iscoroutinefunction(func):
            raise ValueError("Commands must be coroutines")

        _name = name
        if _name is MISSING:
            _name = func.__name__

        _description = description
        if _description is MISSING:
            _description = func.__doc__ or "No Description Set"

        cmd = SlashCommand(
            name=base,
            description=(base_description or base_desc) or "No Description Set",
            group_name=subcommand_group,
            group_description=(subcommand_group_description or sub_group_desc) or "No Description Set",
            sub_cmd_name=_name,
            sub_cmd_description=_description,
            default_member_permissions=base_default_member_permissions,
            integration_types=base_integration_types or [IntegrationType.GUILD_INSTALL],
            contexts=base_contexts or [ContextType.GUILD, ContextType.BOT_DM, ContextType.PRIVATE_CHANNEL],
            dm_permission=base_dm_permission,
            scopes=scopes or [GLOBAL_SCOPE],
            callback=func,
            options=options,
            nsfw=nsfw,
        )
        return cmd

    return wrapper

sync_needed(local_cmd, remote_cmd=None)

Compares a local application command to its remote counterpart to determine if a sync is required.

Parameters:

Name Type Description Default
local_cmd dict

The local json representation of the command

required
remote_cmd Optional[dict]

The json representation of the command from Discord

None

Returns:

Type Description
bool

Boolean indicating if a sync is needed

Source code in interactions/models/internal/application_commands.py
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
def sync_needed(local_cmd: dict, remote_cmd: Optional[dict] = None) -> bool:
    """
    Compares a local application command to its remote counterpart to determine if a sync is required.

    Args:
        local_cmd: The local json representation of the command
        remote_cmd: The json representation of the command from Discord

    Returns:
        Boolean indicating if a sync is needed

    """
    if not remote_cmd:
        # No remote version, command must be new
        return True

    if not _compare_commands(local_cmd, remote_cmd):
        # basic comparison of attributes
        return True

    if remote_cmd["type"] == CommandType.CHAT_INPUT:
        try:
            if not _compare_options(local_cmd["options"], remote_cmd["options"]):
                # options are not the same, sync needed
                return True
        except KeyError:
            if "options" in local_cmd or "options" in remote_cmd:
                return True

    return False

user_context_menu(name=MISSING, *, scopes=MISSING, default_member_permissions=None, integration_types=None, contexts=None, dm_permission=True)

A decorator to declare a coroutine as a User Context Menu.

Parameters:

Name Type Description Default
name Absent[str | LocalisedName]

1-32 character name of the context menu, defaults to the name of the coroutine.

MISSING
scopes Absent[List[Snowflake_Type]]

The scope this command exists within

MISSING
default_member_permissions Optional[Permissions]

What permissions members need to have by default to use this command.

None
integration_types Optional[List[Union[IntegrationType, int]]]

Installation context(s) where the command is available, only for globally-scoped commands.

None
contexts Optional[List[Union[ContextType, int]]]

Interaction context(s) where the command can be used, only for globally-scoped commands.

None
dm_permission bool

Should this command be available in DMs (deprecated).

True

Returns:

Type Description
Callable[[AsyncCallable], ContextMenu]

ContextMenu object

Source code in interactions/models/internal/application_commands.py
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
def user_context_menu(
    name: Absent[str | LocalisedName] = MISSING,
    *,
    scopes: Absent[List["Snowflake_Type"]] = MISSING,
    default_member_permissions: Optional["Permissions"] = None,
    integration_types: Optional[List[Union[IntegrationType, int]]] = None,
    contexts: Optional[List[Union[ContextType, int]]] = None,
    dm_permission: bool = True,
) -> Callable[[AsyncCallable], ContextMenu]:
    """
    A decorator to declare a coroutine as a User Context Menu.

    Args:
        name: 1-32 character name of the context menu, defaults to the name of the coroutine.
        scopes: The scope this command exists within
        default_member_permissions: What permissions members need to have by default to use this command.
        integration_types: Installation context(s) where the command is available, only for globally-scoped commands.
        contexts: Interaction context(s) where the command can be used, only for globally-scoped commands.
        dm_permission: Should this command be available in DMs (deprecated).

    Returns:
        ContextMenu object

    """
    return context_menu(
        name,
        context_type=CommandType.USER,
        scopes=scopes,
        default_member_permissions=default_member_permissions,
        integration_types=integration_types or [IntegrationType.GUILD_INSTALL],
        contexts=contexts or [ContextType.GUILD, ContextType.BOT_DM, ContextType.PRIVATE_CHANNEL],
        dm_permission=dm_permission,
    )