Models and enums used for Discord's Components interaction flow.

This module

Expand source code
Browse git
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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.
"""Models and enums used for Discord's Components interaction flow."""
from __future__ import annotations

__all__: typing.Sequence[str] = ("ComponentInteraction", "COMPONENT_RESPONSE_TYPES", "ComponentResponseTypesT")

import typing

import attr

from hikari import channels
from hikari import traits
from hikari.interactions import base_interactions

if typing.TYPE_CHECKING:
    from hikari import guilds
    from hikari import locales
    from hikari import messages
    from hikari import permissions
    from hikari import snowflakes
    from hikari import users
    from hikari.api import special_endpoints


_DEFERRED_TYPES: typing.AbstractSet[_DeferredTypesT] = frozenset(
    [base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE, base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE]
)
_DeferredTypesT = typing.Literal[
    base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE, 5, base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE, 6
]
_IMMEDIATE_TYPES: typing.AbstractSet[_ImmediateTypesT] = frozenset(
    [base_interactions.ResponseType.MESSAGE_CREATE, base_interactions.ResponseType.MESSAGE_UPDATE]
)
_ImmediateTypesT = typing.Literal[
    base_interactions.ResponseType.MESSAGE_CREATE, 4, base_interactions.ResponseType.MESSAGE_UPDATE, 7
]


COMPONENT_RESPONSE_TYPES: typing.Final[typing.AbstractSet[ComponentResponseTypesT]] = frozenset(
    [*_DEFERRED_TYPES, *_IMMEDIATE_TYPES]
)
"""Set of the response types which are valid for a component interaction.

This includes:

* `hikari.interactions.base_interactions.ResponseType.MESSAGE_CREATE`
* `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE`
* `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE`
* `hikari.interactions.base_interactions.ResponseType.MESSAGE_UPDATE`
"""

ComponentResponseTypesT = typing.Union[_ImmediateTypesT, _DeferredTypesT]
"""Type-hint of the response types which are valid for a component interaction.

The following types are valid for this:

* `hikari.interactions.base_interactions.ResponseType.MESSAGE_CREATE`/`4`
* `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE`/`5`
* `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE`/`6`
* `hikari.interactions.base_interactions.ResponseType.MESSAGE_UPDATE`/`7`
"""


@attr.define(hash=True, weakref_slot=False)
class ComponentInteraction(base_interactions.MessageResponseMixin[ComponentResponseTypesT]):
    """Represents a component interaction on Discord."""

    channel_id: snowflakes.Snowflake = attr.field(eq=False)
    """ID of the channel this interaction was triggered in."""

    component_type: typing.Union[messages.ComponentType, int] = attr.field(eq=False)
    """The type of component which triggers this interaction.

    !!! note
        This will never be `ButtonStyle.LINK` as link buttons don't trigger
        interactions.
    """

    custom_id: str = attr.field(eq=False)
    """Developer defined ID of the component which triggered this interaction."""

    values: typing.Sequence[str] = attr.field(eq=False)
    """Sequence of the values which were selected for a select menu component."""

    guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False)
    """ID of the guild this interaction was triggered in.

    This will be `builtins.None` for component interactions triggered in DMs.
    """

    guild_locale: typing.Optional[typing.Union[str, locales.Locale]] = attr.field(eq=False, hash=False, repr=True)
    """The preferred language of the guild this component interaction was triggered in.

    This will be `builtins.None` for component interactions triggered in DMs.

    !!! note
        This value can usually only be changed if `COMMUNITY` is in `hikari.guilds.Guild.features`
        for the guild and will otherwise default to `en-US`.
    """

    message: messages.Message = attr.field(eq=False, repr=False)
    """Object of the message the components for this interaction are attached to."""

    member: typing.Optional[base_interactions.InteractionMember] = attr.field(eq=False, hash=False, repr=True)
    """The member who triggered this interaction.

    This will be `builtins.None` for interactions triggered in DMs.

    !!! note
        This member object comes with the extra field `permissions` which
        contains the member's permissions in the current channel.
    """

    user: users.User = attr.field(eq=False, hash=False, repr=True)
    """The user who triggered this interaction."""

    locale: typing.Union[str, locales.Locale] = attr.field(eq=False, hash=False, repr=True)
    """The selected language of the user who triggered this component interaction."""

    app_permissions: typing.Optional[permissions.Permissions] = attr.field(eq=False, hash=False, repr=False)
    """Permissions the bot has in this interaction's channel if it's in a guild."""

    def build_response(self, type_: _ImmediateTypesT, /) -> special_endpoints.InteractionMessageBuilder:
        """Get a message response builder for use in the REST server flow.

        !!! note
            For interactions received over the gateway
            `ComponentInteraction.create_initial_response` should be used to set
            the interaction response message.

        Parameters
        ----------
        type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
            The type of immediate response this should be.

            This may be one of the following:

            * `hikari.interactions.base_interactions.ResponseType.MESSAGE_CREATE`
            * `hikari.interactions.base_interactions.ResponseType.MESSAGE_UPDATE`

        Examples
        --------
        ```py
        async def handle_component_interaction(interaction: ComponentInteraction) -> InteractionMessageBuilder:
            return (
                interaction
                .build_response(ResponseType.MESSAGE_UPDATE)
                .add_embed(Embed(description="Hi there"))
                .set_content("Konnichiwa")
            )
        ```

        Returns
        -------
        hikari.api.special_endpoints.InteractionMessageBuilder
            Interaction message response builder object.
        """
        if type_ not in _IMMEDIATE_TYPES:
            raise ValueError("Invalid type passed for an immediate response")

        return self.app.rest.interaction_message_builder(type_)

    def build_deferred_response(self, type_: _DeferredTypesT, /) -> special_endpoints.InteractionDeferredBuilder:
        """Get a deferred message response builder for use in the REST server flow.

        !!! note
            For interactions received over the gateway
            `ComponentInteraction.create_initial_response` should be used to set
            the interaction response message.

        !!! note
            Unlike `hikari.api.special_endpoints.InteractionMessageBuilder`,
            the result of this call can be returned as is without any modifications
            being made to it.

        Parameters
        ----------
        type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
            The type of deferred response this should be.

            This may be one of the following:

            * `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE`
            * `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE`

        Returns
        -------
        hikari.api.special_endpoints.InteractionDeferredBuilder
            Deferred interaction message response builder object.
        """
        if type_ not in _DEFERRED_TYPES:
            raise ValueError("Invalid type passed for a deferred response")

        return self.app.rest.interaction_deferred_builder(type_)

    async def fetch_channel(self) -> channels.TextableChannel:
        """Fetch the channel this interaction occurred in.

        Returns
        -------
        hikari.channels.TextableChannel
            The channel. This will be a _derivative_ of `hikari.channels.TextableChannel`.

        Raises
        ------
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.ForbiddenError
            If you are missing the `READ_MESSAGES` permission in the channel.
        hikari.errors.NotFoundError
            If the channel is not found.
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitedError
            Usually, Hikari will handle and retry on hitting
            rate-limits automatically. This includes most bucket-specific
            rate-limits and global rate-limits. In some rare edge cases,
            however, Discord implements other undocumented rules for
            rate-limiting, such as limits per attribute. These cannot be
            detected or handled normally by Hikari due to their undocumented
            nature, and will trigger this exception if they occur.
        hikari.errors.InternalServerError
            If an internal error occurs on Discord while handling the request.
        """
        channel = await self.app.rest.fetch_channel(self.channel_id)
        assert isinstance(channel, channels.TextableChannel)
        return channel

    def get_channel(self) -> typing.Union[channels.GuildTextChannel, channels.GuildNewsChannel, None]:
        """Get the guild channel this interaction occurred in.

        !!! note
            This will always return `builtins.None` for interactions triggered
            in a DM channel.

        Returns
        -------
        typing.Union[hikari.channels.GuildTextChannel, hikari.channels.GuildNewsChannel, builtins.None]
            The object of the guild channel that was found in the cache or
            `builtins.None`.
        """
        if isinstance(self.app, traits.CacheAware):
            channel = self.app.cache.get_guild_channel(self.channel_id)
            assert isinstance(channel, (channels.GuildTextChannel, channels.GuildNewsChannel))
            return channel

        return None

    async def fetch_guild(self) -> typing.Optional[guilds.RESTGuild]:
        """Fetch the guild this interaction happened in.

        Returns
        -------
        typing.Optional[hikari.guilds.RESTGuild]
            Object of the guild this interaction happened in or `builtins.None`
            if this occurred within a DM channel.

        Raises
        ------
        hikari.errors.ForbiddenError
            If you are not part of the guild.
        hikari.errors.NotFoundError
            If the guild is not found.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitedError
            Usually, Hikari will handle and retry on hitting
            rate-limits automatically. This includes most bucket-specific
            rate-limits and global rate-limits. In some rare edge cases,
            however, Discord implements other undocumented rules for
            rate-limiting, such as limits per attribute. These cannot be
            detected or handled normally by Hikari due to their undocumented
            nature, and will trigger this exception if they occur.
        hikari.errors.InternalServerError
            If an internal error occurs on Discord while handling the request.
        """
        if not self.guild_id:
            return None

        return await self.app.rest.fetch_guild(self.guild_id)

    def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
        """Get the object of this interaction's guild guild from the cache.

        Returns
        -------
        typing.Optional[hikari.guilds.GatewayGuild]
            The object of the guild if found, else `builtins.None`.
        """
        if self.guild_id and isinstance(self.app, traits.CacheAware):
            return self.app.cache.get_guild(self.guild_id)

        return None

    async def fetch_parent_message(self) -> messages.Message:
        """Fetch the message which this interaction was triggered on.

        Returns
        -------
        hikari.messages.Message
            The requested message.

        Raises
        ------
        builtins.ValueError
            If `token` is not available.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the webhook is not found or the webhook's message wasn't found.
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitedError
            Usually, Hikari will handle and retry on hitting
            rate-limits automatically. This includes most bucket-specific
            rate-limits and global rate-limits. In some rare edge cases,
            however, Discord implements other undocumented rules for
            rate-limiting, such as limits per attribute. These cannot be
            detected or handled normally by Hikari due to their undocumented
            nature, and will trigger this exception if they occur.
        hikari.errors.InternalServerError
            If an internal error occurs on Discord while handling the request.
        """
        return await self.fetch_message(self.message.id)

    def get_parent_message(self) -> typing.Optional[messages.PartialMessage]:
        """Get the message which this interaction was triggered on from the cache.

        Returns
        -------
        typing.Optional[hikari.messages.Message]
            The object of the message found in the cache or `builtins.None`.
        """
        if isinstance(self.app, traits.CacheAware):
            return self.app.cache.get_message(self.message.id)

        return None

Variables and Type Hints

const COMPONENT_RESPONSE_TYPESFinal[AbstractSet[ComponentResponseTypesT]]

Set of the response types which are valid for a component interaction.

This includes:

var ComponentResponseTypesT

Type-hint of the response types which are valid for a component interaction.

The following types are valid for this:

Classes

dataclass ComponentInteraction

class ComponentInteraction (
    channel_id: snowflakes.Snowflake,
    component_type: Union[messages.ComponentTypeint],
    custom_id: str,
    values: Sequence[str],
    guild_id: Optional[snowflakes.Snowflake],
    guild_locale: Optional[Union[strlocales.Locale]],
    message: messages.Message,
    member: Optional[base_interactions.InteractionMember],
    user: users.User,
    locale: Union[strlocales.Locale],
    app_permissions: Optional[permissions.Permissions],
    *,
    app: traits.RESTAware,
    id: snowflakes.Snowflake,
    application_id: snowflakes.Snowflake,
    type: Union[InteractionType, int],
    token: str,
    version: int,
): ...

Represents a component interaction on Discord.

Method generated by attrs for class ComponentInteraction.

Expand source code
Browse git
class ComponentInteraction(base_interactions.MessageResponseMixin[ComponentResponseTypesT]):
    """Represents a component interaction on Discord."""

    channel_id: snowflakes.Snowflake = attr.field(eq=False)
    """ID of the channel this interaction was triggered in."""

    component_type: typing.Union[messages.ComponentType, int] = attr.field(eq=False)
    """The type of component which triggers this interaction.

    !!! note
        This will never be `ButtonStyle.LINK` as link buttons don't trigger
        interactions.
    """

    custom_id: str = attr.field(eq=False)
    """Developer defined ID of the component which triggered this interaction."""

    values: typing.Sequence[str] = attr.field(eq=False)
    """Sequence of the values which were selected for a select menu component."""

    guild_id: typing.Optional[snowflakes.Snowflake] = attr.field(eq=False)
    """ID of the guild this interaction was triggered in.

    This will be `builtins.None` for component interactions triggered in DMs.
    """

    guild_locale: typing.Optional[typing.Union[str, locales.Locale]] = attr.field(eq=False, hash=False, repr=True)
    """The preferred language of the guild this component interaction was triggered in.

    This will be `builtins.None` for component interactions triggered in DMs.

    !!! note
        This value can usually only be changed if `COMMUNITY` is in `hikari.guilds.Guild.features`
        for the guild and will otherwise default to `en-US`.
    """

    message: messages.Message = attr.field(eq=False, repr=False)
    """Object of the message the components for this interaction are attached to."""

    member: typing.Optional[base_interactions.InteractionMember] = attr.field(eq=False, hash=False, repr=True)
    """The member who triggered this interaction.

    This will be `builtins.None` for interactions triggered in DMs.

    !!! note
        This member object comes with the extra field `permissions` which
        contains the member's permissions in the current channel.
    """

    user: users.User = attr.field(eq=False, hash=False, repr=True)
    """The user who triggered this interaction."""

    locale: typing.Union[str, locales.Locale] = attr.field(eq=False, hash=False, repr=True)
    """The selected language of the user who triggered this component interaction."""

    app_permissions: typing.Optional[permissions.Permissions] = attr.field(eq=False, hash=False, repr=False)
    """Permissions the bot has in this interaction's channel if it's in a guild."""

    def build_response(self, type_: _ImmediateTypesT, /) -> special_endpoints.InteractionMessageBuilder:
        """Get a message response builder for use in the REST server flow.

        !!! note
            For interactions received over the gateway
            `ComponentInteraction.create_initial_response` should be used to set
            the interaction response message.

        Parameters
        ----------
        type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
            The type of immediate response this should be.

            This may be one of the following:

            * `hikari.interactions.base_interactions.ResponseType.MESSAGE_CREATE`
            * `hikari.interactions.base_interactions.ResponseType.MESSAGE_UPDATE`

        Examples
        --------
        ```py
        async def handle_component_interaction(interaction: ComponentInteraction) -> InteractionMessageBuilder:
            return (
                interaction
                .build_response(ResponseType.MESSAGE_UPDATE)
                .add_embed(Embed(description="Hi there"))
                .set_content("Konnichiwa")
            )
        ```

        Returns
        -------
        hikari.api.special_endpoints.InteractionMessageBuilder
            Interaction message response builder object.
        """
        if type_ not in _IMMEDIATE_TYPES:
            raise ValueError("Invalid type passed for an immediate response")

        return self.app.rest.interaction_message_builder(type_)

    def build_deferred_response(self, type_: _DeferredTypesT, /) -> special_endpoints.InteractionDeferredBuilder:
        """Get a deferred message response builder for use in the REST server flow.

        !!! note
            For interactions received over the gateway
            `ComponentInteraction.create_initial_response` should be used to set
            the interaction response message.

        !!! note
            Unlike `hikari.api.special_endpoints.InteractionMessageBuilder`,
            the result of this call can be returned as is without any modifications
            being made to it.

        Parameters
        ----------
        type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
            The type of deferred response this should be.

            This may be one of the following:

            * `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE`
            * `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE`

        Returns
        -------
        hikari.api.special_endpoints.InteractionDeferredBuilder
            Deferred interaction message response builder object.
        """
        if type_ not in _DEFERRED_TYPES:
            raise ValueError("Invalid type passed for a deferred response")

        return self.app.rest.interaction_deferred_builder(type_)

    async def fetch_channel(self) -> channels.TextableChannel:
        """Fetch the channel this interaction occurred in.

        Returns
        -------
        hikari.channels.TextableChannel
            The channel. This will be a _derivative_ of `hikari.channels.TextableChannel`.

        Raises
        ------
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.ForbiddenError
            If you are missing the `READ_MESSAGES` permission in the channel.
        hikari.errors.NotFoundError
            If the channel is not found.
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitedError
            Usually, Hikari will handle and retry on hitting
            rate-limits automatically. This includes most bucket-specific
            rate-limits and global rate-limits. In some rare edge cases,
            however, Discord implements other undocumented rules for
            rate-limiting, such as limits per attribute. These cannot be
            detected or handled normally by Hikari due to their undocumented
            nature, and will trigger this exception if they occur.
        hikari.errors.InternalServerError
            If an internal error occurs on Discord while handling the request.
        """
        channel = await self.app.rest.fetch_channel(self.channel_id)
        assert isinstance(channel, channels.TextableChannel)
        return channel

    def get_channel(self) -> typing.Union[channels.GuildTextChannel, channels.GuildNewsChannel, None]:
        """Get the guild channel this interaction occurred in.

        !!! note
            This will always return `builtins.None` for interactions triggered
            in a DM channel.

        Returns
        -------
        typing.Union[hikari.channels.GuildTextChannel, hikari.channels.GuildNewsChannel, builtins.None]
            The object of the guild channel that was found in the cache or
            `builtins.None`.
        """
        if isinstance(self.app, traits.CacheAware):
            channel = self.app.cache.get_guild_channel(self.channel_id)
            assert isinstance(channel, (channels.GuildTextChannel, channels.GuildNewsChannel))
            return channel

        return None

    async def fetch_guild(self) -> typing.Optional[guilds.RESTGuild]:
        """Fetch the guild this interaction happened in.

        Returns
        -------
        typing.Optional[hikari.guilds.RESTGuild]
            Object of the guild this interaction happened in or `builtins.None`
            if this occurred within a DM channel.

        Raises
        ------
        hikari.errors.ForbiddenError
            If you are not part of the guild.
        hikari.errors.NotFoundError
            If the guild is not found.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitedError
            Usually, Hikari will handle and retry on hitting
            rate-limits automatically. This includes most bucket-specific
            rate-limits and global rate-limits. In some rare edge cases,
            however, Discord implements other undocumented rules for
            rate-limiting, such as limits per attribute. These cannot be
            detected or handled normally by Hikari due to their undocumented
            nature, and will trigger this exception if they occur.
        hikari.errors.InternalServerError
            If an internal error occurs on Discord while handling the request.
        """
        if not self.guild_id:
            return None

        return await self.app.rest.fetch_guild(self.guild_id)

    def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
        """Get the object of this interaction's guild guild from the cache.

        Returns
        -------
        typing.Optional[hikari.guilds.GatewayGuild]
            The object of the guild if found, else `builtins.None`.
        """
        if self.guild_id and isinstance(self.app, traits.CacheAware):
            return self.app.cache.get_guild(self.guild_id)

        return None

    async def fetch_parent_message(self) -> messages.Message:
        """Fetch the message which this interaction was triggered on.

        Returns
        -------
        hikari.messages.Message
            The requested message.

        Raises
        ------
        builtins.ValueError
            If `token` is not available.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the webhook is not found or the webhook's message wasn't found.
        hikari.errors.RateLimitTooLongError
            Raised in the event that a rate limit occurs that is
            longer than `max_rate_limit` when making a request.
        hikari.errors.RateLimitedError
            Usually, Hikari will handle and retry on hitting
            rate-limits automatically. This includes most bucket-specific
            rate-limits and global rate-limits. In some rare edge cases,
            however, Discord implements other undocumented rules for
            rate-limiting, such as limits per attribute. These cannot be
            detected or handled normally by Hikari due to their undocumented
            nature, and will trigger this exception if they occur.
        hikari.errors.InternalServerError
            If an internal error occurs on Discord while handling the request.
        """
        return await self.fetch_message(self.message.id)

    def get_parent_message(self) -> typing.Optional[messages.PartialMessage]:
        """Get the message which this interaction was triggered on from the cache.

        Returns
        -------
        typing.Optional[hikari.messages.Message]
            The object of the message found in the cache or `builtins.None`.
        """
        if isinstance(self.app, traits.CacheAware):
            return self.app.cache.get_message(self.message.id)

        return None
Method resolution order
dataclass ComponentInteraction
That's this class!
dataclass MessageResponseMixin

Mixin' class for all interaction types which can be responded to with a message …

dataclass PartialInteraction

The base model for all interaction models …

abstract class Unique

Mixin for a class that enforces uniqueness by a snowflake ID.

abstract class ExecutableWebhook

An abstract class with logic for executing entities as webhooks.

extern class abc.ABC

Helper class that provides a standard way to create an ABC using inheritance.

extern class Generic

Abstract base class for generic types …

Variables and properties
property apptraits.RESTAware

The client application that models may use for procedures.

property app_permissionsOptional[permissions.Permissions]

Permissions the bot has in this interaction's channel if it's in a guild.

property application_idsnowflakes.Snowflake

ID of the application this interaction belongs to.

property channel_idsnowflakes.Snowflake

ID of the channel this interaction was triggered in.

property component_typeUnion[messages.ComponentType, int]

The type of component which triggers this interaction.

Note

This will never be ButtonStyle.LINK as link buttons don't trigger interactions.

property created_atdatetime.datetime

When the object was created.

property custom_idstr

Developer defined ID of the component which triggered this interaction.

property guild_idOptional[snowflakes.Snowflake]

ID of the guild this interaction was triggered in.

This will be None for component interactions triggered in DMs.

property guild_localeOptional[Union[str, locales.Locale]]

The preferred language of the guild this component interaction was triggered in.

This will be None for component interactions triggered in DMs.

Note

This value can usually only be changed if COMMUNITY is in features for the guild and will otherwise default to en-US.

property idsnowflakes.Snowflake

Return the ID of this entity.

Returns

Snowflake
The snowflake ID of this object.
property localeUnion[str, locales.Locale]

The selected language of the user who triggered this component interaction.

property memberOptional[base_interactions.InteractionMember]

The member who triggered this interaction.

This will be None for interactions triggered in DMs.

Note

This member object comes with the extra field permissions which contains the member's permissions in the current channel.

property messagemessages.Message

Object of the message the components for this interaction are attached to.

property tokenstr

The interaction's token.

property typeUnion[InteractionType, int]

The type of interaction this is.

property userusers.User

The user who triggered this interaction.

property valuesSequence[str]

Sequence of the values which were selected for a select menu component.

property versionint

Version of the interaction system this interaction is under.

property webhook_idSnowflake

ID used to execute this entity as a webhook.

Returns

Snowflake
The ID used to execute this entity as a webhook.
Methods
def build_deferred_response(
    type_: _DeferredTypesT,
    /,
) -> special_endpoints.InteractionDeferredBuilder: ...

Get a deferred message response builder for use in the REST server flow.

Note

For interactions received over the gateway create_initial_response should be used to set the interaction response message.

Note

Unlike InteractionMessageBuilder, the result of this call can be returned as is without any modifications being made to it.

Parameters

type_ : Union[int, ResponseType]

The type of deferred response this should be.

This may be one of the following:

Returns

InteractionDeferredBuilder
Deferred interaction message response builder object.
Expand source code
Browse git
def build_deferred_response(self, type_: _DeferredTypesT, /) -> special_endpoints.InteractionDeferredBuilder:
    """Get a deferred message response builder for use in the REST server flow.

    !!! note
        For interactions received over the gateway
        `ComponentInteraction.create_initial_response` should be used to set
        the interaction response message.

    !!! note
        Unlike `hikari.api.special_endpoints.InteractionMessageBuilder`,
        the result of this call can be returned as is without any modifications
        being made to it.

    Parameters
    ----------
    type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
        The type of deferred response this should be.

        This may be one of the following:

        * `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_CREATE`
        * `hikari.interactions.base_interactions.ResponseType.DEFERRED_MESSAGE_UPDATE`

    Returns
    -------
    hikari.api.special_endpoints.InteractionDeferredBuilder
        Deferred interaction message response builder object.
    """
    if type_ not in _DEFERRED_TYPES:
        raise ValueError("Invalid type passed for a deferred response")

    return self.app.rest.interaction_deferred_builder(type_)
def build_response(
    type_: _ImmediateTypesT,
    /,
) -> special_endpoints.InteractionMessageBuilder: ...

Get a message response builder for use in the REST server flow.

Note

For interactions received over the gateway create_initial_response should be used to set the interaction response message.

Parameters

type_ : Union[int, ResponseType]

The type of immediate response this should be.

This may be one of the following:

Examples

async def handle_component_interaction(interaction: ComponentInteraction) -> InteractionMessageBuilder:
    return (
        interaction
        .build_response(ResponseType.MESSAGE_UPDATE)
        .add_embed(Embed(description="Hi there"))
        .set_content("Konnichiwa")
    )

Returns

InteractionMessageBuilder
Interaction message response builder object.
Expand source code
Browse git
def build_response(self, type_: _ImmediateTypesT, /) -> special_endpoints.InteractionMessageBuilder:
    """Get a message response builder for use in the REST server flow.

    !!! note
        For interactions received over the gateway
        `ComponentInteraction.create_initial_response` should be used to set
        the interaction response message.

    Parameters
    ----------
    type_ : typing.Union[builtins.int, hikari.interactions.base_interactions.ResponseType]
        The type of immediate response this should be.

        This may be one of the following:

        * `hikari.interactions.base_interactions.ResponseType.MESSAGE_CREATE`
        * `hikari.interactions.base_interactions.ResponseType.MESSAGE_UPDATE`

    Examples
    --------
    ```py
    async def handle_component_interaction(interaction: ComponentInteraction) -> InteractionMessageBuilder:
        return (
            interaction
            .build_response(ResponseType.MESSAGE_UPDATE)
            .add_embed(Embed(description="Hi there"))
            .set_content("Konnichiwa")
        )
    ```

    Returns
    -------
    hikari.api.special_endpoints.InteractionMessageBuilder
        Interaction message response builder object.
    """
    if type_ not in _IMMEDIATE_TYPES:
        raise ValueError("Invalid type passed for an immediate response")

    return self.app.rest.interaction_message_builder(type_)
async def create_initial_response(
    response_type: _CommandResponseTypesT,
    content: undefined.UndefinedOr[Any] = UNDEFINED,
    *,
    flags: Union[intmessages.MessageFlag, undefined.UndefinedType] = UNDEFINED,
    tts: undefined.UndefinedOr[bool] = UNDEFINED,
    attachment: undefined.UndefinedOr[files.Resourceish] = UNDEFINED,
    attachments: undefined.UndefinedOr[Sequence[files.Resourceish]] = UNDEFINED,
    component: undefined.UndefinedOr[special_endpoints.ComponentBuilder] = UNDEFINED,
    components: undefined.UndefinedOr[Sequence[special_endpoints.ComponentBuilder]] = UNDEFINED,
    embed: undefined.UndefinedOr[embeds_.Embed] = UNDEFINED,
    embeds: undefined.UndefinedOr[Sequence[embeds_.Embed]] = UNDEFINED,
    replace_attachments: bool = False,
    mentions_everyone: undefined.UndefinedOr[bool] = UNDEFINED,
    user_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[users.PartialUser], bool]] = UNDEFINED,
    role_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[guilds.PartialRole], bool]] = UNDEFINED,
) -> None: ...

Inherited from: MessageResponseMixin.create_initial_response

Create the initial response for this interaction.

Warning

Calling this on an interaction which already has an initial response will result in this raising a NotFoundError. This includes if the REST interaction server has already responded to the request.

Parameters

response_type : Union[int, CommandResponseTypesT]
The type of interaction response this is.

Other Parameters

content : UndefinedOr[Any]

If provided, the message contents. If UNDEFINED, then nothing will be sent in the content. Any other value here will be cast to a str.

If this is a Embed and no embed nor embeds kwarg is provided, then this will instead update the embed. This allows for simpler syntax when sending an embed alone.

attachment : UndefinedOr[Resourceish],
If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.
attachments : UndefinedOr[Sequence[Resourceish]],
If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.
component : UndefinedOr[ComponentBuilder]
If provided, builder object of the component to include in this message.
components : UndefinedOr[Sequence[ComponentBuilder]]
If provided, a sequence of the component builder objects to include in this message.
embed : UndefinedOr[Embed]
If provided, the message embed.
embeds : UndefinedOr[Sequence[Embed]]
If provided, the message embeds.
replace_attachments : bool

Whether to replace the attachments with the provided ones. Defaults to False. This only effects component interactions.

Note this will also overwrite the embed attachments.

flags : Union[int, MessageFlag, UndefinedType]

If provided, the message flags this response should have.

As of writing the only message flag which can be set here is EPHEMERAL.

tts : UndefinedOr[bool]
If provided, whether the message will be read out by a screen reader using Discord's TTS (text-to-speech) system.
mentions_everyone : UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here mentions.
user_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialUser], bool]]
If provided, and True, all user mentions will be detected. If provided, and False, all user mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialUser derivatives to enforce mentioning specific users.
role_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialRole], bool]]
If provided, and True, all role mentions will be detected. If provided, and False, all role mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialRole derivatives to enforce mentioning specific roles.

Raises

ValueError
If more than 100 unique objects/entities are passed for role_mentions or user_mentions.
TypeError
If both embed and embeds are specified.
BadRequestError
This may be raised in several discrete situations, such as messages being empty with no embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; invalid image URLs in embeds.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the interaction is not found or if the interaction's initial response has already been created.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def delete_initial_response() -> None: ...

Inherited from: MessageResponseMixin.delete_initial_response

Delete the initial response of this interaction.

Raises

UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the interaction or response is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def delete_message(
    message: snowflakes.SnowflakeishOr[messages_.Message],
) -> None: ...

Inherited from: MessageResponseMixin.delete_message

Delete a given message in a given channel.

Parameters

message : SnowflakeishOr[PartialMessage]
The message to delete. This may be the object or the ID of an existing message.

Raises

ValueError
If token is not available.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the webhook or the message are not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def edit_initial_response(
    content: undefined.UndefinedNoneOr[Any] = UNDEFINED,
    *,
    attachment: undefined.UndefinedOr[files.Resourceish] = UNDEFINED,
    attachments: undefined.UndefinedOr[Sequence[files.Resourceish]] = UNDEFINED,
    component: undefined.UndefinedNoneOr[special_endpoints.ComponentBuilder] = UNDEFINED,
    components: undefined.UndefinedNoneOr[Sequence[special_endpoints.ComponentBuilder]] = UNDEFINED,
    embed: undefined.UndefinedNoneOr[embeds_.Embed] = UNDEFINED,
    embeds: undefined.UndefinedNoneOr[Sequence[embeds_.Embed]] = UNDEFINED,
    replace_attachments: bool = False,
    mentions_everyone: undefined.UndefinedOr[bool] = UNDEFINED,
    user_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[users.PartialUser], bool]] = UNDEFINED,
    role_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[guilds.PartialRole], bool]] = UNDEFINED,
) -> messages.Message: ...

Inherited from: MessageResponseMixin.edit_initial_response

Edit the initial response of this command interaction.

Other Parameters

content : UndefinedNoneOr[Any]

If provided, the message contents. If UNDEFINED, then nothing will be sent in the content. Any other value here will be cast to a str.

If this is a Embed and neither the embed or embeds kwargs are provided or if this is a Resourceish and neither the attachment or attachments kwargs are provided, the values will be overwritten. This allows for simpler syntax when sending an embed or an attachment alone.

Likewise, if this is a Resource, then the content is instead treated as an attachment if no attachment and no attachments kwargs are provided.

attachment : UndefinedOr[Resourceish]
If provided, the attachment to set on the message. If UNDEFINED, the previous attachment, if present, is not changed. If this is None, then the attachment is removed, if present. Otherwise, the new attachment that was provided will be attached.
attachments : UndefinedOr[Sequence[Resourceish]]
If provided, the attachments to set on the message. If UNDEFINED, the previous attachments, if present, are not changed. If this is None, then the attachments is removed, if present. Otherwise, the new attachments that were provided will be attached.
component : UndefinedNoneOr[ComponentBuilder]
If provided, builder object of the component to set for this message. This component will replace any previously set components and passing None will remove all components.
components : UndefinedNoneOr[Sequence[ComponentBuilder]]
If provided, a sequence of the component builder objects set for this message. These components will replace any previously set components and passing None or an empty sequence will remove all components.
embed : UndefinedNoneOr[Embed]
If provided, the embed to set on the message. If UNDEFINED, the previous embed(s) are not changed. If this is None then any present embeds are removed. Otherwise, the new embed that was provided will be used as the replacement.
embeds : UndefinedNoneOr[Sequence[Embed]]
If provided, the embeds to set on the message. If UNDEFINED, the previous embed(s) are not changed. If this is None then any present embeds are removed. Otherwise, the new embeds that were provided will be used as the replacement.
replace_attachments : bool

Whether to replace the attachments with the provided ones. Defaults to False.

Note this will also overwrite the embed attachments.

mentions_everyone : UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here mentions.
user_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialUser], bool]]
If provided, and True, all user mentions will be detected. If provided, and False, all user mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialUser derivatives to enforce mentioning specific users.
role_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialRole], bool]]
If provided, and True, all role mentions will be detected. If provided, and False, all role mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialRole derivatives to enforce mentioning specific roles.

Note

Mentioning everyone, roles, or users in message edits currently will not send a push notification showing a new mention to people on Discord. It will still highlight in their chat as if they were mentioned, however.

Warning

If you specify one of mentions_everyone, user_mentions, or role_mentions, then all others will default to False, even if they were enabled previously.

This is a limitation of Discord's design. If in doubt, specify all three of them each time.

Returns

Message
The edited message.

Raises

ValueError
If more than 100 unique objects/entities are passed for role_mentions or user_mentions.
TypeError
If both embed and embeds are specified.
BadRequestError
This may be raised in several discrete situations, such as messages being empty with no attachments or embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; too many attachments; attachments that are too large; invalid image URLs in embeds; too many components.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the interaction or the message are not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def edit_message(
    message: snowflakes.SnowflakeishOr[messages_.Message],
    content: undefined.UndefinedNoneOr[Any] = UNDEFINED,
    *,
    attachment: undefined.UndefinedOr[files.Resourceish] = UNDEFINED,
    attachments: undefined.UndefinedOr[Sequence[files.Resourceish]] = UNDEFINED,
    component: undefined.UndefinedNoneOr[special_endpoints.ComponentBuilder] = UNDEFINED,
    components: undefined.UndefinedNoneOr[Sequence[special_endpoints.ComponentBuilder]] = UNDEFINED,
    embed: undefined.UndefinedNoneOr[embeds_.Embed] = UNDEFINED,
    embeds: undefined.UndefinedNoneOr[Sequence[embeds_.Embed]] = UNDEFINED,
    replace_attachments: bool = False,
    mentions_everyone: undefined.UndefinedOr[bool] = UNDEFINED,
    user_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[users_.PartialUser], bool]] = UNDEFINED,
    role_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[guilds_.PartialRole], bool]] = UNDEFINED,
) -> messages_.Message: ...

Inherited from: MessageResponseMixin.edit_message

Edit a message sent by a webhook.

Parameters

message : SnowflakeishOr[PartialMessage]
The message to delete. This may be the object or the ID of an existing message.
content : UndefinedNoneOr[Any]

If provided, the message contents. If UNDEFINED, then nothing will be sent in the content. Any other value here will be cast to a str.

If this is a Embed and no embed nor no embeds kwarg is provided, then this will instead update the embed. This allows for simpler syntax when sending an embed alone.

Likewise, if this is a Resource, then the content is instead treated as an attachment if no attachment and no attachments kwargs are provided.

Other Parameters

attachment : UndefinedOr[Resourceish]
If provided, the attachment to set on the message. If UNDEFINED, the previous attachment, if present, is not changed. If this is None, then the attachment is removed, if present. Otherwise, the new attachment that was provided will be attached.
attachments : UndefinedOr[Sequence[Resourceish]]
If provided, the attachments to set on the message. If UNDEFINED, the previous attachments, if present, are not changed. If this is None, then the attachments is removed, if present. Otherwise, the new attachments that were provided will be attached.
component : UndefinedNoneOr[ComponentBuilder]
If provided, builder object of the component to set for this message. This component will replace any previously set components and passing None will remove all components.
components : UndefinedNoneOr[Sequence[ComponentBuilder]]
If provided, a sequence of the component builder objects set for this message. These components will replace any previously set components and passing None or an empty sequence will remove all components.
embed : UndefinedNoneOr[Embed]
If provided, the embed to set on the message. If UNDEFINED, the previous embed(s) are not changed. If this is None then any present embeds are removed. Otherwise, the new embed that was provided will be used as the replacement.
embeds : UndefinedNoneOr[Sequence[Embed]]
If provided, the embeds to set on the message. If UNDEFINED, the previous embed(s) are not changed. If this is None then any present embeds are removed. Otherwise, the new embeds that were provided will be used as the replacement.
replace_attachments : bool

Whether to replace the attachments with the provided ones. Defaults to False.

Note this will also overwrite the embed attachments.

mentions_everyone : UndefinedOr[bool]
If provided, sanitation for @everyone mentions. If UNDEFINED, then the previous setting is not changed. If True, then @everyone/@here mentions in the message content will show up as mentioning everyone that can view the chat.
user_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialUser], bool]]
If provided, and True, all user mentions will be detected. If provided, and False, all user mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialUser derivatives to enforce mentioning specific users.
role_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialRole], bool]]
If provided, and True, all role mentions will be detected. If provided, and False, all role mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialRole derivatives to enforce mentioning specific roles.

Note

Mentioning everyone, roles, or users in message edits currently will not send a push notification showing a new mention to people on Discord. It will still highlight in their chat as if they were mentioned, however.

Warning

If you specify a non-embed content, mentions_everyone, mentions_reply, user_mentions, and role_mentions will default to False as the message will be re-parsed for mentions.

This is a limitation of Discord's design. If in doubt, specify all three of them each time.

Warning

If you specify one of mentions_everyone, mentions_reply, user_mentions, or role_mentions, then all others will default to False, even if they were enabled previously.

This is a limitation of Discord's design. If in doubt, specify all three of them each time.

Returns

Message
The edited message.

Raises

ValueError
If more than 100 unique objects/entities are passed for role_mentions or user_mentions or token is not available.
TypeError
If both attachment and attachments are specified or if both embed and embeds are specified.
BadRequestError
This may be raised in several discrete situations, such as messages being empty with no attachments or embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; too many attachments; attachments that are too large; too many components.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the webhook or the message are not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def execute(
    content: undefined.UndefinedOr[Any] = UNDEFINED,
    *,
    username: undefined.UndefinedOr[str] = UNDEFINED,
    avatar_url: Union[undefined.UndefinedType, str, files.URL] = UNDEFINED,
    tts: undefined.UndefinedOr[bool] = UNDEFINED,
    attachment: undefined.UndefinedOr[files_.Resourceish] = UNDEFINED,
    attachments: undefined.UndefinedOr[Sequence[files_.Resourceish]] = UNDEFINED,
    component: undefined.UndefinedOr[special_endpoints.ComponentBuilder] = UNDEFINED,
    components: undefined.UndefinedOr[Sequence[special_endpoints.ComponentBuilder]] = UNDEFINED,
    embed: undefined.UndefinedOr[embeds_.Embed] = UNDEFINED,
    embeds: undefined.UndefinedOr[Sequence[embeds_.Embed]] = UNDEFINED,
    mentions_everyone: undefined.UndefinedOr[bool] = UNDEFINED,
    user_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[users_.PartialUser], bool]] = UNDEFINED,
    role_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[guilds_.PartialRole], bool]] = UNDEFINED,
    flags: Union[undefined.UndefinedType, int, messages_.MessageFlag] = UNDEFINED,
) -> messages_.Message: ...

Inherited from: MessageResponseMixin.execute

Execute the webhook to create a message.

Parameters

content : UndefinedOr[Any]

If provided, the message contents. If UNDEFINED, then nothing will be sent in the content. Any other value here will be cast to a str.

If this is a Embed and no embed kwarg is provided, then this will instead update the embed. This allows for simpler syntax when sending an embed alone.

Likewise, if this is a Resource, then the content is instead treated as an attachment if no attachment and no attachments kwargs are provided.

Other Parameters

username : UndefinedOr[str]
If provided, the username to override the webhook's username for this request.
avatar_url : Union[UndefinedType, str, URL]
If provided, the url of an image to override the webhook's avatar with for this request.
tts : UndefinedOr[bool]
If provided, whether the message will be sent as a TTS message.
attachment : UndefinedOr[Resourceish]
If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.
attachments : UndefinedOr[Sequence[Resourceish]]
If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.
component : UndefinedOr[ComponentBuilder]
If provided, builder object of the component to include in this message.
components : UndefinedOr[Sequence[ComponentBuilder]]
If provided, a sequence of the component builder objects to include in this message.
embed : UndefinedOr[Embed]
If provided, the message embed.
embeds : UndefinedOr[Sequence[Embed]]
If provided, the message embeds.
mentions_everyone : UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here mentions.
user_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialUser], bool]]
If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of Snowflake, or PartialUser derivatives to enforce mentioning specific users.
role_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialRole], bool]]
If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of Snowflake, or PartialRole derivatives to enforce mentioning specific roles.
flags : Union[UndefinedType, int, MessageFlag]

The flags to set for this webhook message.

Warning

As of writing this can only be set for interaction webhooks and the only settable flag is EPHEMERAL; this field is just ignored for non-interaction webhooks.

Warning

As of writing, username and avatar_url are ignored for interaction webhooks.

Returns

Message
The created message object.

Raises

NotFoundError
If the current webhook is not found.
BadRequestError
This can be raised if the file is too large; if the embed exceeds the defined limits; if the message content is specified only and empty or greater than 2000 characters; if neither content, file or embeds are specified. If any invalid snowflake IDs are passed; a snowflake may be invalid due to it being outside of the range of a 64 bit integer.
UnauthorizedError
If you pass a token that's invalid for the target webhook.
ValueError
If either ExecutableWebhook.token is None or more than 100 unique objects/entities are passed for role_mentions or `user_mentions or if token is not available.
TypeError
If both attachment and attachments are specified.
async def fetch_channel() -> TextableChannel: ...

Fetch the channel this interaction occurred in.

Returns

TextableChannel
The channel. This will be a derivative of TextableChannel.

Raises

UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
ForbiddenError
If you are missing the READ_MESSAGES permission in the channel.
NotFoundError
If the channel is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
Expand source code
Browse git
async def fetch_channel(self) -> channels.TextableChannel:
    """Fetch the channel this interaction occurred in.

    Returns
    -------
    hikari.channels.TextableChannel
        The channel. This will be a _derivative_ of `hikari.channels.TextableChannel`.

    Raises
    ------
    hikari.errors.UnauthorizedError
        If you are unauthorized to make the request (invalid/missing token).
    hikari.errors.ForbiddenError
        If you are missing the `READ_MESSAGES` permission in the channel.
    hikari.errors.NotFoundError
        If the channel is not found.
    hikari.errors.RateLimitTooLongError
        Raised in the event that a rate limit occurs that is
        longer than `max_rate_limit` when making a request.
    hikari.errors.RateLimitTooLongError
        Raised in the event that a rate limit occurs that is
        longer than `max_rate_limit` when making a request.
    hikari.errors.RateLimitedError
        Usually, Hikari will handle and retry on hitting
        rate-limits automatically. This includes most bucket-specific
        rate-limits and global rate-limits. In some rare edge cases,
        however, Discord implements other undocumented rules for
        rate-limiting, such as limits per attribute. These cannot be
        detected or handled normally by Hikari due to their undocumented
        nature, and will trigger this exception if they occur.
    hikari.errors.InternalServerError
        If an internal error occurs on Discord while handling the request.
    """
    channel = await self.app.rest.fetch_channel(self.channel_id)
    assert isinstance(channel, channels.TextableChannel)
    return channel
async def fetch_guild() -> Optional[guilds.RESTGuild]: ...

Fetch the guild this interaction happened in.

Returns

Optional[RESTGuild]
Object of the guild this interaction happened in or None if this occurred within a DM channel.

Raises

ForbiddenError
If you are not part of the guild.
NotFoundError
If the guild is not found.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
Expand source code
Browse git
async def fetch_guild(self) -> typing.Optional[guilds.RESTGuild]:
    """Fetch the guild this interaction happened in.

    Returns
    -------
    typing.Optional[hikari.guilds.RESTGuild]
        Object of the guild this interaction happened in or `builtins.None`
        if this occurred within a DM channel.

    Raises
    ------
    hikari.errors.ForbiddenError
        If you are not part of the guild.
    hikari.errors.NotFoundError
        If the guild is not found.
    hikari.errors.UnauthorizedError
        If you are unauthorized to make the request (invalid/missing token).
    hikari.errors.RateLimitTooLongError
        Raised in the event that a rate limit occurs that is
        longer than `max_rate_limit` when making a request.
    hikari.errors.RateLimitedError
        Usually, Hikari will handle and retry on hitting
        rate-limits automatically. This includes most bucket-specific
        rate-limits and global rate-limits. In some rare edge cases,
        however, Discord implements other undocumented rules for
        rate-limiting, such as limits per attribute. These cannot be
        detected or handled normally by Hikari due to their undocumented
        nature, and will trigger this exception if they occur.
    hikari.errors.InternalServerError
        If an internal error occurs on Discord while handling the request.
    """
    if not self.guild_id:
        return None

    return await self.app.rest.fetch_guild(self.guild_id)
async def fetch_initial_response() -> messages.Message: ...

Inherited from: MessageResponseMixin.fetch_initial_response

Fetch the initial response of this interaction.

Returns

Message
Message object of the initial response.

Raises

ForbiddenError
If you cannot access the target interaction.
NotFoundError
If the initial response isn't found.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def fetch_message(
    message: snowflakes.SnowflakeishOr[messages_.Message],
) -> messages_.Message: ...

Inherited from: MessageResponseMixin.fetch_message

Fetch an old message sent by the webhook.

Parameters

message : SnowflakeishOr[PartialMessage]
The message to fetch. This may be the object or the ID of an existing channel.

Returns

Message
The requested message.

Raises

ValueError
If token is not available.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the webhook is not found or the webhook's message wasn't found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def fetch_parent_message() -> messages.Message: ...

Fetch the message which this interaction was triggered on.

Returns

Message
The requested message.

Raises

ValueError
If token is not available.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the webhook is not found or the webhook's message wasn't found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
Expand source code
Browse git
async def fetch_parent_message(self) -> messages.Message:
    """Fetch the message which this interaction was triggered on.

    Returns
    -------
    hikari.messages.Message
        The requested message.

    Raises
    ------
    builtins.ValueError
        If `token` is not available.
    hikari.errors.UnauthorizedError
        If you are unauthorized to make the request (invalid/missing token).
    hikari.errors.NotFoundError
        If the webhook is not found or the webhook's message wasn't found.
    hikari.errors.RateLimitTooLongError
        Raised in the event that a rate limit occurs that is
        longer than `max_rate_limit` when making a request.
    hikari.errors.RateLimitedError
        Usually, Hikari will handle and retry on hitting
        rate-limits automatically. This includes most bucket-specific
        rate-limits and global rate-limits. In some rare edge cases,
        however, Discord implements other undocumented rules for
        rate-limiting, such as limits per attribute. These cannot be
        detected or handled normally by Hikari due to their undocumented
        nature, and will trigger this exception if they occur.
    hikari.errors.InternalServerError
        If an internal error occurs on Discord while handling the request.
    """
    return await self.fetch_message(self.message.id)
def get_channel() -> Union[GuildTextChannelGuildNewsChannelNone]: ...

Get the guild channel this interaction occurred in.

Note

This will always return None for interactions triggered in a DM channel.

Returns

Union[GuildTextChannel, GuildNewsChannel, None]
The object of the guild channel that was found in the cache or None.
Expand source code
Browse git
def get_channel(self) -> typing.Union[channels.GuildTextChannel, channels.GuildNewsChannel, None]:
    """Get the guild channel this interaction occurred in.

    !!! note
        This will always return `builtins.None` for interactions triggered
        in a DM channel.

    Returns
    -------
    typing.Union[hikari.channels.GuildTextChannel, hikari.channels.GuildNewsChannel, builtins.None]
        The object of the guild channel that was found in the cache or
        `builtins.None`.
    """
    if isinstance(self.app, traits.CacheAware):
        channel = self.app.cache.get_guild_channel(self.channel_id)
        assert isinstance(channel, (channels.GuildTextChannel, channels.GuildNewsChannel))
        return channel

    return None
def get_guild() -> Optional[guilds.GatewayGuild]: ...

Get the object of this interaction's guild guild from the cache.

Returns

Optional[GatewayGuild]
The object of the guild if found, else None.
Expand source code
Browse git
def get_guild(self) -> typing.Optional[guilds.GatewayGuild]:
    """Get the object of this interaction's guild guild from the cache.

    Returns
    -------
    typing.Optional[hikari.guilds.GatewayGuild]
        The object of the guild if found, else `builtins.None`.
    """
    if self.guild_id and isinstance(self.app, traits.CacheAware):
        return self.app.cache.get_guild(self.guild_id)

    return None
def get_parent_message() -> Optional[messages.PartialMessage]: ...

Get the message which this interaction was triggered on from the cache.

Returns

Optional[Message]
The object of the message found in the cache or None.
Expand source code
Browse git
def get_parent_message(self) -> typing.Optional[messages.PartialMessage]:
    """Get the message which this interaction was triggered on from the cache.

    Returns
    -------
    typing.Optional[hikari.messages.Message]
        The object of the message found in the cache or `builtins.None`.
    """
    if isinstance(self.app, traits.CacheAware):
        return self.app.cache.get_message(self.message.id)

    return None