Back to top

hikari.applications

Application and entities related to discord's OAuth2 flow.

View Source
# -*- 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.
"""Application and entities related to discord's OAuth2 flow."""

from __future__ import annotations

__all__: typing.Sequence[str] = (
    "InviteApplication",
    "Application",
    "ApplicationFlags",
    "AuthorizationApplication",
    "AuthorizationInformation",
    "ConnectionVisibility",
    "OAuth2AuthorizationToken",
    "OAuth2ImplicitToken",
    "OAuth2Scope",
    "OwnConnection",
    "OwnGuild",
    "PartialOAuth2Token",
    "Team",
    "TeamMember",
    "TeamMembershipState",
    "TokenType",
    "get_token_id",
)

import base64
import typing

import attr

from hikari import guilds
from hikari import snowflakes
from hikari import urls
from hikari import users
from hikari.internal import attr_extensions
from hikari.internal import enums
from hikari.internal import routes

if typing.TYPE_CHECKING:
    import datetime

    from hikari import colors
    from hikari import files
    from hikari import permissions as permissions_
    from hikari import traits
    from hikari import webhooks


@typing.final
class ApplicationFlags(enums.Flag):
    """The known application flag bits."""

    VERIFIED_FOR_GUILD_PRESENCES = 1 << 12
    """Denotes that a verified application can use the GUILD_PRESENCES intent."""

    GUILD_PRESENCES_INTENT = 1 << 13
    """Denotes that the application has the GUILD_PRESENCES intent enabled in it's dashboard."""

    VERIFIED_FOR_GUILD_MEMBERS_INTENT = 1 << 14
    """Denotes that a verified application can use the GUILD_MEMBERS intent."""

    GUILD_MEMBERS_INTENT = 1 << 15
    """Denotes that the application has the GUILD_MEMBERS intent enabled in it's dashboard."""

    VERIFICATION_PENDING_GUILD_LIMIT = 1 << 16
    """Denotes that the application's verification is pending."""

    EMBEDDED = 1 << 17
    """Denotes that the application has functionality that's specially embedded in Discord's client."""

    MESSAGE_CONTENT_INTENT = 1 << 18
    """Denotes that the application has message content intent enabled in it's dashboard."""

    MESSAGE_CONTENT_INTENT_LIMITED = 1 << 19
    """Denotes that the application has message content access while pending verification."""


@typing.final
class OAuth2Scope(str, enums.Enum):
    """OAuth2 Scopes that Discord allows.

    These are categories of permissions for applications using the OAuth2 API
    directly. Most users will only ever need the `BOT` scope when developing
    bots.
    """

    ACTIVITIES_READ = "activities.read"
    """Enables fetching the "Now Playing/Recently Played" list.

    .. note::
        You must be whitelisted to use this scope.
    """

    ACTIVITIES_WRITE = "activities.write"
    """Enables updating a user's activity.

    .. note::
        You must be whitelisted to use this scope.

    .. note::
        This is not required to use the GameSDK activity manager.
    """

    APPLICATIONS_BUILDS_READ = "applications.builds.read"
    """Enables reading build data for a user's applications.

    .. note::
        You must be whitelisted to use this scope.
    """

    APPLICATIONS_BUILDS_UPLOAD = "applications.builds.upload"
    """Enables uploading/updating builds for a user's applications.

    .. note::
        You must be whitelisted to use this scope.
    """

    APPLICATIONS_COMMANDS = "applications.commands"
    """Allows your application's (slash) commands to be used in a guild.

    This is used in Discord's special Bot Authorization Flow like
    `OAuth2Scope.BOT` in-order to join an application into a guild as an
    application command providing integration.
    """

    APPLICATIONS_COMMANDS_UPDATE = "applications.commands.update"
    """Allows your application to update it's (slash) commands via a bearer token."""

    APPLICATIONS_ENTITLEMENTS = "applications.entitlements"
    """Enables reading entitlements for a user's applications."""

    APPLICATIONS_STORE_UPDATE = "applications.store.update"
    """Enables reading/updating store data for the user's applications.

    This includes store listings, achievements, SKU's, etc.

    .. note::
        The store API is deprecated and may be removed in the future.
    """

    BOT = "bot"
    """Enables adding a bot application to a guild.

    .. note::
        This requires you to have set up a bot account for your application.
    """

    CONNECTIONS = "connections"
    """Enables viewing third-party linked accounts such as Twitch."""

    EMAIL = "email"
    """Enable the application to view the user's email and application info."""

    GROUP_DM_JOIN = "gdm.join"
    """Enables joining users into a group DM.

    .. warning::
        This cannot add the bot to a group DM.
    """

    GUILDS = "guilds"
    """Enables viewing the guilds the user is in."""

    GUILDS_JOIN = "guilds.join"
    """Enables adding the user to a specific guild.

    .. note::
        This requires you to have set up a bot account for your application.
    """

    IDENTIFY = "identify"
    """Enables viewing info about itself.

    .. note::
        This does not include email address info. Use the `EMAIL` scope instead
        to retrieve this information.
    """

    RELATIONSHIPS_READ = "relationships.read"
    """Enables viewing a user's friend list.

    .. note::
        You must be whitelisted to use this scope.
    """

    RPC = "rpc"
    """Enables the RPC application to control the local user's Discord client.

    .. note::
        You must be whitelisted to use this scope.
    """

    RPC_MESSAGES_READ = "messages.read"
    """Enables the RPC application to read messages from all channels the user is in."""

    RPC_NOTIFICATIONS_READ = "rpc.notifications.read"
    """Enables the RPC application to read  from all channels the user is in.

    .. note::
        You must be whitelisted to use this scope.
    """

    WEBHOOK_INCOMING = "webhook.incoming"
    """Used to generate a webhook that is returned in the OAuth2 token response.

    This is used during authorization code grants.
    """

    GUILDS_MEMBERS_READ = "guilds.members.read"
    """Used to read the current user's guild members."""


@typing.final
class ConnectionVisibility(int, enums.Enum):
    """Describes who can see a connection with a third party account."""

    NONE = 0
    """Implies that only you can see the corresponding connection."""

    EVERYONE = 1
    """Everyone can see the connection."""


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OwnConnection:
    """Represents a user's connection with a third party account.

    Returned by the `GET Current User Connections` endpoint.
    """

    id: str = attr.field(hash=True, repr=True)
    """The string ID of the third party connected account.

    .. warning::
        Seeing as this is a third party ID, it will not be a snowflakes.
    """

    name: str = attr.field(eq=False, hash=False, repr=True)
    """The username of the connected account."""

    type: str = attr.field(eq=False, hash=False, repr=True)
    """The type of service this connection is for."""

    is_revoked: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if the connection has been revoked."""

    integrations: typing.Sequence[guilds.PartialIntegration] = attr.field(eq=False, hash=False, repr=False)
    """A sequence of the partial guild integration objects this connection has."""

    is_verified: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if the connection has been verified."""

    is_friend_sync_enabled: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if friends should be added based on this connection."""

    is_activity_visible: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if this connection's activities are shown in the user's presence."""

    visibility: typing.Union[ConnectionVisibility, int] = attr.field(eq=False, hash=False, repr=True)
    """The visibility of the connection."""


@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OwnGuild(guilds.PartialGuild):
    """Represents a user bound partial guild object."""

    features: typing.Sequence[typing.Union[str, guilds.GuildFeature]] = attr.field(eq=False, hash=False, repr=False)
    """A list of the features in this guild."""

    is_owner: bool = attr.field(eq=False, hash=False, repr=True)
    """`True` when the current user owns this guild."""

    my_permissions: permissions_.Permissions = attr.field(eq=False, hash=False, repr=False)
    """The guild-level permissions that apply to the current user or bot."""


@typing.final
class TeamMembershipState(int, enums.Enum):
    """Represents the state of a user's team membership."""

    INVITED = 1
    """Denotes the user has been invited to the team but has yet to accept."""

    ACCEPTED = 2
    """Denotes the user has accepted the invite and is now a member."""


@attr_extensions.with_copy
@attr.define(eq=False, hash=False, kw_only=True, weakref_slot=False)
class TeamMember(users.User):
    """Represents a member of a Team."""

    membership_state: typing.Union[TeamMembershipState, int] = attr.field(repr=False)
    """The state of this user's membership."""

    permissions: typing.Sequence[str] = attr.field(repr=False)
    """This member's permissions within a team.

    At the time of writing, this will always be a sequence of one `str`,
    which will always be `"*"`. This may change in the future, however.
    """

    team_id: snowflakes.Snowflake = attr.field(repr=True)
    """The ID of the team this member belongs to."""

    user: users.User = attr.field(repr=True)
    """The user representation of this team member."""

    @property
    def app(self) -> traits.RESTAware:
        """Return the app that is bound to the user object."""
        return self.user.app

    @property
    def avatar_hash(self) -> typing.Optional[str]:
        return self.user.avatar_hash

    @property
    def avatar_url(self) -> typing.Optional[files.URL]:
        return self.user.avatar_url

    @property
    def default_avatar_url(self) -> files.URL:
        return self.user.default_avatar_url

    @property
    def banner_hash(self) -> typing.Optional[str]:
        return self.user.banner_hash

    @property
    def banner_url(self) -> typing.Optional[files.URL]:
        return self.user.banner_url

    @property
    def accent_color(self) -> typing.Optional[colors.Color]:
        return self.user.accent_color

    @property
    def discriminator(self) -> str:
        return self.user.discriminator

    @property
    def flags(self) -> users.UserFlag:
        return self.user.flags

    @property
    def id(self) -> snowflakes.Snowflake:
        return self.user.id

    @property
    def is_bot(self) -> bool:
        return self.user.is_bot

    @property
    def is_system(self) -> bool:
        return self.user.is_system

    @property
    def mention(self) -> str:
        return self.user.mention

    @property
    def username(self) -> str:
        return self.user.username

    def __str__(self) -> str:
        return str(self.user)

    def __hash__(self) -> int:
        return hash(self.user)

    def __eq__(self, other: object) -> bool:
        return self.user == other


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class Team(snowflakes.Unique):
    """Represents a development team, along with all its members."""

    app: traits.RESTAware = attr.field(
        repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
    )
    """The client application that models may use for procedures."""

    id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
    """The ID of this entity."""

    name: str = attr.field(hash=False, eq=False, repr=True)
    """The name of this team."""

    icon_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The CDN hash of this team's icon.

    If no icon is provided, this will be `None`.
    """

    members: typing.Mapping[snowflakes.Snowflake, TeamMember] = attr.field(eq=False, hash=False, repr=False)
    """A mapping containing each member in this team.

    The mapping maps keys containing the member's ID to values containing the
    member object.
    """

    owner_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
    """The ID of this team's owner."""

    def __str__(self) -> str:
        return f"Team {self.name} ({self.id})"

    @property
    def icon_url(self) -> typing.Optional[files.URL]:
        """Icon URL, or `None` if no icon exists."""
        return self.make_icon_url()

    def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the icon URL for this team if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`. Can be any power
            of two between `16` and `4096` inclusive.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no icon exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.icon_hash is None:
            return None

        return routes.CDN_TEAM_ICON.compile_to_file(
            urls.CDN_URL,
            team_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class InviteApplication(guilds.PartialApplication):
    """Represents the information of an Invite Application."""

    app: traits.RESTAware = attr.field(
        repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
    )
    """The client application that models may use for procedures."""

    cover_image_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The CDN's hash of this application's default rich presence invite cover image."""

    public_key: bytes = attr.field(eq=False, hash=False, repr=False)
    """The key used for verifying interaction and GameSDK payload signatures."""

    @property
    def cover_image_url(self) -> typing.Optional[files.URL]:
        """Rich presence cover image URL for this application, if set."""
        return self.make_cover_image_url()

    def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the rich presence cover image URL for this application, if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no cover image exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.cover_image_hash is None:
            return None

        return routes.CDN_APPLICATION_COVER.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.cover_image_hash,
            size=size,
            file_format=ext,
        )


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class Application(guilds.PartialApplication):
    """Represents the information of an Oauth2 Application."""

    app: traits.RESTAware = attr.field(
        repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
    )
    """The client application that models may use for procedures."""

    is_bot_public: bool = attr.field(eq=False, hash=False, repr=True)
    """`True` if the bot associated with this application is public."""

    is_bot_code_grant_required: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if this application's bot is requiring code grant for invites."""

    owner: users.User = attr.field(eq=False, hash=False, repr=True)
    """The application's owner."""

    rpc_origins: typing.Optional[typing.Sequence[str]] = attr.field(eq=False, hash=False, repr=False)
    """A collection of this application's RPC origin URLs, if RPC is enabled."""

    flags: ApplicationFlags = attr.field(eq=False, hash=False, repr=False)
    """The flags for this application."""

    public_key: bytes = attr.field(eq=False, hash=False, repr=False)
    """The key used for verifying interaction and GameSDK payload signatures."""

    team: typing.Optional[Team] = attr.field(eq=False, hash=False, repr=False)
    """The team this application belongs to.

    If the application is not part of a team, this will be `None`.
    """

    cover_image_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The CDN's hash of this application's default rich presence invite cover image."""

    terms_of_service_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's terms of service."""

    privacy_policy_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's privacy policy."""

    @property
    def cover_image_url(self) -> typing.Optional[files.URL]:
        """Rich presence cover image URL for this application, if set."""
        return self.make_cover_image_url()

    def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the rich presence cover image URL for this application, if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no cover image exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.cover_image_hash is None:
            return None

        return routes.CDN_APPLICATION_COVER.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.cover_image_hash,
            size=size,
            file_format=ext,
        )


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class AuthorizationApplication(guilds.PartialApplication):
    """The application model found attached to `AuthorizationInformation`."""

    public_key: bytes = attr.field(eq=False, hash=False, repr=False)
    """The key used for verifying interaction and GameSDK payload signatures."""

    is_bot_public: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=True)
    """`True` if the bot associated with this application is public.

    Will be `None` if this application doesn't have an associated bot.
    """

    is_bot_code_grant_required: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=False)
    """`True` if this application's bot is requiring code grant for invites.

    Will be `None` if this application doesn't have a bot.
    """

    terms_of_service_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's terms of service."""

    privacy_policy_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's privacy policy."""


@attr_extensions.with_copy
@attr.define(hash=False, kw_only=True, weakref_slot=False)
class AuthorizationInformation:
    """Model for the data returned by Get Current Authorization Information."""

    application: AuthorizationApplication = attr.field(hash=False, repr=True)
    """The current application."""

    expires_at: datetime.datetime = attr.field(hash=False, repr=True)
    """When the access token this data was retrieved with expires."""

    scopes: typing.Sequence[typing.Union[OAuth2Scope, str]] = attr.field(hash=False, repr=True)
    """A sequence of the scopes the current user has authorized the application for."""

    user: typing.Optional[users.User] = attr.field(hash=False, repr=True)
    """The user who has authorized this token if they included the `identify` scope."""


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class PartialOAuth2Token:
    """Model for partial OAuth2 token data returned by the API.

    This will generally only be returned when by the client credentials OAuth2
    flow.
    """

    access_token: str = attr.field(hash=True, repr=False)
    """Access token issued by the authorization server."""

    token_type: typing.Union[TokenType, str] = attr.field(eq=False, hash=False, repr=True)
    """Type of token issued by the authorization server."""

    expires_in: datetime.timedelta = attr.field(eq=False, hash=False, repr=True)
    """Lifetime of this access token."""

    scopes: typing.Sequence[typing.Union[OAuth2Scope, str]] = attr.field(eq=False, hash=False, repr=True)
    """Scopes the access token has access to."""

    def __str__(self) -> str:
        return self.access_token


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OAuth2AuthorizationToken(PartialOAuth2Token):
    """Model for the OAuth2 token data returned by the authorization grant flow."""

    refresh_token: int = attr.field(eq=False, hash=False, repr=False)
    """Refresh token used to obtain new access tokens with the same grant."""

    webhook: typing.Optional[webhooks.IncomingWebhook] = attr.field(eq=False, hash=False, repr=True)
    """Object of the webhook that was created.

    This will only be present if this token was authorized with the
    `webhooks.incoming` scope, otherwise this will be `None`.
    """

    guild: typing.Optional[guilds.RESTGuild] = attr.field(eq=False, hash=False, repr=True)
    """Object of the guild the user was added to.

    This will only be present if this token was authorized with the
    `bot` scope, otherwise this will be `None`.
    """


@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OAuth2ImplicitToken(PartialOAuth2Token):
    """Model for the OAuth2 token data returned by the implicit grant flow."""

    state: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """State parameter that was present in the authorization request if provided."""


@typing.final
class TokenType(str, enums.Enum):
    """Token types used within Hikari clients."""

    BOT = "Bot"
    """Bot token type."""

    BASIC = "Basic"
    """OAuth2 basic token type."""

    BEARER = "Bearer"
    """OAuth2 bearer token type."""


def get_token_id(token: str) -> snowflakes.Snowflake:
    """Try to get the bot ID stored in a token.

    Returns
    -------
    hikari.snowflakes.Snowflake
        The ID that was extracted from the token.

    Raises
    ------
    ValueError
        If the passed token has an unexpected format.
    """
    try:
        segment = token.split(".", 1)[0]
        # I don't trust Discord to always provide the right amount of padding here as they don't
        # with the middle field so just to be safe we will add padding here if necessary to avoid
        # base64.b64decode raising a length or padding error.
        segment += "=" * (len(segment) % 4)
        return snowflakes.Snowflake(base64.b64decode(segment))

    except (TypeError, ValueError, IndexError) as exc:
        raise ValueError("Unexpected token format") from exc
#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class Application(hikari.guilds.PartialApplication):
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class Application(guilds.PartialApplication):
    """Represents the information of an Oauth2 Application."""

    app: traits.RESTAware = attr.field(
        repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
    )
    """The client application that models may use for procedures."""

    is_bot_public: bool = attr.field(eq=False, hash=False, repr=True)
    """`True` if the bot associated with this application is public."""

    is_bot_code_grant_required: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if this application's bot is requiring code grant for invites."""

    owner: users.User = attr.field(eq=False, hash=False, repr=True)
    """The application's owner."""

    rpc_origins: typing.Optional[typing.Sequence[str]] = attr.field(eq=False, hash=False, repr=False)
    """A collection of this application's RPC origin URLs, if RPC is enabled."""

    flags: ApplicationFlags = attr.field(eq=False, hash=False, repr=False)
    """The flags for this application."""

    public_key: bytes = attr.field(eq=False, hash=False, repr=False)
    """The key used for verifying interaction and GameSDK payload signatures."""

    team: typing.Optional[Team] = attr.field(eq=False, hash=False, repr=False)
    """The team this application belongs to.

    If the application is not part of a team, this will be `None`.
    """

    cover_image_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The CDN's hash of this application's default rich presence invite cover image."""

    terms_of_service_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's terms of service."""

    privacy_policy_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's privacy policy."""

    @property
    def cover_image_url(self) -> typing.Optional[files.URL]:
        """Rich presence cover image URL for this application, if set."""
        return self.make_cover_image_url()

    def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the rich presence cover image URL for this application, if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no cover image exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.cover_image_hash is None:
            return None

        return routes.CDN_APPLICATION_COVER.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.cover_image_hash,
            size=size,
            file_format=ext,
        )

Represents the information of an Oauth2 Application.

Variables and properties

The client application that models may use for procedures.

#  cover_image_hash: Optional[str]

The CDN's hash of this application's default rich presence invite cover image.

#  cover_image_url: Optional[hikari.files.URL]

Rich presence cover image URL for this application, if set.

#  created_at: datetime.datetime

When the object was created.

#  description: Optional[str]

The description of this application, if any.

The flags for this application.

#  icon_hash: Optional[str]

The CDN hash of this application's icon, if set.

#  icon_url: Optional[hikari.files.URL]

Team icon URL, if there is one.

The ID of this entity.

#  is_bot_code_grant_required: bool

True if this application's bot is requiring code grant for invites.

#  is_bot_public: bool

True if the bot associated with this application is public.

#  name: str

The name of this application.

The application's owner.

#  privacy_policy_url: Optional[str]

The URL of this application's privacy policy.

#  public_key: bytes

The key used for verifying interaction and GameSDK payload signatures.

#  rpc_origins: Optional[Sequence[str]]

A collection of this application's RPC origin URLs, if RPC is enabled.

The team this application belongs to.

If the application is not part of a team, this will be None.

#  terms_of_service_url: Optional[str]

The URL of this application's terms of service.

Methods
#  def __init__(
   self,
   *,
   id: hikari.snowflakes.Snowflake,
   name: str,
   description: Optional[str],
   icon_hash: Optional[str],
   app: hikari.traits.RESTAware,
   is_bot_public: bool,
   is_bot_code_grant_required: bool,
   owner: hikari.users.User,
   rpc_origins: Optional[Sequence[str]],
   flags: hikari.applications.ApplicationFlags,
   public_key: bytes,
   team: Optional[hikari.applications.Team],
   cover_image_hash: Optional[str],
   terms_of_service_url: Optional[str],
   privacy_policy_url: Optional[str]
):
View Source
def __init__(self, *, id, name, description, icon_hash, app, is_bot_public, is_bot_code_grant_required, owner, rpc_origins, flags, public_key, team, cover_image_hash, terms_of_service_url, privacy_policy_url):
    self.id = id
    self.name = name
    self.description = description
    self.icon_hash = icon_hash
    self.app = app
    self.is_bot_public = is_bot_public
    self.is_bot_code_grant_required = is_bot_code_grant_required
    self.owner = owner
    self.rpc_origins = rpc_origins
    self.flags = flags
    self.public_key = public_key
    self.team = team
    self.cover_image_hash = cover_image_hash
    self.terms_of_service_url = terms_of_service_url
    self.privacy_policy_url = privacy_policy_url

Method generated by attrs for class Application.

#  def make_cover_image_url(
   self,
   *,
   ext: str = 'png',
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the rich presence cover image URL for this application, if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no cover image exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.cover_image_hash is None:
            return None

        return routes.CDN_APPLICATION_COVER.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.cover_image_hash,
            size=size,
            file_format=ext,
        )

Generate the rich presence cover image URL for this application, if set.

Parameters
  • ext (str): The extension to use for this URL, defaults to png. Supports png, jpeg, jpg and webp.
  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
Raises
  • ValueError: If the size is not an integer power of 2 between 16 and 4096 (inclusive).
#  def make_icon_url(
   self,
   *,
   ext: str = 'png',
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the icon URL for this application.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no icon exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.icon_hash is None:
            return None

        return routes.CDN_APPLICATION_ICON.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )

Generate the icon URL for this application.

Parameters
  • ext (str): The extension to use for this URL, defaults to png. Supports png, jpeg, jpg and webp.
  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
Raises
  • ValueError: If the size is not an integer power of 2 between 16 and 4096 (inclusive).
#  
@typing.final
class ApplicationFlags(builtins.int, hikari.internal.enums.Flag):
View Source
@typing.final
class ApplicationFlags(enums.Flag):
    """The known application flag bits."""

    VERIFIED_FOR_GUILD_PRESENCES = 1 << 12
    """Denotes that a verified application can use the GUILD_PRESENCES intent."""

    GUILD_PRESENCES_INTENT = 1 << 13
    """Denotes that the application has the GUILD_PRESENCES intent enabled in it's dashboard."""

    VERIFIED_FOR_GUILD_MEMBERS_INTENT = 1 << 14
    """Denotes that a verified application can use the GUILD_MEMBERS intent."""

    GUILD_MEMBERS_INTENT = 1 << 15
    """Denotes that the application has the GUILD_MEMBERS intent enabled in it's dashboard."""

    VERIFICATION_PENDING_GUILD_LIMIT = 1 << 16
    """Denotes that the application's verification is pending."""

    EMBEDDED = 1 << 17
    """Denotes that the application has functionality that's specially embedded in Discord's client."""

    MESSAGE_CONTENT_INTENT = 1 << 18
    """Denotes that the application has message content intent enabled in it's dashboard."""

    MESSAGE_CONTENT_INTENT_LIMITED = 1 << 19
    """Denotes that the application has message content access while pending verification."""

The known application flag bits.

Variables and properties
#  EMBEDDED

Denotes that the application has functionality that's specially embedded in Discord's client.

#  GUILD_MEMBERS_INTENT

Denotes that the application has the GUILD_MEMBERS intent enabled in it's dashboard.

#  GUILD_PRESENCES_INTENT

Denotes that the application has the GUILD_PRESENCES intent enabled in it's dashboard.

#  MESSAGE_CONTENT_INTENT

Denotes that the application has message content intent enabled in it's dashboard.

#  MESSAGE_CONTENT_INTENT_LIMITED

Denotes that the application has message content access while pending verification.

#  VERIFICATION_PENDING_GUILD_LIMIT

Denotes that the application's verification is pending.

#  VERIFIED_FOR_GUILD_MEMBERS_INTENT

Denotes that a verified application can use the GUILD_MEMBERS intent.

#  VERIFIED_FOR_GUILD_PRESENCES

Denotes that a verified application can use the GUILD_PRESENCES intent.

#  denominator

the denominator of a rational number in lowest terms

#  imag

the imaginary part of a complex number

#  name: str

Return the name of the flag combination as a str.

#  numerator

the numerator of a rational number in lowest terms

#  real

the real part of a complex number

#  value: int

Return the int value of the flag.

Methods
#  def __init__(cls, value: int = 0):
View Source
    def __call__(cls, value: int = 0) -> typing.Any:
        """Cast a value to the flag enum, returning the raw value that was passed if values not found."""
        # We want to handle value invariantly to avoid issues brought in by different behaviours from sub-classed ints
        # and floats. This also ensures that .__int__ only returns an invariant int.
        value = int(value)
        try:
            return cls._value_to_member_map_[value]
        except KeyError:
            # We only need this ability here usually, so overloading operators
            # is an overkill and would add more overhead.

            if value < 0:
                # Convert to a positive value instead.
                return cls.__everything__ - ~value

            temp_members = cls._temp_members_
            # For huge enums, don't ever cache anything. We could consume masses of memory otherwise
            # (e.g. Permissions)
            try:
                # Try to get a cached value.
                return temp_members[value]
            except KeyError:
                # If we can't find the value, just return what got casted in by generating a pseudomember
                # and caching it. We can't use weakref because int is not weak referenceable, annoyingly.
                pseudomember = cls.__new__(cls, value)
                pseudomember._name_ = None
                pseudomember._value_ = value
                temp_members[value] = pseudomember
                if len(temp_members) > _MAX_CACHED_MEMBERS:
                    temp_members.popitem()

                return pseudomember

Cast a value to the flag enum, returning the raw value that was passed if values not found.

#  def all(self: ~_T, *flags: ~_T) -> bool:
View Source
    def all(self: _T, *flags: _T) -> bool:
        """Check if all of the given flags are part of this value.

        Returns
        -------
        bool
            `True` if any of the given flags are part of this value.
            Otherwise, return `False`.
        """
        return all((flag & self) == flag for flag in flags)

Check if all of the given flags are part of this value.

Returns
  • bool: True if any of the given flags are part of this value. Otherwise, return False.
#  def any(self: ~_T, *flags: ~_T) -> bool:
View Source
    def any(self: _T, *flags: _T) -> bool:
        """Check if any of the given flags are part of this value.

        Returns
        -------
        bool
            `True` if any of the given flags are part of this value.
            Otherwise, return `False`.
        """
        return any((flag & self) == flag for flag in flags)

Check if any of the given flags are part of this value.

Returns
  • bool: True if any of the given flags are part of this value. Otherwise, return False.
#  def as_integer_ratio(self, /):

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
#  def bit_length(self, /):

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
#  def conjugate(unknown):

Returns self, the complex conjugate of any int.

#  def difference(self: ~_T, other: Union[~_T, int]) -> ~_T:
View Source
    def difference(self: _T, other: typing.Union[_T, int]) -> _T:
        """Perform a set difference with the other set.

        This will return all flags in this set that are not in the other value.

        Equivalent to using the subtraction `-` operator.
        """
        return self.__class__(self & ~int(other))

Perform a set difference with the other set.

This will return all flags in this set that are not in the other value.

Equivalent to using the subtraction - operator.

#  def from_bytes(type, /, bytes, byteorder, *, signed=False):

Return the integer represented by the given array of bytes.

bytes Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Indicates whether two's complement is used to represent the integer.

#  def intersection(self: ~_T, other: Union[~_T, int]) -> ~_T:
View Source
    def intersection(self: _T, other: typing.Union[_T, int]) -> _T:
        """Return a combination of flags that are set for both given values.

        Equivalent to using the "AND" `&` operator.
        """
        return self.__class__(self._value_ & int(other))

Return a combination of flags that are set for both given values.

Equivalent to using the "AND" & operator.

#  def invert(self: ~_T) -> ~_T:
View Source
    def invert(self: _T) -> _T:
        """Return a set of all flags not in the current set."""
        return self.__class__(self.__class__.__everything__._value_ & ~self._value_)

Return a set of all flags not in the current set.

#  def is_disjoint(self: ~_T, other: Union[~_T, int]) -> bool:
View Source
    def is_disjoint(self: _T, other: typing.Union[_T, int]) -> bool:
        """Return whether two sets have a intersection or not.

        If the two sets have an intersection, then this returns
        `False`. If no common flag values exist between them, then
        this returns `True`.
        """
        return not (self & other)

Return whether two sets have a intersection or not.

If the two sets have an intersection, then this returns False. If no common flag values exist between them, then this returns True.

#  def is_subset(self: ~_T, other: Union[~_T, int]) -> bool:
View Source
    def is_subset(self: _T, other: typing.Union[_T, int]) -> bool:
        """Return whether another set contains this set or not.

        Equivalent to using the "in" operator.
        """
        return (self & other) == other

Return whether another set contains this set or not.

Equivalent to using the "in" operator.

#  def is_superset(self: ~_T, other: Union[~_T, int]) -> bool:
View Source
    def is_superset(self: _T, other: typing.Union[_T, int]) -> bool:
        """Return whether this set contains another set or not."""
        return (self & other) == self

Return whether this set contains another set or not.

#  def isdisjoint(self: ~_T, other: Union[~_T, int]) -> bool:
View Source
    def is_disjoint(self: _T, other: typing.Union[_T, int]) -> bool:
        """Return whether two sets have a intersection or not.

        If the two sets have an intersection, then this returns
        `False`. If no common flag values exist between them, then
        this returns `True`.
        """
        return not (self & other)

Return whether two sets have a intersection or not.

If the two sets have an intersection, then this returns False. If no common flag values exist between them, then this returns True.

#  def issubset(self: ~_T, other: Union[~_T, int]) -> bool:
View Source
    def is_subset(self: _T, other: typing.Union[_T, int]) -> bool:
        """Return whether another set contains this set or not.

        Equivalent to using the "in" operator.
        """
        return (self & other) == other

Return whether another set contains this set or not.

Equivalent to using the "in" operator.

#  def issuperset(self: ~_T, other: Union[~_T, int]) -> bool:
View Source
    def is_superset(self: _T, other: typing.Union[_T, int]) -> bool:
        """Return whether this set contains another set or not."""
        return (self & other) == self

Return whether this set contains another set or not.

#  def none(self: ~_T, *flags: ~_T) -> bool:
View Source
    def none(self: _T, *flags: _T) -> bool:
        """Check if none of the given flags are part of this value.

        .. note::
            This is essentially the opposite of `Flag.any`.

        Returns
        -------
        bool
            `True` if none of the given flags are part of this value.
            Otherwise, return `False`.
        """
        return not self.any(*flags)

Check if none of the given flags are part of this value.

Note: This is essentially the opposite of Flag.any.

Returns
  • bool: True if none of the given flags are part of this value. Otherwise, return False.
#  def split(self: ~_T) -> Sequence[~_T]:
View Source
    def split(self: _T) -> typing.Sequence[_T]:
        """Return a list of all defined atomic values for this flag.

        Any unrecognised bits will be omitted for brevity.

        The result will be a name-sorted `typing.Sequence` of each member
        """
        return sorted(
            (member for member in self.__class__._powers_of_2_to_member_map_.values() if member.value & self),
            # Assumption: powers of 2 already have a cached value.
            key=lambda m: m._name_,
        )

Return a list of all defined atomic values for this flag.

Any unrecognised bits will be omitted for brevity.

The result will be a name-sorted typing.Sequence of each member

#  def symmetric_difference(self: ~_T, other: Union[~_T, int]) -> ~_T:
View Source
    def symmetric_difference(self: _T, other: typing.Union[_T, int]) -> _T:
        """Return a set with the symmetric differences of two flag sets.

        Equivalent to using the "XOR" `^` operator.

        For `a ^ b`, this can be considered the same as `(a - b) | (b - a)`.
        """
        return self.__class__(self._value_ ^ int(other))

Return a set with the symmetric differences of two flag sets.

Equivalent to using the "XOR" ^ operator.

For a ^ b, this can be considered the same as (a - b) | (b - a).

#  def symmetricdifference(self: ~_T, other: Union[~_T, int]) -> ~_T:
View Source
    def symmetric_difference(self: _T, other: typing.Union[_T, int]) -> _T:
        """Return a set with the symmetric differences of two flag sets.

        Equivalent to using the "XOR" `^` operator.

        For `a ^ b`, this can be considered the same as `(a - b) | (b - a)`.
        """
        return self.__class__(self._value_ ^ int(other))

Return a set with the symmetric differences of two flag sets.

Equivalent to using the "XOR" ^ operator.

For a ^ b, this can be considered the same as (a - b) | (b - a).

#  def to_bytes(self, /, length, byteorder, *, signed=False):

Return an array of bytes representing an integer.

length Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

#  def union(self: ~_T, other: Union[~_T, int]) -> ~_T:
View Source
    def union(self: _T, other: typing.Union[_T, int]) -> _T:
        """Return a combination of all flags in this set and the other set.

        Equivalent to using the "OR" `~` operator.
        """
        return self.__class__(self._value_ | int(other))

Return a combination of all flags in this set and the other set.

Equivalent to using the "OR" ~ operator.

#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class AuthorizationApplication(hikari.guilds.PartialApplication):
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class AuthorizationApplication(guilds.PartialApplication):
    """The application model found attached to `AuthorizationInformation`."""

    public_key: bytes = attr.field(eq=False, hash=False, repr=False)
    """The key used for verifying interaction and GameSDK payload signatures."""

    is_bot_public: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=True)
    """`True` if the bot associated with this application is public.

    Will be `None` if this application doesn't have an associated bot.
    """

    is_bot_code_grant_required: typing.Optional[bool] = attr.field(eq=False, hash=False, repr=False)
    """`True` if this application's bot is requiring code grant for invites.

    Will be `None` if this application doesn't have a bot.
    """

    terms_of_service_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's terms of service."""

    privacy_policy_url: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The URL of this application's privacy policy."""

The application model found attached to AuthorizationInformation.

Variables and properties
#  created_at: datetime.datetime

When the object was created.

#  description: Optional[str]

The description of this application, if any.

#  icon_hash: Optional[str]

The CDN hash of this application's icon, if set.

#  icon_url: Optional[hikari.files.URL]

Team icon URL, if there is one.

The ID of this entity.

#  is_bot_code_grant_required: Optional[bool]

True if this application's bot is requiring code grant for invites.

Will be None if this application doesn't have a bot.

#  is_bot_public: Optional[bool]

True if the bot associated with this application is public.

Will be None if this application doesn't have an associated bot.

#  name: str

The name of this application.

#  privacy_policy_url: Optional[str]

The URL of this application's privacy policy.

#  public_key: bytes

The key used for verifying interaction and GameSDK payload signatures.

#  terms_of_service_url: Optional[str]

The URL of this application's terms of service.

Methods
#  def __init__(
   self,
   *,
   id: hikari.snowflakes.Snowflake,
   name: str,
   description: Optional[str],
   icon_hash: Optional[str],
   public_key: bytes,
   is_bot_public: Optional[bool],
   is_bot_code_grant_required: Optional[bool],
   terms_of_service_url: Optional[str],
   privacy_policy_url: Optional[str]
):
View Source
def __init__(self, *, id, name, description, icon_hash, public_key, is_bot_public, is_bot_code_grant_required, terms_of_service_url, privacy_policy_url):
    self.id = id
    self.name = name
    self.description = description
    self.icon_hash = icon_hash
    self.public_key = public_key
    self.is_bot_public = is_bot_public
    self.is_bot_code_grant_required = is_bot_code_grant_required
    self.terms_of_service_url = terms_of_service_url
    self.privacy_policy_url = privacy_policy_url

Method generated by attrs for class AuthorizationApplication.

#  def make_icon_url(
   self,
   *,
   ext: str = 'png',
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the icon URL for this application.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no icon exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.icon_hash is None:
            return None

        return routes.CDN_APPLICATION_ICON.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )

Generate the icon URL for this application.

Parameters
  • ext (str): The extension to use for this URL, defaults to png. Supports png, jpeg, jpg and webp.
  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
Raises
  • ValueError: If the size is not an integer power of 2 between 16 and 4096 (inclusive).
#  
@attr_extensions.with_copy
@attr.define(hash=False, kw_only=True, weakref_slot=False)
class AuthorizationInformation:
View Source
@attr_extensions.with_copy
@attr.define(hash=False, kw_only=True, weakref_slot=False)
class AuthorizationInformation:
    """Model for the data returned by Get Current Authorization Information."""

    application: AuthorizationApplication = attr.field(hash=False, repr=True)
    """The current application."""

    expires_at: datetime.datetime = attr.field(hash=False, repr=True)
    """When the access token this data was retrieved with expires."""

    scopes: typing.Sequence[typing.Union[OAuth2Scope, str]] = attr.field(hash=False, repr=True)
    """A sequence of the scopes the current user has authorized the application for."""

    user: typing.Optional[users.User] = attr.field(hash=False, repr=True)
    """The user who has authorized this token if they included the `identify` scope."""

Model for the data returned by Get Current Authorization Information.

Variables and properties

The current application.

#  expires_at: datetime.datetime

When the access token this data was retrieved with expires.

#  scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]]

A sequence of the scopes the current user has authorized the application for.

#  user: Optional[hikari.users.User]

The user who has authorized this token if they included the identify scope.

Methods
#  def __init__(
   self,
   *,
   application: hikari.applications.AuthorizationApplication,
   expires_at: datetime.datetime,
   scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]],
   user: Optional[hikari.users.User]
):
View Source
def __init__(self, *, application, expires_at, scopes, user):
    self.application = application
    self.expires_at = expires_at
    self.scopes = scopes
    self.user = user

Method generated by attrs for class AuthorizationInformation.

#  
@typing.final
class ConnectionVisibility(builtins.int, hikari.internal.enums.Enum):
View Source
@typing.final
class ConnectionVisibility(int, enums.Enum):
    """Describes who can see a connection with a third party account."""

    NONE = 0
    """Implies that only you can see the corresponding connection."""

    EVERYONE = 1
    """Everyone can see the connection."""

Describes who can see a connection with a third party account.

Variables and properties
#  EVERYONE

Everyone can see the connection.

#  NONE

Implies that only you can see the corresponding connection.

#  denominator

the denominator of a rational number in lowest terms

#  imag

the imaginary part of a complex number

#  name: str

Return the name of the enum member as a str.

#  numerator

the numerator of a rational number in lowest terms

#  real

the real part of a complex number

#  value

Return the value of the enum member.

Methods
#  def __init__(cls, value: Any):
View Source
    def __call__(cls, value: typing.Any) -> typing.Any:
        """Cast a value to the enum, returning the raw value that was passed if value not found."""
        try:
            return cls._value_to_member_map_[value]
        except KeyError:
            # If we can't find the value, just return what got casted in
            return value

Cast a value to the enum, returning the raw value that was passed if value not found.

#  def as_integer_ratio(self, /):

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
#  def bit_length(self, /):

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
#  def conjugate(unknown):

Returns self, the complex conjugate of any int.

#  def from_bytes(type, /, bytes, byteorder, *, signed=False):

Return the integer represented by the given array of bytes.

bytes Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Indicates whether two's complement is used to represent the integer.

#  def to_bytes(self, /, length, byteorder, *, signed=False):

Return an array of bytes representing an integer.

length Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class InviteApplication(hikari.guilds.PartialApplication):
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class InviteApplication(guilds.PartialApplication):
    """Represents the information of an Invite Application."""

    app: traits.RESTAware = attr.field(
        repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
    )
    """The client application that models may use for procedures."""

    cover_image_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The CDN's hash of this application's default rich presence invite cover image."""

    public_key: bytes = attr.field(eq=False, hash=False, repr=False)
    """The key used for verifying interaction and GameSDK payload signatures."""

    @property
    def cover_image_url(self) -> typing.Optional[files.URL]:
        """Rich presence cover image URL for this application, if set."""
        return self.make_cover_image_url()

    def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the rich presence cover image URL for this application, if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no cover image exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.cover_image_hash is None:
            return None

        return routes.CDN_APPLICATION_COVER.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.cover_image_hash,
            size=size,
            file_format=ext,
        )

Represents the information of an Invite Application.

Variables and properties

The client application that models may use for procedures.

#  cover_image_hash: Optional[str]

The CDN's hash of this application's default rich presence invite cover image.

#  cover_image_url: Optional[hikari.files.URL]

Rich presence cover image URL for this application, if set.

#  created_at: datetime.datetime

When the object was created.

#  description: Optional[str]

The description of this application, if any.

#  icon_hash: Optional[str]

The CDN hash of this application's icon, if set.

#  icon_url: Optional[hikari.files.URL]

Team icon URL, if there is one.

The ID of this entity.

#  name: str

The name of this application.

#  public_key: bytes

The key used for verifying interaction and GameSDK payload signatures.

Methods
#  def __init__(
   self,
   *,
   id: hikari.snowflakes.Snowflake,
   name: str,
   description: Optional[str],
   icon_hash: Optional[str],
   app: hikari.traits.RESTAware,
   cover_image_hash: Optional[str],
   public_key: bytes
):
View Source
def __init__(self, *, id, name, description, icon_hash, app, cover_image_hash, public_key):
    self.id = id
    self.name = name
    self.description = description
    self.icon_hash = icon_hash
    self.app = app
    self.cover_image_hash = cover_image_hash
    self.public_key = public_key

Method generated by attrs for class InviteApplication.

#  def make_cover_image_url(
   self,
   *,
   ext: str = 'png',
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_cover_image_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the rich presence cover image URL for this application, if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no cover image exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.cover_image_hash is None:
            return None

        return routes.CDN_APPLICATION_COVER.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.cover_image_hash,
            size=size,
            file_format=ext,
        )

Generate the rich presence cover image URL for this application, if set.

Parameters
  • ext (str): The extension to use for this URL, defaults to png. Supports png, jpeg, jpg and webp.
  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
Raises
  • ValueError: If the size is not an integer power of 2 between 16 and 4096 (inclusive).
#  def make_icon_url(
   self,
   *,
   ext: str = 'png',
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the icon URL for this application.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no icon exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.icon_hash is None:
            return None

        return routes.CDN_APPLICATION_ICON.compile_to_file(
            urls.CDN_URL,
            application_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )

Generate the icon URL for this application.

Parameters
  • ext (str): The extension to use for this URL, defaults to png. Supports png, jpeg, jpg and webp.
  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
Raises
  • ValueError: If the size is not an integer power of 2 between 16 and 4096 (inclusive).
#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OAuth2AuthorizationToken(PartialOAuth2Token):
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OAuth2AuthorizationToken(PartialOAuth2Token):
    """Model for the OAuth2 token data returned by the authorization grant flow."""

    refresh_token: int = attr.field(eq=False, hash=False, repr=False)
    """Refresh token used to obtain new access tokens with the same grant."""

    webhook: typing.Optional[webhooks.IncomingWebhook] = attr.field(eq=False, hash=False, repr=True)
    """Object of the webhook that was created.

    This will only be present if this token was authorized with the
    `webhooks.incoming` scope, otherwise this will be `None`.
    """

    guild: typing.Optional[guilds.RESTGuild] = attr.field(eq=False, hash=False, repr=True)
    """Object of the guild the user was added to.

    This will only be present if this token was authorized with the
    `bot` scope, otherwise this will be `None`.
    """

Model for the OAuth2 token data returned by the authorization grant flow.

Variables and properties
#  access_token: str

Access token issued by the authorization server.

#  expires_in: datetime.timedelta

Lifetime of this access token.

Object of the guild the user was added to.

This will only be present if this token was authorized with the bot scope, otherwise this will be None.

#  refresh_token: int

Refresh token used to obtain new access tokens with the same grant.

#  scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]]

Scopes the access token has access to.

#  token_type: Union[hikari.applications.TokenType, str]

Type of token issued by the authorization server.

Object of the webhook that was created.

This will only be present if this token was authorized with the webhooks.incoming scope, otherwise this will be None.

Methods
#  def __init__(
   self,
   *,
   access_token: str,
   token_type: Union[hikari.applications.TokenType, str],
   expires_in: datetime.timedelta,
   scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]],
   refresh_token: int,
   webhook: Optional[hikari.webhooks.IncomingWebhook],
   guild: Optional[hikari.guilds.RESTGuild]
):
View Source
def __init__(self, *, access_token, token_type, expires_in, scopes, refresh_token, webhook, guild):
    self.access_token = access_token
    self.token_type = token_type
    self.expires_in = expires_in
    self.scopes = scopes
    self.refresh_token = refresh_token
    self.webhook = webhook
    self.guild = guild

Method generated by attrs for class OAuth2AuthorizationToken.

#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OAuth2ImplicitToken(PartialOAuth2Token):
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OAuth2ImplicitToken(PartialOAuth2Token):
    """Model for the OAuth2 token data returned by the implicit grant flow."""

    state: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """State parameter that was present in the authorization request if provided."""

Model for the OAuth2 token data returned by the implicit grant flow.

Variables and properties
#  access_token: str

Access token issued by the authorization server.

#  expires_in: datetime.timedelta

Lifetime of this access token.

#  scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]]

Scopes the access token has access to.

#  state: Optional[str]

State parameter that was present in the authorization request if provided.

#  token_type: Union[hikari.applications.TokenType, str]

Type of token issued by the authorization server.

Methods
#  def __init__(
   self,
   *,
   access_token: str,
   token_type: Union[hikari.applications.TokenType, str],
   expires_in: datetime.timedelta,
   scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]],
   state: Optional[str]
):
View Source
def __init__(self, *, access_token, token_type, expires_in, scopes, state):
    self.access_token = access_token
    self.token_type = token_type
    self.expires_in = expires_in
    self.scopes = scopes
    self.state = state

Method generated by attrs for class OAuth2ImplicitToken.

#  
@typing.final
class OAuth2Scope(builtins.str, hikari.internal.enums.Enum):
View Source
@typing.final
class OAuth2Scope(str, enums.Enum):
    """OAuth2 Scopes that Discord allows.

    These are categories of permissions for applications using the OAuth2 API
    directly. Most users will only ever need the `BOT` scope when developing
    bots.
    """

    ACTIVITIES_READ = "activities.read"
    """Enables fetching the "Now Playing/Recently Played" list.

    .. note::
        You must be whitelisted to use this scope.
    """

    ACTIVITIES_WRITE = "activities.write"
    """Enables updating a user's activity.

    .. note::
        You must be whitelisted to use this scope.

    .. note::
        This is not required to use the GameSDK activity manager.
    """

    APPLICATIONS_BUILDS_READ = "applications.builds.read"
    """Enables reading build data for a user's applications.

    .. note::
        You must be whitelisted to use this scope.
    """

    APPLICATIONS_BUILDS_UPLOAD = "applications.builds.upload"
    """Enables uploading/updating builds for a user's applications.

    .. note::
        You must be whitelisted to use this scope.
    """

    APPLICATIONS_COMMANDS = "applications.commands"
    """Allows your application's (slash) commands to be used in a guild.

    This is used in Discord's special Bot Authorization Flow like
    `OAuth2Scope.BOT` in-order to join an application into a guild as an
    application command providing integration.
    """

    APPLICATIONS_COMMANDS_UPDATE = "applications.commands.update"
    """Allows your application to update it's (slash) commands via a bearer token."""

    APPLICATIONS_ENTITLEMENTS = "applications.entitlements"
    """Enables reading entitlements for a user's applications."""

    APPLICATIONS_STORE_UPDATE = "applications.store.update"
    """Enables reading/updating store data for the user's applications.

    This includes store listings, achievements, SKU's, etc.

    .. note::
        The store API is deprecated and may be removed in the future.
    """

    BOT = "bot"
    """Enables adding a bot application to a guild.

    .. note::
        This requires you to have set up a bot account for your application.
    """

    CONNECTIONS = "connections"
    """Enables viewing third-party linked accounts such as Twitch."""

    EMAIL = "email"
    """Enable the application to view the user's email and application info."""

    GROUP_DM_JOIN = "gdm.join"
    """Enables joining users into a group DM.

    .. warning::
        This cannot add the bot to a group DM.
    """

    GUILDS = "guilds"
    """Enables viewing the guilds the user is in."""

    GUILDS_JOIN = "guilds.join"
    """Enables adding the user to a specific guild.

    .. note::
        This requires you to have set up a bot account for your application.
    """

    IDENTIFY = "identify"
    """Enables viewing info about itself.

    .. note::
        This does not include email address info. Use the `EMAIL` scope instead
        to retrieve this information.
    """

    RELATIONSHIPS_READ = "relationships.read"
    """Enables viewing a user's friend list.

    .. note::
        You must be whitelisted to use this scope.
    """

    RPC = "rpc"
    """Enables the RPC application to control the local user's Discord client.

    .. note::
        You must be whitelisted to use this scope.
    """

    RPC_MESSAGES_READ = "messages.read"
    """Enables the RPC application to read messages from all channels the user is in."""

    RPC_NOTIFICATIONS_READ = "rpc.notifications.read"
    """Enables the RPC application to read  from all channels the user is in.

    .. note::
        You must be whitelisted to use this scope.
    """

    WEBHOOK_INCOMING = "webhook.incoming"
    """Used to generate a webhook that is returned in the OAuth2 token response.

    This is used during authorization code grants.
    """

    GUILDS_MEMBERS_READ = "guilds.members.read"
    """Used to read the current user's guild members."""

OAuth2 Scopes that Discord allows.

These are categories of permissions for applications using the OAuth2 API directly. Most users will only ever need the BOT scope when developing bots.

Variables and properties
#  ACTIVITIES_READ

Enables fetching the "Now Playing/Recently Played" list.

Note: You must be whitelisted to use this scope.

#  ACTIVITIES_WRITE

Enables updating a user's activity.

Note: You must be whitelisted to use this scope.

Note: This is not required to use the GameSDK activity manager.

#  APPLICATIONS_BUILDS_READ

Enables reading build data for a user's applications.

Note: You must be whitelisted to use this scope.

#  APPLICATIONS_BUILDS_UPLOAD

Enables uploading/updating builds for a user's applications.

Note: You must be whitelisted to use this scope.

#  APPLICATIONS_COMMANDS

Allows your application's (slash) commands to be used in a guild.

This is used in Discord's special Bot Authorization Flow like OAuth2Scope.BOT in-order to join an application into a guild as an application command providing integration.

#  APPLICATIONS_COMMANDS_UPDATE

Allows your application to update it's (slash) commands via a bearer token.

#  APPLICATIONS_ENTITLEMENTS

Enables reading entitlements for a user's applications.

#  APPLICATIONS_STORE_UPDATE

Enables reading/updating store data for the user's applications.

This includes store listings, achievements, SKU's, etc.

Note: The store API is deprecated and may be removed in the future.

Enables adding a bot application to a guild.

Note: This requires you to have set up a bot account for your application.

#  CONNECTIONS

Enables viewing third-party linked accounts such as Twitch.

#  EMAIL

Enable the application to view the user's email and application info.

#  GROUP_DM_JOIN

Enables joining users into a group DM.

Warning: This cannot add the bot to a group DM.

#  GUILDS

Enables viewing the guilds the user is in.

#  GUILDS_JOIN

Enables adding the user to a specific guild.

Note: This requires you to have set up a bot account for your application.

#  GUILDS_MEMBERS_READ

Used to read the current user's guild members.

#  IDENTIFY

Enables viewing info about itself.

Note: This does not include email address info. Use the EMAIL scope instead to retrieve this information.

#  RELATIONSHIPS_READ

Enables viewing a user's friend list.

Note: You must be whitelisted to use this scope.

Enables the RPC application to control the local user's Discord client.

Note: You must be whitelisted to use this scope.

#  RPC_MESSAGES_READ

Enables the RPC application to read messages from all channels the user is in.

#  RPC_NOTIFICATIONS_READ

Enables the RPC application to read from all channels the user is in.

Note: You must be whitelisted to use this scope.

#  WEBHOOK_INCOMING

Used to generate a webhook that is returned in the OAuth2 token response.

This is used during authorization code grants.

#  name: str

Return the name of the enum member as a str.

#  value

Return the value of the enum member.

Methods
#  def __init__(cls, value: Any):
View Source
    def __call__(cls, value: typing.Any) -> typing.Any:
        """Cast a value to the enum, returning the raw value that was passed if value not found."""
        try:
            return cls._value_to_member_map_[value]
        except KeyError:
            # If we can't find the value, just return what got casted in
            return value

Cast a value to the enum, returning the raw value that was passed if value not found.

#  def capitalize(self, /):

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

#  def casefold(self, /):

Return a version of the string suitable for caseless comparisons.

#  def center(self, width, fillchar=' ', /):

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

#  def count(unknown):

S.count(sub[, start[, end]]) -> int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

#  def encode(self, /, encoding='utf-8', errors='strict'):

Encode the string using the codec registered for encoding.

encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

#  def endswith(unknown):

S.endswith(suffix[, start[, end]]) -> bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

#  def expandtabs(self, /, tabsize=8):

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

#  def find(unknown):

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

#  def format(unknown):

S.format(args, *kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').

#  def format_map(unknown):

S.format_map(mapping) -> str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').

#  def index(unknown):

S.index(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

#  def isalnum(self, /):

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

#  def isalpha(self, /):

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

#  def isascii(self, /):

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

#  def isdecimal(self, /):

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

#  def isdigit(self, /):

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

#  def isidentifier(self, /):

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as "def" or "class".

#  def islower(self, /):

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

#  def isnumeric(self, /):

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

#  def isprintable(self, /):

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

#  def isspace(self, /):

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

#  def istitle(self, /):

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

#  def isupper(self, /):

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

#  def join(self, iterable, /):

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

#  def ljust(self, width, fillchar=' ', /):

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

#  def lower(self, /):

Return a copy of the string converted to lowercase.

#  def lstrip(self, chars=None, /):

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

#  def maketrans(unknown):

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

#  def partition(self, sep, /):

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

#  def removeprefix(self, prefix, /):

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

#  def removesuffix(self, suffix, /):

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

#  def replace(self, old, new, count=-1, /):

Return a copy with all occurrences of substring old replaced by new.

count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

#  def rfind(unknown):

S.rfind(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

#  def rindex(unknown):

S.rindex(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

#  def rjust(self, width, fillchar=' ', /):

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

#  def rpartition(self, sep, /):

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

#  def rsplit(self, /, sep=None, maxsplit=-1):

Return a list of the words in the string, using sep as the delimiter string.

sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

Splits are done starting at the end of the string and working to the front.

#  def rstrip(self, chars=None, /):

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

#  def split(self, /, sep=None, maxsplit=-1):

Return a list of the words in the string, using sep as the delimiter string.

sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

#  def splitlines(self, /, keepends=False):

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

#  def startswith(unknown):

S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

#  def strip(self, chars=None, /):

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

#  def swapcase(self, /):

Convert uppercase characters to lowercase and lowercase characters to uppercase.

#  def title(self, /):

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

#  def translate(self, table, /):

Replace each character in the string using the given translation table.

table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

#  def upper(self, /):

Return a copy of the string converted to uppercase.

#  def zfill(self, width, /):

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OwnConnection:
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OwnConnection:
    """Represents a user's connection with a third party account.

    Returned by the `GET Current User Connections` endpoint.
    """

    id: str = attr.field(hash=True, repr=True)
    """The string ID of the third party connected account.

    .. warning::
        Seeing as this is a third party ID, it will not be a snowflakes.
    """

    name: str = attr.field(eq=False, hash=False, repr=True)
    """The username of the connected account."""

    type: str = attr.field(eq=False, hash=False, repr=True)
    """The type of service this connection is for."""

    is_revoked: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if the connection has been revoked."""

    integrations: typing.Sequence[guilds.PartialIntegration] = attr.field(eq=False, hash=False, repr=False)
    """A sequence of the partial guild integration objects this connection has."""

    is_verified: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if the connection has been verified."""

    is_friend_sync_enabled: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if friends should be added based on this connection."""

    is_activity_visible: bool = attr.field(eq=False, hash=False, repr=False)
    """`True` if this connection's activities are shown in the user's presence."""

    visibility: typing.Union[ConnectionVisibility, int] = attr.field(eq=False, hash=False, repr=True)
    """The visibility of the connection."""

Represents a user's connection with a third party account.

Returned by the GET Current User Connections endpoint.

Variables and properties
#  id: str

The string ID of the third party connected account.

Warning: Seeing as this is a third party ID, it will not be a snowflakes.

A sequence of the partial guild integration objects this connection has.

#  is_activity_visible: bool

True if this connection's activities are shown in the user's presence.

#  is_friend_sync_enabled: bool

True if friends should be added based on this connection.

#  is_revoked: bool

True if the connection has been revoked.

#  is_verified: bool

True if the connection has been verified.

#  name: str

The username of the connected account.

#  type: str

The type of service this connection is for.

The visibility of the connection.

Methods
#  def __init__(
   self,
   *,
   id: str,
   name: str,
   type: str,
   is_revoked: bool,
   integrations: Sequence[hikari.guilds.PartialIntegration],
   is_verified: bool,
   is_friend_sync_enabled: bool,
   is_activity_visible: bool,
   visibility: Union[hikari.applications.ConnectionVisibility, int]
):
View Source
def __init__(self, *, id, name, type, is_revoked, integrations, is_verified, is_friend_sync_enabled, is_activity_visible, visibility):
    self.id = id
    self.name = name
    self.type = type
    self.is_revoked = is_revoked
    self.integrations = integrations
    self.is_verified = is_verified
    self.is_friend_sync_enabled = is_friend_sync_enabled
    self.is_activity_visible = is_activity_visible
    self.visibility = visibility

Method generated by attrs for class OwnConnection.

#  
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OwnGuild(hikari.guilds.PartialGuild):
View Source
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class OwnGuild(guilds.PartialGuild):
    """Represents a user bound partial guild object."""

    features: typing.Sequence[typing.Union[str, guilds.GuildFeature]] = attr.field(eq=False, hash=False, repr=False)
    """A list of the features in this guild."""

    is_owner: bool = attr.field(eq=False, hash=False, repr=True)
    """`True` when the current user owns this guild."""

    my_permissions: permissions_.Permissions = attr.field(eq=False, hash=False, repr=False)
    """The guild-level permissions that apply to the current user or bot."""

Represents a user bound partial guild object.

Variables and properties

The client application that models may use for procedures.

#  created_at: datetime.datetime

When the object was created.

#  features: Sequence[Union[str, hikari.guilds.GuildFeature]]

A list of the features in this guild.

#  icon_hash: Optional[str]

The hash for the guild icon, if there is one.

#  icon_url: Optional[hikari.files.URL]

Icon URL for the guild, if set; otherwise None.

The ID of this entity.

#  is_owner: bool

True when the current user owns this guild.

The guild-level permissions that apply to the current user or bot.

#  name: str

The name of the guild.

#  shard_id: Optional[int]

Return the ID of the shard this guild is served by.

This may return None if the application does not have a gateway connection.

Methods
#  def __init__(
   self,
   *,
   app: hikari.traits.RESTAware,
   id: hikari.snowflakes.Snowflake,
   icon_hash: Optional[str],
   name: str,
   features: Sequence[Union[str, hikari.guilds.GuildFeature]],
   is_owner: bool,
   my_permissions: hikari.permissions.Permissions
):
View Source
def __init__(self, *, app, id, icon_hash, name, features, is_owner, my_permissions):
    self.app = app
    self.id = id
    self.icon_hash = icon_hash
    self.name = name
    self.features = features
    self.is_owner = is_owner
    self.my_permissions = my_permissions

Method generated by attrs for class OwnGuild.

#  async def ban(
   self,
   user: Union[hikari.users.PartialUser, hikari.snowflakes.Snowflake, int],
   *,
   delete_message_days: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> None:
View Source
    async def ban(
        self,
        user: snowflakes.SnowflakeishOr[users.PartialUser],
        *,
        delete_message_days: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> None:
        """Ban the given user from this guild.

        Parameters
        ----------
        user: hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
            The user to ban from the guild

        Other Parameters
        ----------------
        delete_message_days : hikari.undefined.UndefinedNoneOr[int]
            If provided, the number of days to delete messages for.
            This must be between 0 and 7.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `BAN_MEMBERS` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild or user are 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.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.
        """
        await self.app.rest.ban_user(self.id, user, delete_message_days=delete_message_days, reason=reason)

Ban the given user from this guild.

Parameters
Other Parameters
Raises
#  async def create_category(
   self,
   name: str,
   *,
   position: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   permission_overwrites: Union[Sequence[hikari.channels.PermissionOverwrite], hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.channels.GuildCategory:
View Source
    async def create_category(
        self,
        name: str,
        *,
        position: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        permission_overwrites: undefined.UndefinedOr[
            typing.Sequence[channels_.PermissionOverwrite]
        ] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> channels_.GuildCategory:
        """Create a category in the guild.

        Parameters
        ----------
        name : str
            The channels name. Must be between 2 and 1000 characters.

        Other Parameters
        ----------------
        position : hikari.undefined.UndefinedOr[int]
            If provided, the position of the category.
        permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
            If provided, the permission overwrites for the category.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.channels.GuildCategory
            The created category.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_CHANNEL` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild 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.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.app.rest.create_guild_category(
            self.id, name, position=position, permission_overwrites=permission_overwrites, reason=reason
        )

Create a category in the guild.

Parameters
  • name (str): The channels name. Must be between 2 and 1000 characters.
Other Parameters
Returns
Raises
#  async def create_news_channel(
   self,
   name: str,
   *,
   position: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   topic: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   nsfw: Union[bool, hikari.undefined.UndefinedType] = UNDEFINED,
   rate_limit_per_user: Union[int, float, datetime.timedelta, hikari.undefined.UndefinedType] = UNDEFINED,
   permission_overwrites: Union[Sequence[hikari.channels.PermissionOverwrite], hikari.undefined.UndefinedType] = UNDEFINED,
   category: Union[hikari.channels.GuildCategory, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.channels.GuildNewsChannel:
View Source
    async def create_news_channel(
        self,
        name: str,
        *,
        position: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        topic: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        nsfw: undefined.UndefinedOr[bool] = undefined.UNDEFINED,
        rate_limit_per_user: undefined.UndefinedOr[time.Intervalish] = undefined.UNDEFINED,
        permission_overwrites: undefined.UndefinedOr[
            typing.Sequence[channels_.PermissionOverwrite]
        ] = undefined.UNDEFINED,
        category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> channels_.GuildNewsChannel:
        """Create a news channel in the guild.

        Parameters
        ----------
        name : str
            The channels name. Must be between 2 and 1000 characters.

        Other Parameters
        ----------------
        position : hikari.undefined.UndefinedOr[int]
            If provided, the position of the channel (relative to the
            category, if any).
        topic : hikari.undefined.UndefinedOr[str]
            If provided, the channels topic. Maximum 1024 characters.
        nsfw : hikari.undefined.UndefinedOr[bool]
            If provided, whether to mark the channel as NSFW.
        rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
            If provided, the amount of seconds a user has to wait
            before being able to send another message in the channel.
            Maximum 21600 seconds.
        permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
            If provided, the permission overwrites for the channel.
        category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
            The category to create the channel under. This may be the
            object or the ID of an existing category.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.channels.GuildNewsChannel
            The created channel.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_CHANNEL` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild 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.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.app.rest.create_guild_news_channel(
            self.id,
            name,
            position=position,
            topic=topic,
            nsfw=nsfw,
            rate_limit_per_user=rate_limit_per_user,
            permission_overwrites=permission_overwrites,
            category=category,
            reason=reason,
        )

Create a news channel in the guild.

Parameters
  • name (str): The channels name. Must be between 2 and 1000 characters.
Other Parameters
Returns
Raises
#  async def create_stage_channel(
   self,
   name: str,
   *,
   position: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   user_limit: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   bitrate: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   permission_overwrites: Union[Sequence[hikari.channels.PermissionOverwrite], hikari.undefined.UndefinedType] = UNDEFINED,
   region: Union[hikari.voices.VoiceRegion, str, hikari.undefined.UndefinedType] = UNDEFINED,
   category: Union[hikari.channels.GuildCategory, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.channels.GuildStageChannel:
View Source
    async def create_stage_channel(
        self,
        name: str,
        *,
        position: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        user_limit: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        bitrate: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        permission_overwrites: undefined.UndefinedOr[
            typing.Sequence[channels_.PermissionOverwrite]
        ] = undefined.UNDEFINED,
        region: undefined.UndefinedOr[typing.Union[voices_.VoiceRegion, str]] = undefined.UNDEFINED,
        category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> channels_.GuildStageChannel:
        """Create a stage channel in the guild.

        Parameters
        ----------
        name : str
            The channel's name. Must be between 2 and 1000 characters.

        Other Parameters
        ----------------
        position : hikari.undefined.UndefinedOr[int]
            If provided, the position of the channel (relative to the
            category, if any).
        user_limit : hikari.undefined.UndefinedOr[int]
            If provided, the maximum users in the channel at once.
            Must be between 0 and 99 with 0 meaning no limit.
        bitrate : hikari.undefined.UndefinedOr[int]
            If provided, the bitrate for the channel. Must be
            between 8000 and 96000 or 8000 and 128000 for VIP
            servers.
        permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
            If provided, the permission overwrites for the channel.
        region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
            If provided, the voice region to for this channel. Passing
            `None` here will set it to "auto" mode where the used
            region will be decided based on the first person who connects to it
            when it's empty.
        category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
            The category to create the channel under. This may be the
            object or the ID of an existing category.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.channels.GuildStageChannel
            The created channel.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_CHANNEL` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild 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.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.app.rest.create_guild_stage_channel(
            self.id,
            name,
            position=position,
            user_limit=user_limit,
            bitrate=bitrate,
            permission_overwrites=permission_overwrites,
            region=region,
            category=category,
            reason=reason,
        )

Create a stage channel in the guild.

Parameters
  • name (str): The channel's name. Must be between 2 and 1000 characters.
Other Parameters
Returns
Raises
#  async def create_sticker(
   self,
   name: str,
   tag: str,
   image: 'files.Resourceish',
   *,
   description: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.stickers.GuildSticker:
View Source
    async def create_sticker(
        self,
        name: str,
        tag: str,
        image: files.Resourceish,
        *,
        description: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> stickers.GuildSticker:
        """Create a sticker in a guild.

        .. note::
            Lottie support is only available for verified and partnered
            servers.

        Parameters
        ----------
        name : str
            The name for the sticker.
        tag : str
            The tag for the sticker.
        image : hikari.files.Resourceish
            The 320x320 image for the sticker. Maximum upload size is 500kb.
            This can be a still or an animated PNG or a Lottie.

        Other Parameters
        ----------------
        description: hikari.undefined.UndefinedOr[str]
            If provided, the description of the sticker.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.stickers.GuildSticker
            The created sticker.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value or
            if there are no more spaces for the sticker in the guild.
        hikari.errors.ForbiddenError
            If you are missing `MANAGE_EMOJIS_AND_STICKERS` in the server.
        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.
        """
        return await self.app.rest.create_sticker(self.id, name, tag, image, description=description, reason=reason)

Create a sticker in a guild.

Note: Lottie support is only available for verified and partnered servers.

Parameters
  • name (str): The name for the sticker.
  • tag (str): The tag for the sticker.
  • image (hikari.files.Resourceish): The 320x320 image for the sticker. Maximum upload size is 500kb. This can be a still or an animated PNG or a Lottie.
Other Parameters
Returns
Raises
  • hikari.errors.BadRequestError: If any of the fields that are passed have an invalid value or if there are no more spaces for the sticker in the guild.
  • hikari.errors.ForbiddenError: If you are missing MANAGE_EMOJIS_AND_STICKERS in the server.
  • 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.
#  async def create_text_channel(
   self,
   name: str,
   *,
   position: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   topic: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   nsfw: Union[bool, hikari.undefined.UndefinedType] = UNDEFINED,
   rate_limit_per_user: Union[int, float, datetime.timedelta, hikari.undefined.UndefinedType] = UNDEFINED,
   permission_overwrites: Union[Sequence[hikari.channels.PermissionOverwrite], hikari.undefined.UndefinedType] = UNDEFINED,
   category: Union[hikari.channels.GuildCategory, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.channels.GuildTextChannel:
View Source
    async def create_text_channel(
        self,
        name: str,
        *,
        position: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        topic: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        nsfw: undefined.UndefinedOr[bool] = undefined.UNDEFINED,
        rate_limit_per_user: undefined.UndefinedOr[time.Intervalish] = undefined.UNDEFINED,
        permission_overwrites: undefined.UndefinedOr[
            typing.Sequence[channels_.PermissionOverwrite]
        ] = undefined.UNDEFINED,
        category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> channels_.GuildTextChannel:
        """Create a text channel in the guild.

        Parameters
        ----------
        name : str
            The channels name. Must be between 2 and 1000 characters.

        Other Parameters
        ----------------
        position : hikari.undefined.UndefinedOr[int]
            If provided, the position of the channel (relative to the
            category, if any).
        topic : hikari.undefined.UndefinedOr[str]
            If provided, the channels topic. Maximum 1024 characters.
        nsfw : hikari.undefined.UndefinedOr[bool]
            If provided, whether to mark the channel as NSFW.
        rate_limit_per_user : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
            If provided, the amount of seconds a user has to wait
            before being able to send another message in the channel.
            Maximum 21600 seconds.
        permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
            If provided, the permission overwrites for the channel.
        category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
            The category to create the channel under. This may be the
            object or the ID of an existing category.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.channels.GuildTextChannel
            The created channel.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_CHANNEL` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild 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.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.app.rest.create_guild_text_channel(
            self.id,
            name,
            position=position,
            topic=topic,
            nsfw=nsfw,
            rate_limit_per_user=rate_limit_per_user,
            permission_overwrites=permission_overwrites,
            category=category,
            reason=reason,
        )

Create a text channel in the guild.

Parameters
  • name (str): The channels name. Must be between 2 and 1000 characters.
Other Parameters
Returns
Raises
#  async def create_voice_channel(
   self,
   name: str,
   *,
   position: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   user_limit: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   bitrate: Union[int, hikari.undefined.UndefinedType] = UNDEFINED,
   video_quality_mode: Union[hikari.channels.VideoQualityMode, int, hikari.undefined.UndefinedType] = UNDEFINED,
   permission_overwrites: Union[Sequence[hikari.channels.PermissionOverwrite], hikari.undefined.UndefinedType] = UNDEFINED,
   region: Union[hikari.voices.VoiceRegion, str, hikari.undefined.UndefinedType] = UNDEFINED,
   category: Union[hikari.channels.GuildCategory, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.channels.GuildVoiceChannel:
View Source
    async def create_voice_channel(
        self,
        name: str,
        *,
        position: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        user_limit: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        bitrate: undefined.UndefinedOr[int] = undefined.UNDEFINED,
        video_quality_mode: undefined.UndefinedOr[typing.Union[channels_.VideoQualityMode, int]] = undefined.UNDEFINED,
        permission_overwrites: undefined.UndefinedOr[
            typing.Sequence[channels_.PermissionOverwrite]
        ] = undefined.UNDEFINED,
        region: undefined.UndefinedOr[typing.Union[voices_.VoiceRegion, str]] = undefined.UNDEFINED,
        category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> channels_.GuildVoiceChannel:
        """Create a voice channel in a guild.

        Parameters
        ----------
        name : str
            The channels name. Must be between 2 and 1000 characters.

        Other Parameters
        ----------------
        position : hikari.undefined.UndefinedOr[int]
            If provided, the position of the channel (relative to the
            category, if any).
        user_limit : hikari.undefined.UndefinedOr[int]
            If provided, the maximum users in the channel at once.
            Must be between 0 and 99 with 0 meaning no limit.
        bitrate : hikari.undefined.UndefinedOr[int]
            If provided, the bitrate for the channel. Must be
            between 8000 and 96000 or 8000 and 128000 for VIP
            servers.
        video_quality_mode: hikari.undefined.UndefinedOr[typing.Union[hikari.channels.VideoQualityMode, int]]
            If provided, the new video quality mode for the channel.
        permission_overwrites : hikari.undefined.UndefinedOr[typing.Sequence[hikari.channels.PermissionOverwrite]]
            If provided, the permission overwrites for the channel.
        region : hikari.undefined.UndefinedOr[typing.Union[hikari.voices.VoiceRegion, str]]
            If provided, the voice region to for this channel. Passing
            `None` here will set it to "auto" mode where the used
            region will be decided based on the first person who connects to it
            when it's empty.
        category : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildCategory]]
            The category to create the channel under. This may be the
            object or the ID of an existing category.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.channels.GuildVoiceChannel
            The created channel.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_CHANNEL` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the gui  ld 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.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.app.rest.create_guild_voice_channel(
            self.id,
            name,
            position=position,
            user_limit=user_limit,
            bitrate=bitrate,
            video_quality_mode=video_quality_mode,
            permission_overwrites=permission_overwrites,
            region=region,
            category=category,
            reason=reason,
        )

Create a voice channel in a guild.

Parameters
  • name (str): The channels name. Must be between 2 and 1000 characters.
Other Parameters
Returns
Raises
#  async def delete_channel(
   self,
   channel: Union[hikari.channels.GuildChannel, hikari.snowflakes.Snowflake, int]
) -> hikari.channels.GuildChannel:
View Source
    async def delete_channel(
        self, channel: snowflakes.SnowflakeishOr[channels_.GuildChannel]
    ) -> channels_.GuildChannel:
        """Delete a channel in the guild.

        .. note::
            This method can also be used for deleting guild categories as well.

        .. note::
            For Public servers, the set 'Rules' or 'Guidelines' channels and the
            'Public Server Updates' channel cannot be deleted.

        Parameters
        ----------
        channel : hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildChannel]
            The channel or category to delete. This may be the object or the ID of an
            existing channel.

        Returns
        -------
        hikari.channels.GuildChannel
            Object of the channel or category that was deleted.

        Raises
        ------
        hikari.errors.UnauthorizedError, or close a DM.
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_CHANNEL` 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.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.
        """
        deleted_channel = await self.app.rest.delete_channel(channel)
        assert isinstance(deleted_channel, channels_.GuildChannel)

        return deleted_channel

Delete a channel in the guild.

Note: This method can also be used for deleting guild categories as well.

Note: For Public servers, the set 'Rules' or 'Guidelines' channels and the 'Public Server Updates' channel cannot be deleted.

Parameters
Returns
Raises
  • hikari.errors.UnauthorizedError, or close a DM.: If you are unauthorized to make the request (invalid/missing token).
  • hikari.errors.ForbiddenError: If you are missing the MANAGE_CHANNEL 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.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.
#  async def delete_sticker(
   self,
   sticker: Union[hikari.stickers.PartialSticker, hikari.snowflakes.Snowflake, int],
   *,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> None:
View Source
    async def delete_sticker(
        self,
        sticker: snowflakes.SnowflakeishOr[stickers.PartialSticker],
        *,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> None:
        """Delete a sticker in a guild.

        Parameters
        ----------
        sticker : hikari.snowflakes.SnowflakeishOr[hikari.stickers.PartialSticker]
            The sticker to delete. This can be a sticker object or the ID
            of an existing sticker.

        Other Parameters
        ----------------
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Raises
        ------
        hikari.errors.ForbiddenError
            If you are missing `MANAGE_EMOJIS_AND_STICKERS` in the server.
        hikari.errors.NotFoundError
            If the guild or the sticker are 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.
        """
        return await self.app.rest.delete_sticker(self.id, sticker, reason=reason)

Delete a sticker in a guild.

Parameters
Other Parameters
Raises
  • hikari.errors.ForbiddenError: If you are missing MANAGE_EMOJIS_AND_STICKERS in the server.
  • hikari.errors.NotFoundError: If the guild or the sticker are 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.
#  async def edit(
   self,
   *,
   name: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   verification_level: Union[hikari.guilds.GuildVerificationLevel, hikari.undefined.UndefinedType] = UNDEFINED,
   default_message_notifications: Union[hikari.guilds.GuildMessageNotificationsLevel, hikari.undefined.UndefinedType] = UNDEFINED,
   explicit_content_filter_level: Union[hikari.guilds.GuildExplicitContentFilterLevel, hikari.undefined.UndefinedType] = UNDEFINED,
   afk_channel: Union[hikari.channels.GuildVoiceChannel, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   afk_timeout: Union[int, float, datetime.timedelta, hikari.undefined.UndefinedType] = UNDEFINED,
   icon: 'undefined.UndefinedNoneOr[files.Resourceish]' = UNDEFINED,
   owner: Union[hikari.users.PartialUser, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   splash: 'undefined.UndefinedNoneOr[files.Resourceish]' = UNDEFINED,
   banner: 'undefined.UndefinedNoneOr[files.Resourceish]' = UNDEFINED,
   system_channel: Union[hikari.channels.GuildTextChannel, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType, NoneType] = UNDEFINED,
   rules_channel: Union[hikari.channels.GuildTextChannel, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType, NoneType] = UNDEFINED,
   public_updates_channel: Union[hikari.channels.GuildTextChannel, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType, NoneType] = UNDEFINED,
   preferred_locale: Union[str, hikari.locales.Locale, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.guilds.RESTGuild:
View Source
    async def edit(
        self,
        *,
        name: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        verification_level: undefined.UndefinedOr[GuildVerificationLevel] = undefined.UNDEFINED,
        default_message_notifications: undefined.UndefinedOr[GuildMessageNotificationsLevel] = undefined.UNDEFINED,
        explicit_content_filter_level: undefined.UndefinedOr[GuildExplicitContentFilterLevel] = undefined.UNDEFINED,
        afk_channel: undefined.UndefinedOr[
            snowflakes.SnowflakeishOr[channels_.GuildVoiceChannel]
        ] = undefined.UNDEFINED,
        afk_timeout: undefined.UndefinedOr[time.Intervalish] = undefined.UNDEFINED,
        icon: undefined.UndefinedNoneOr[files.Resourceish] = undefined.UNDEFINED,
        owner: undefined.UndefinedOr[snowflakes.SnowflakeishOr[users.PartialUser]] = undefined.UNDEFINED,
        splash: undefined.UndefinedNoneOr[files.Resourceish] = undefined.UNDEFINED,
        banner: undefined.UndefinedNoneOr[files.Resourceish] = undefined.UNDEFINED,
        system_channel: undefined.UndefinedNoneOr[
            snowflakes.SnowflakeishOr[channels_.GuildTextChannel]
        ] = undefined.UNDEFINED,
        rules_channel: undefined.UndefinedNoneOr[
            snowflakes.SnowflakeishOr[channels_.GuildTextChannel]
        ] = undefined.UNDEFINED,
        public_updates_channel: undefined.UndefinedNoneOr[
            snowflakes.SnowflakeishOr[channels_.GuildTextChannel]
        ] = undefined.UNDEFINED,
        preferred_locale: undefined.UndefinedOr[typing.Union[str, locales.Locale]] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> RESTGuild:
        """Edits the guild.

        Parameters
        ----------
        name : hikari.undefined.UndefinedOr[str]
            If provided, the new name for the guild.
        verification_level : hikari.undefined.UndefinedOr[hikari.guilds.GuildVerificationLevel]
            If provided, the new verification level.
        default_message_notifications : hikari.undefined.UndefinedOr[hikari.guilds.GuildMessageNotificationsLevel]
            If provided, the new default message notifications level.
        explicit_content_filter_level : hikari.undefined.UndefinedOr[hikari.guilds.GuildExplicitContentFilterLevel]
            If provided, the new explicit content filter level.
        afk_channel : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildVoiceChannel]]
            If provided, the new afk channel. Requires `afk_timeout` to
            be set to work.
        afk_timeout : hikari.undefined.UndefinedOr[hikari.internal.time.Intervalish]
            If provided, the new afk timeout.
        icon : hikari.undefined.UndefinedOr[hikari.files.Resourceish]
            If provided, the new guild icon. Must be a 1024x1024 image or can be
            an animated gif when the guild has the `ANIMATED_ICON` feature.
        owner : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.users.PartialUser]]]
            If provided, the new guild owner.

            .. warning::
                You need to be the owner of the server to use this.
        splash : hikari.undefined.UndefinedNoneOr[hikari.files.Resourceish]
            If provided, the new guild splash. Must be a 16:9 image and the
            guild must have the `INVITE_SPLASH` feature.
        banner : hikari.undefined.UndefinedNoneOr[hikari.files.Resourceish]
            If provided, the new guild banner. Must be a 16:9 image and the
            guild must have the `BANNER` feature.
        system_channel : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildTextChannel]]
            If provided, the new system channel.
        rules_channel : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildTextChannel]]
            If provided, the new rules channel.
        public_updates_channel : hikari.undefined.UndefinedNoneOr[hikari.snowflakes.SnowflakeishOr[hikari.channels.GuildTextChannel]]
            If provided, the new public updates channel.
        preferred_locale : hikari.undefined.UndefinedNoneOr[str]
            If provided, the new preferred locale.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.guilds.RESTGuild
            The edited guild.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value. Or
            you are missing the
        hikari.errors.ForbiddenError
            If you are missing the `MANAGE_GUILD` permission or if you tried to
            pass ownership without being the server owner.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild 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.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.
        """  # noqa: E501 - Line too long
        return await self.app.rest.edit_guild(
            self.id,
            name=name,
            verification_level=verification_level,
            default_message_notifications=default_message_notifications,
            explicit_content_filter_level=explicit_content_filter_level,
            afk_channel=afk_channel,
            afk_timeout=afk_timeout,
            icon=icon,
            owner=owner,
            splash=splash,
            banner=banner,
            system_channel=system_channel,
            rules_channel=rules_channel,
            public_updates_channel=public_updates_channel,
            preferred_locale=preferred_locale,
            reason=reason,
        )

Edits the guild.

Parameters
Returns
Raises
  • hikari.errors.BadRequestError: If any of the fields that are passed have an invalid value. Or you are missing the
  • hikari.errors.ForbiddenError: If you are missing the MANAGE_GUILD permission or if you tried to pass ownership without being the server owner.
  • hikari.errors.UnauthorizedError: If you are unauthorized to make the request (invalid/missing token).
  • hikari.errors.NotFoundError: If the guild 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.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.
#  async def edit_sticker(
   self,
   sticker: Union[hikari.stickers.PartialSticker, hikari.snowflakes.Snowflake, int],
   *,
   name: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   description: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   tag: Union[str, hikari.undefined.UndefinedType] = UNDEFINED,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.stickers.GuildSticker:
View Source
    async def edit_sticker(
        self,
        sticker: snowflakes.SnowflakeishOr[stickers.PartialSticker],
        *,
        name: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        description: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        tag: undefined.UndefinedOr[str] = undefined.UNDEFINED,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> stickers.GuildSticker:
        """Edit a sticker in a guild.

        Parameters
        ----------
        sticker : hikari.snowflakes.SnowflakeishOr[hikari.stickers.PartialSticker]
            The sticker to edit. This can be a sticker object or the ID of an
            existing sticker.

        Other Parameters
        ----------------
        name : hikari.undefined.UndefinedOr[str]
            If provided, the new name for the sticker.
        description : hikari.undefined.UndefinedOr[str]
            If provided, the new description for the sticker.
        tag : hikari.undefined.UndefinedOr[str]
            If provided, the new sticker tag.
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Returns
        -------
        hikari.stickers.GuildSticker
            The edited sticker.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing `MANAGE_EMOJIS_AND_STICKERS` in the server.
        hikari.errors.NotFoundError
            If the guild or the sticker are 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.
        """
        return await self.app.rest.edit_sticker(
            self.id, sticker, name=name, description=description, tag=tag, reason=reason
        )

Edit a sticker in a guild.

Parameters
Other Parameters
Returns
Raises
#  async def fetch_emoji(
   self,
   emoji: Union[hikari.emojis.CustomEmoji, hikari.snowflakes.Snowflake, int]
) -> hikari.emojis.KnownCustomEmoji:
View Source
    async def fetch_emoji(self, emoji: snowflakes.SnowflakeishOr[emojis_.CustomEmoji]) -> emojis_.KnownCustomEmoji:
        """Fetch an emoji from the guild.

        Parameters
        ----------
        emoji : hikari.snowflakes.SnowflakeishOr[hikari.emojis.CustomEmoji]
            The emoji to fetch. This can be a `hikari.emojis.CustomEmoji`
            or the ID of an existing emoji.

        Returns
        -------
        hikari.emojis.KnownCustomEmoji
            The requested emoji.

        Raises
        ------
        hikari.errors.NotFoundError
            If the guild or the emoji are 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.
        """
        return await self.app.rest.fetch_emoji(self.id, emoji)

Fetch an emoji from the guild.

Parameters
Returns
Raises
  • hikari.errors.NotFoundError: If the guild or the emoji are 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.
#  async def fetch_emojis(self) -> Sequence[hikari.emojis.KnownCustomEmoji]:
View Source
    async def fetch_emojis(self) -> typing.Sequence[emojis_.KnownCustomEmoji]:
        """Fetch the emojis of the guild.

        Returns
        -------
        typing.Sequence[hikari.emojis.KnownCustomEmoji]
            The requested emojis.

        Raises
        ------
        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.
        """
        return await self.app.rest.fetch_guild_emojis(self.id)

Fetch the emojis of the guild.

Returns
Raises
  • 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.
#  async def fetch_roles(self) -> Sequence[hikari.guilds.Role]:
View Source
    async def fetch_roles(self) -> typing.Sequence[Role]:
        """Fetch the roles of the guild.

        Returns
        -------
        typing.Sequence[hikari.guilds.Role]
            The requested roles.

        Raises
        ------
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
            hikari.errors.NotFoundError
                If the guild 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.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.app.rest.fetch_roles(self.id)

Fetch the roles of the guild.

Returns
Raises
  • hikari.errors.UnauthorizedError: If you are unauthorized to make the request (invalid/missing token). hikari.errors.NotFoundError If the guild 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.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.
#  async def fetch_self(self) -> hikari.guilds.RESTGuild:
View Source
    async def fetch_self(self) -> RESTGuild:
        """Fetch the guild.

        Returns
        -------
        hikari.guilds.RESTGuild
            The requested guild.

        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.
        """
        return await self.app.rest.fetch_guild(self.id)

Fetch the guild.

Returns
Raises
#  async def fetch_sticker(
   self,
   sticker: Union[hikari.stickers.PartialSticker, hikari.snowflakes.Snowflake, int]
) -> hikari.stickers.GuildSticker:
View Source
    async def fetch_sticker(self, sticker: snowflakes.SnowflakeishOr[stickers.PartialSticker]) -> stickers.GuildSticker:
        """Fetch a sticker from the guild.

        Parameters
        ----------
        sticker : snowflakes.SnowflakeishOr[hikari.stickers.PartialSticker]
            The sticker to fetch. This can be a sticker object or the
            ID of an existing sticker.

        Returns
        -------
        hikari.stickers.GuildSticker
            The requested sticker.

        Raises
        ------
        hikari.errors.ForbiddenError
            If you are not part of the server.
        hikari.errors.NotFoundError
            If the guild or the sticker are 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.
        """
        return await self.app.rest.fetch_guild_sticker(self.id, sticker)

Fetch a sticker from the guild.

Parameters
  • sticker (snowflakes.SnowflakeishOr[hikari.stickers.PartialSticker]): The sticker to fetch. This can be a sticker object or the ID of an existing sticker.
Returns
Raises
#  async def fetch_stickers(self) -> Sequence[hikari.stickers.GuildSticker]:
View Source
    async def fetch_stickers(self) -> typing.Sequence[stickers.GuildSticker]:
        """Fetch the stickers of the guild.

        Returns
        -------
        typing.Sequence[hikari.stickers.GuildSticker]
            The requested stickers.

        Raises
        ------
        hikari.errors.ForbiddenError
            If you are not part of the server.
        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.
        """
        return await self.app.rest.fetch_guild_stickers(self.id)

Fetch the stickers of the guild.

Returns
Raises
#  async def kick(
   self,
   user: Union[hikari.users.PartialUser, hikari.snowflakes.Snowflake, int],
   *,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> None:
View Source
    async def kick(
        self,
        user: snowflakes.SnowflakeishOr[users.PartialUser],
        *,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> None:
        """Kicks the given user from this guild.

        Parameters
        ----------
        user: hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
            The user to kick from the guild

        Other Parameters
        ----------------
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `KICK_MEMBERS` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild or user are 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.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.
        """
        await self.app.rest.kick_user(self.id, user, reason=reason)

Kicks the given user from this guild.

Parameters
Other Parameters
Raises
#  def make_icon_url(
   self,
   *,
   ext: Optional[str] = None,
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_icon_url(self, *, ext: typing.Optional[str] = None, size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the guild's icon URL, if set.

        Parameters
        ----------
        ext : typing.Optional[str]
            The extension to use for this URL, defaults to `png` or `gif`.
            Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
            animated).

            If `None`, then the correct default extension is
            determined based on whether the icon is animated or not.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL to the resource, or `None` if no icon is set.

        Raises
        ------
        ValueError
            If `size` is not a power of two or not between 16 and 4096.
        """
        if self.icon_hash is None:
            return None

        if ext is None:
            if self.icon_hash.startswith("a_"):
                ext = "gif"
            else:
                ext = "png"

        return routes.CDN_GUILD_ICON.compile_to_file(
            urls.CDN_URL,
            guild_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )

Generate the guild's icon URL, if set.

Parameters
  • ext (typing.Optional[str]): The extension to use for this URL, defaults to png or gif. Supports png, jpeg, jpg, webp and gif (when animated).

    If None, then the correct default extension is determined based on whether the icon is animated or not.

  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
  • typing.Optional[hikari.files.URL]: The URL to the resource, or None if no icon is set.
Raises
  • ValueError: If size is not a power of two or not between 16 and 4096.
#  async def unban(
   self,
   user: Union[hikari.users.PartialUser, hikari.snowflakes.Snowflake, int],
   *,
   reason: Union[str, hikari.undefined.UndefinedType] = UNDEFINED
) -> None:
View Source
    async def unban(
        self,
        user: snowflakes.SnowflakeishOr[users.PartialUser],
        *,
        reason: undefined.UndefinedOr[str] = undefined.UNDEFINED,
    ) -> None:
        """Unban the given user from this guild.

        Parameters
        ----------
        user: hikari.snowflakes.Snowflakeish[hikari.users.PartialUser]
            The user to unban from the guild

        Other Parameters
        ----------------
        reason : hikari.undefined.UndefinedOr[str]
            If provided, the reason that will be recorded in the audit logs.
            Maximum of 512 characters.

        Raises
        ------
        hikari.errors.BadRequestError
            If any of the fields that are passed have an invalid value.
        hikari.errors.ForbiddenError
            If you are missing the `BAN_MEMBERS` permission.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the guild or user are 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.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.
        """
        await self.app.rest.unban_user(self.id, user, reason=reason)

Unban the given user from this guild.

Parameters
Other Parameters
Raises
#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class PartialOAuth2Token:
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class PartialOAuth2Token:
    """Model for partial OAuth2 token data returned by the API.

    This will generally only be returned when by the client credentials OAuth2
    flow.
    """

    access_token: str = attr.field(hash=True, repr=False)
    """Access token issued by the authorization server."""

    token_type: typing.Union[TokenType, str] = attr.field(eq=False, hash=False, repr=True)
    """Type of token issued by the authorization server."""

    expires_in: datetime.timedelta = attr.field(eq=False, hash=False, repr=True)
    """Lifetime of this access token."""

    scopes: typing.Sequence[typing.Union[OAuth2Scope, str]] = attr.field(eq=False, hash=False, repr=True)
    """Scopes the access token has access to."""

    def __str__(self) -> str:
        return self.access_token

Model for partial OAuth2 token data returned by the API.

This will generally only be returned when by the client credentials OAuth2 flow.

Variables and properties
#  access_token: str

Access token issued by the authorization server.

#  expires_in: datetime.timedelta

Lifetime of this access token.

#  scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]]

Scopes the access token has access to.

#  token_type: Union[hikari.applications.TokenType, str]

Type of token issued by the authorization server.

Methods
#  def __init__(
   self,
   *,
   access_token: str,
   token_type: Union[hikari.applications.TokenType, str],
   expires_in: datetime.timedelta,
   scopes: Sequence[Union[hikari.applications.OAuth2Scope, str]]
):
View Source
def __init__(self, *, access_token, token_type, expires_in, scopes):
    self.access_token = access_token
    self.token_type = token_type
    self.expires_in = expires_in
    self.scopes = scopes

Method generated by attrs for class PartialOAuth2Token.

#  
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class Team(hikari.snowflakes.Unique):
View Source
@attr_extensions.with_copy
@attr.define(hash=True, kw_only=True, weakref_slot=False)
class Team(snowflakes.Unique):
    """Represents a development team, along with all its members."""

    app: traits.RESTAware = attr.field(
        repr=False, eq=False, hash=False, metadata={attr_extensions.SKIP_DEEP_COPY: True}
    )
    """The client application that models may use for procedures."""

    id: snowflakes.Snowflake = attr.field(hash=True, repr=True)
    """The ID of this entity."""

    name: str = attr.field(hash=False, eq=False, repr=True)
    """The name of this team."""

    icon_hash: typing.Optional[str] = attr.field(eq=False, hash=False, repr=False)
    """The CDN hash of this team's icon.

    If no icon is provided, this will be `None`.
    """

    members: typing.Mapping[snowflakes.Snowflake, TeamMember] = attr.field(eq=False, hash=False, repr=False)
    """A mapping containing each member in this team.

    The mapping maps keys containing the member's ID to values containing the
    member object.
    """

    owner_id: snowflakes.Snowflake = attr.field(eq=False, hash=False, repr=True)
    """The ID of this team's owner."""

    def __str__(self) -> str:
        return f"Team {self.name} ({self.id})"

    @property
    def icon_url(self) -> typing.Optional[files.URL]:
        """Icon URL, or `None` if no icon exists."""
        return self.make_icon_url()

    def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the icon URL for this team if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`. Can be any power
            of two between `16` and `4096` inclusive.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no icon exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.icon_hash is None:
            return None

        return routes.CDN_TEAM_ICON.compile_to_file(
            urls.CDN_URL,
            team_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )

Represents a development team, along with all its members.

Variables and properties

The client application that models may use for procedures.

#  created_at: datetime.datetime

When the object was created.

#  icon_hash: Optional[str]

The CDN hash of this team's icon.

If no icon is provided, this will be None.

#  icon_url: Optional[hikari.files.URL]

Icon URL, or None if no icon exists.

The ID of this entity.

A mapping containing each member in this team.

The mapping maps keys containing the member's ID to values containing the member object.

#  name: str

The name of this team.

The ID of this team's owner.

Methods
#  def __init__(
   self,
   *,
   app: hikari.traits.RESTAware,
   id: hikari.snowflakes.Snowflake,
   name: str,
   icon_hash: Optional[str],
   members: Mapping[hikari.snowflakes.Snowflake, hikari.applications.TeamMember],
   owner_id: hikari.snowflakes.Snowflake
):
View Source
def __init__(self, *, app, id, name, icon_hash, members, owner_id):
    self.app = app
    self.id = id
    self.name = name
    self.icon_hash = icon_hash
    self.members = members
    self.owner_id = owner_id

Method generated by attrs for class Team.

#  def make_icon_url(
   self,
   *,
   ext: str = 'png',
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_icon_url(self, *, ext: str = "png", size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the icon URL for this team if set.

        Parameters
        ----------
        ext : str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : int
            The size to set for the URL, defaults to `4096`. Can be any power
            of two between `16` and `4096` inclusive.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `None` if no icon exists.

        Raises
        ------
        ValueError
            If the size is not an integer power of 2 between 16 and 4096
            (inclusive).
        """
        if self.icon_hash is None:
            return None

        return routes.CDN_TEAM_ICON.compile_to_file(
            urls.CDN_URL,
            team_id=self.id,
            hash=self.icon_hash,
            size=size,
            file_format=ext,
        )

Generate the icon URL for this team if set.

Parameters
  • ext (str): The extension to use for this URL, defaults to png. Supports png, jpeg, jpg and webp.
  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096 inclusive.
Returns
Raises
  • ValueError: If the size is not an integer power of 2 between 16 and 4096 (inclusive).
#  
@attr_extensions.with_copy
@attr.define(eq=False, hash=False, kw_only=True, weakref_slot=False)
class TeamMember(hikari.users.User):
View Source
@attr_extensions.with_copy
@attr.define(eq=False, hash=False, kw_only=True, weakref_slot=False)
class TeamMember(users.User):
    """Represents a member of a Team."""

    membership_state: typing.Union[TeamMembershipState, int] = attr.field(repr=False)
    """The state of this user's membership."""

    permissions: typing.Sequence[str] = attr.field(repr=False)
    """This member's permissions within a team.

    At the time of writing, this will always be a sequence of one `str`,
    which will always be `"*"`. This may change in the future, however.
    """

    team_id: snowflakes.Snowflake = attr.field(repr=True)
    """The ID of the team this member belongs to."""

    user: users.User = attr.field(repr=True)
    """The user representation of this team member."""

    @property
    def app(self) -> traits.RESTAware:
        """Return the app that is bound to the user object."""
        return self.user.app

    @property
    def avatar_hash(self) -> typing.Optional[str]:
        return self.user.avatar_hash

    @property
    def avatar_url(self) -> typing.Optional[files.URL]:
        return self.user.avatar_url

    @property
    def default_avatar_url(self) -> files.URL:
        return self.user.default_avatar_url

    @property
    def banner_hash(self) -> typing.Optional[str]:
        return self.user.banner_hash

    @property
    def banner_url(self) -> typing.Optional[files.URL]:
        return self.user.banner_url

    @property
    def accent_color(self) -> typing.Optional[colors.Color]:
        return self.user.accent_color

    @property
    def discriminator(self) -> str:
        return self.user.discriminator

    @property
    def flags(self) -> users.UserFlag:
        return self.user.flags

    @property
    def id(self) -> snowflakes.Snowflake:
        return self.user.id

    @property
    def is_bot(self) -> bool:
        return self.user.is_bot

    @property
    def is_system(self) -> bool:
        return self.user.is_system

    @property
    def mention(self) -> str:
        return self.user.mention

    @property
    def username(self) -> str:
        return self.user.username

    def __str__(self) -> str:
        return str(self.user)

    def __hash__(self) -> int:
        return hash(self.user)

    def __eq__(self, other: object) -> bool:
        return self.user == other

Represents a member of a Team.

Variables and properties
#  accent_color: Optional[hikari.colors.Color]

The custom banner color for the user, if set else None.

The official client will decide the default color if not set.

#  accent_colour: Optional[hikari.colors.Color]

Alias for the accent_color field.

Return the app that is bound to the user object.

#  avatar_hash: Optional[str]

Avatar hash for the user, if they have one, otherwise None.

#  avatar_url: Optional[hikari.files.URL]

Avatar URL for the user, if they have one set.

May be None if no custom avatar is set. In this case, you should use default_avatar_url instead.

#  banner_hash: Optional[str]

Banner hash for the user, if they have one, otherwise hikari.undefined.UNDEFINED.

#  banner_url: Optional[hikari.files.URL]

Banner URL for the user, if they have one set.

May be None if no custom banner is set.

#  created_at: datetime.datetime

When the object was created.

#  default_avatar_url: hikari.files.URL

Default avatar URL for this user.

#  discriminator: str

Discriminator for the user.

#  display_avatar_url: hikari.files.URL

Display avatar URL for this user.

Flag bits that are set for the user.

Return the ID of this entity.

Returns
  • Snowflake: The snowflake ID of this object.
#  is_bot: bool

Whether this user is a bot account.

#  is_system: bool

Whether this user is a system account.

#  membership_state: Union[hikari.applications.TeamMembershipState, int]

The state of this user's membership.

#  mention: str

Return a raw mention string for the given user.

Example
>>> some_user.mention
'<@123456789123456789>'
#  permissions: Sequence[str]

This member's permissions within a team.

At the time of writing, this will always be a sequence of one str, which will always be "*". This may change in the future, however.

The ID of the team this member belongs to.

The user representation of this team member.

#  username: str

Username for the user.

Methods
#  def __init__(
   self,
   *,
   membership_state: Union[hikari.applications.TeamMembershipState, int],
   permissions: Sequence[str],
   team_id: hikari.snowflakes.Snowflake,
   user: hikari.users.User
):
View Source
def __init__(self, *, membership_state, permissions, team_id, user):
    self.membership_state = membership_state
    self.permissions = permissions
    self.team_id = team_id
    self.user = user

Method generated by attrs for class TeamMember.

#  async def fetch_dm_channel(self) -> hikari.channels.DMChannel:
View Source
    async def fetch_dm_channel(self) -> channels.DMChannel:
        """Fetch the DM channel for this user.

        Returns
        -------
        hikari.channels.DMChannel
            The requested channel.

        Raises
        ------
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.NotFoundError
            If the user 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.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.app.rest.create_dm_channel(self.id)

Fetch the DM channel for this user.

Returns
Raises
  • hikari.errors.UnauthorizedError: If you are unauthorized to make the request (invalid/missing token).
  • hikari.errors.NotFoundError: If the user 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.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.
#  async def fetch_self(self) -> hikari.users.User:
View Source
    async def fetch_self(self) -> User:
        """Get this user's up-to-date object by performing an API call.

        Returns
        -------
        hikari.users.User
            The requested user object.

        Raises
        ------
        hikari.errors.NotFoundError
            If the user 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.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.app.rest.fetch_user(user=self.id)

Get this user's up-to-date object by performing an API call.

Returns
Raises
  • hikari.errors.NotFoundError: If the user 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.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.
#  def make_avatar_url(
   self,
   *,
   ext: Optional[str] = None,
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_avatar_url(self, *, ext: typing.Optional[str] = None, size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the avatar URL for this user, if set.

        If no custom avatar is set, this returns `None`. You can then
        use the `default_avatar_url` attribute instead to fetch the displayed
        URL.

        Parameters
        ----------
        ext : typing.Optional[str]
            The ext to use for this URL, defaults to `png` or `gif`.
            Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
            animated). Will be ignored for default avatars which can only be
            `png`.

            If `None`, then the correct default extension is
            determined based on whether the icon is animated or not.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.
            Will be ignored for default avatars.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL to the avatar, or `None` if not present.

        Raises
        ------
        ValueError
            If `size` is not a power of two or not between 16 and 4096.
        """
        if self.avatar_hash is None:
            return None

        if ext is None:
            if self.avatar_hash.startswith("a_"):
                ext = "gif"
            else:
                ext = "png"

        return routes.CDN_USER_AVATAR.compile_to_file(
            urls.CDN_URL,
            user_id=self.id,
            hash=self.avatar_hash,
            size=size,
            file_format=ext,
        )

Generate the avatar URL for this user, if set.

If no custom avatar is set, this returns None. You can then use the default_avatar_url attribute instead to fetch the displayed URL.

Parameters
  • ext (typing.Optional[str]): The ext to use for this URL, defaults to png or gif. Supports png, jpeg, jpg, webp and gif (when animated). Will be ignored for default avatars which can only be png.

    If None, then the correct default extension is determined based on whether the icon is animated or not.

  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096. Will be ignored for default avatars.
Returns
  • typing.Optional[hikari.files.URL]: The URL to the avatar, or None if not present.
Raises
  • ValueError: If size is not a power of two or not between 16 and 4096.
#  def make_banner_url(
   self,
   *,
   ext: Optional[str] = None,
   size: int = 4096
) -> Optional[hikari.files.URL]:
View Source
    def make_banner_url(self, *, ext: typing.Optional[str] = None, size: int = 4096) -> typing.Optional[files.URL]:
        """Generate the banner URL for this user, if set.

        If no custom banner is set, this returns `None`.

        Parameters
        ----------
        ext : typing.Optional[str]
            The ext to use for this URL, defaults to `png` or `gif`.
            Supports `png`, `jpeg`, `jpg`, `webp` and `gif` (when
            animated).

            If `None`, then the correct default extension is
            determined based on whether the banner is animated or not.
        size : int
            The size to set for the URL, defaults to `4096`.
            Can be any power of two between 16 and 4096.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL to the banner, or `None` if not present.

        Raises
        ------
        ValueError
            If `size` is not a power of two or not between 16 and 4096.
        """
        if self.banner_hash is None:
            return None

        if ext is None:
            if self.banner_hash.startswith("a_"):
                ext = "gif"
            else:
                ext = "png"

        return routes.CDN_USER_BANNER.compile_to_file(
            urls.CDN_URL,
            user_id=self.id,
            hash=self.banner_hash,
            size=size,
            file_format=ext,
        )

Generate the banner URL for this user, if set.

If no custom banner is set, this returns None.

Parameters
  • ext (typing.Optional[str]): The ext to use for this URL, defaults to png or gif. Supports png, jpeg, jpg, webp and gif (when animated).

    If None, then the correct default extension is determined based on whether the banner is animated or not.

  • size (int): The size to set for the URL, defaults to 4096. Can be any power of two between 16 and 4096.
Returns
  • typing.Optional[hikari.files.URL]: The URL to the banner, or None if not present.
Raises
  • ValueError: If size is not a power of two or not between 16 and 4096.
#  async def send(
   self,
   content: Union[Any, hikari.undefined.UndefinedType] = UNDEFINED,
   *,
   attachment: 'undefined.UndefinedOr[files.Resourceish]' = UNDEFINED,
   attachments: 'undefined.UndefinedOr[typing.Sequence[files.Resourceish]]' = UNDEFINED,
   component: Union[hikari.api.special_endpoints.ComponentBuilder, hikari.undefined.UndefinedType] = UNDEFINED,
   components: Union[Sequence[hikari.api.special_endpoints.ComponentBuilder], hikari.undefined.UndefinedType] = UNDEFINED,
   embed: Union[hikari.embeds.Embed, hikari.undefined.UndefinedType] = UNDEFINED,
   embeds: Union[Sequence[hikari.embeds.Embed], hikari.undefined.UndefinedType] = UNDEFINED,
   tts: Union[bool, hikari.undefined.UndefinedType] = UNDEFINED,
   reply: Union[hikari.messages.PartialMessage, hikari.snowflakes.Snowflake, int, hikari.undefined.UndefinedType] = UNDEFINED,
   mentions_everyone: Union[bool, hikari.undefined.UndefinedType] = UNDEFINED,
   mentions_reply: Union[bool, hikari.undefined.UndefinedType] = UNDEFINED,
   user_mentions: Union[Sequence[Union[hikari.users.PartialUser, hikari.snowflakes.Snowflake, int]], bool, hikari.undefined.UndefinedType] = UNDEFINED,
   role_mentions: Union[Sequence[Union[hikari.guilds.PartialRole, hikari.snowflakes.Snowflake, int]], bool, hikari.undefined.UndefinedType] = UNDEFINED
) -> hikari.messages.Message:
View Source
    async def send(
        self,
        content: undefined.UndefinedOr[typing.Any] = undefined.UNDEFINED,
        *,
        attachment: undefined.UndefinedOr[files.Resourceish] = undefined.UNDEFINED,
        attachments: undefined.UndefinedOr[typing.Sequence[files.Resourceish]] = undefined.UNDEFINED,
        component: undefined.UndefinedOr[special_endpoints.ComponentBuilder] = undefined.UNDEFINED,
        components: undefined.UndefinedOr[typing.Sequence[special_endpoints.ComponentBuilder]] = undefined.UNDEFINED,
        embed: undefined.UndefinedOr[embeds_.Embed] = undefined.UNDEFINED,
        embeds: undefined.UndefinedOr[typing.Sequence[embeds_.Embed]] = undefined.UNDEFINED,
        tts: undefined.UndefinedOr[bool] = undefined.UNDEFINED,
        reply: undefined.UndefinedOr[snowflakes.SnowflakeishOr[messages.PartialMessage]] = undefined.UNDEFINED,
        mentions_everyone: undefined.UndefinedOr[bool] = undefined.UNDEFINED,
        mentions_reply: undefined.UndefinedOr[bool] = undefined.UNDEFINED,
        user_mentions: undefined.UndefinedOr[
            typing.Union[snowflakes.SnowflakeishSequence[PartialUser], bool]
        ] = undefined.UNDEFINED,
        role_mentions: undefined.UndefinedOr[
            typing.Union[snowflakes.SnowflakeishSequence[guilds.PartialRole], bool]
        ] = undefined.UNDEFINED,
    ) -> messages.Message:
        """Send a message to this user in DM's.

        Parameters
        ----------
        content : hikari.undefined.UndefinedOr[typing.Any]
            If provided, the message contents. If
            `hikari.undefined.UNDEFINED`, then nothing will be sent
            in the content. Any other value here will be cast to a
            `str`.

            If this is a `hikari.embeds.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.

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


        Other Parameters
        ----------------
        attachment : hikari.undefined.UndefinedOr[hikari.files.Resourceish],
            If provided, the message attachment. This can be a resource,
            or string of a path on your computer or a URL.

            Attachments can be passed as many different things, to aid in
            convenience.

            - If a `pathlib.PurePath` or `str` to a valid URL, the
                resource at the given URL will be streamed to Discord when
                sending the message. Subclasses of
                `hikari.files.WebResource` such as
                `hikari.files.URL`,
                `hikari.messages.Attachment`,
                `hikari.emojis.Emoji`,
                `EmbedResource`, etc will also be uploaded this way.
                This will use bit-inception, so only a small percentage of the
                resource will remain in memory at any one time, thus aiding in
                scalability.
            - If a `hikari.files.Bytes` is passed, or a `str`
                that contains a valid data URI is passed, then this is uploaded
                with a randomized file name if not provided.
            - If a `hikari.files.File`, `pathlib.PurePath` or
                `str` that is an absolute or relative path to a file
                on your file system is passed, then this resource is uploaded
                as an attachment using non-blocking code internally and streamed
                using bit-inception where possible. This depends on the
                type of `concurrent.futures.Executor` that is being used for
                the application (default is a thread pool which supports this
                behaviour).
        attachments : hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]],
            If provided, the message attachments. These can be resources, or
            strings consisting of paths on your computer or URLs.
        component : hikari.undefined.UndefinedOr[hikari.api.special_endpoints.ComponentBuilder]
            If provided, builder object of the component to include in this message.
        components : hikari.undefined.UndefinedOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]
            If provided, a sequence of the component builder objects to include
            in this message.
        embed : hikari.undefined.UndefinedOr[hikari.embeds.Embed]
            If provided, the message embed.
        embeds : hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]
            If provided, the message embeds.
        tts : hikari.undefined.UndefinedOr[bool]
            If provided, whether the message will be read out by a screen
            reader using Discord's TTS (text-to-speech) system.
        reply : hikari.undefined.UndefinedOr[hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage]]
            If provided, the message to reply to.
        mentions_everyone : hikari.undefined.UndefinedOr[bool]
            If provided, whether the message should parse @everyone/@here
            mentions.
        mentions_reply : hikari.undefined.UndefinedOr[bool]
            If provided, whether to mention the author of the message
            that is being replied to.

            This will not do anything if not being used with `reply`.
        user_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.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
            `hikari.snowflakes.Snowflake`, or
            `hikari.users.PartialUser` derivatives to enforce mentioning
            specific users.
        role_mentions : hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.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
            `hikari.snowflakes.Snowflake`, or
            `hikari.guilds.PartialRole` derivatives to enforce mentioning
            specific roles.

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

        Raises
        ------
        ValueError
            If more than 100 unique objects/entities are passed for
            `role_mentions` or `user_mentions`.
        TypeError
            If both `attachment` and `attachments` are specified.
        hikari.errors.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; `reply` not found or not in the same
            channel; too many components.
        hikari.errors.UnauthorizedError
            If you are unauthorized to make the request (invalid/missing token).
        hikari.errors.ForbiddenError
            If you are missing the `SEND_MESSAGES` in the channel or the
            person you are trying to message has the DM's disabled.
        hikari.errors.NotFoundError
            If the user 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.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.
        """  # noqa: E501 - Line too long
        channel_id = None
        if isinstance(self.app, traits.CacheAware):
            channel_id = self.app.cache.get_dm_channel_id(self.id)

        if channel_id is None:
            channel_id = (await self.fetch_dm_channel()).id

        return await self.app.rest.create_message(
            channel=channel_id,
            content=content,
            attachment=attachment,
            attachments=attachments,
            component=component,
            components=components,
            embed=embed,
            embeds=embeds,
            tts=tts,
            reply=reply,
            mentions_everyone=mentions_everyone,
            user_mentions=user_mentions,
            role_mentions=role_mentions,
            mentions_reply=mentions_reply,
        )

Send a message to this user in DM's.

Parameters
  • content (hikari.undefined.UndefinedOr[typing.Any]): If provided, the message contents. If hikari.undefined.UNDEFINED, then nothing will be sent in the content. Any other value here will be cast to a str.

    If this is a hikari.embeds.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.

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

Other Parameters
Returns
Raises
  • ValueError: If more than 100 unique objects/entities are passed for role_mentions or user_mentions.
  • TypeError: If both attachment and attachments are specified.
  • hikari.errors.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; reply not found or not in the same channel; too many components.
  • hikari.errors.UnauthorizedError: If you are unauthorized to make the request (invalid/missing token).
  • hikari.errors.ForbiddenError: If you are missing the SEND_MESSAGES in the channel or the person you are trying to message has the DM's disabled.
  • hikari.errors.NotFoundError: If the user 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.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.
#  
@typing.final
class TeamMembershipState(builtins.int, hikari.internal.enums.Enum):
View Source
@typing.final
class TeamMembershipState(int, enums.Enum):
    """Represents the state of a user's team membership."""

    INVITED = 1
    """Denotes the user has been invited to the team but has yet to accept."""

    ACCEPTED = 2
    """Denotes the user has accepted the invite and is now a member."""

Represents the state of a user's team membership.

Variables and properties
#  ACCEPTED

Denotes the user has accepted the invite and is now a member.

#  INVITED

Denotes the user has been invited to the team but has yet to accept.

#  denominator

the denominator of a rational number in lowest terms

#  imag

the imaginary part of a complex number

#  name: str

Return the name of the enum member as a str.

#  numerator

the numerator of a rational number in lowest terms

#  real

the real part of a complex number

#  value

Return the value of the enum member.

Methods
#  def __init__(cls, value: Any):
View Source
    def __call__(cls, value: typing.Any) -> typing.Any:
        """Cast a value to the enum, returning the raw value that was passed if value not found."""
        try:
            return cls._value_to_member_map_[value]
        except KeyError:
            # If we can't find the value, just return what got casted in
            return value

Cast a value to the enum, returning the raw value that was passed if value not found.

#  def as_integer_ratio(self, /):

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
#  def bit_length(self, /):

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
#  def conjugate(unknown):

Returns self, the complex conjugate of any int.

#  def from_bytes(type, /, bytes, byteorder, *, signed=False):

Return the integer represented by the given array of bytes.

bytes Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Indicates whether two's complement is used to represent the integer.

#  def to_bytes(self, /, length, byteorder, *, signed=False):

Return an array of bytes representing an integer.

length Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. byteorder The byte order used to represent the integer. If byteorder is 'big', the most significant byte is at the beginning of the byte array. If byteorder is 'little', the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder' as the byte order value. signed Determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

#  
@typing.final
class TokenType(builtins.str, hikari.internal.enums.Enum):
View Source
@typing.final
class TokenType(str, enums.Enum):
    """Token types used within Hikari clients."""

    BOT = "Bot"
    """Bot token type."""

    BASIC = "Basic"
    """OAuth2 basic token type."""

    BEARER = "Bearer"
    """OAuth2 bearer token type."""

Token types used within Hikari clients.

Variables and properties
#  BASIC

OAuth2 basic token type.

#  BEARER

OAuth2 bearer token type.

Bot token type.

#  name: str

Return the name of the enum member as a str.

#  value

Return the value of the enum member.

Methods
#  def __init__(cls, value: Any):
View Source
    def __call__(cls, value: typing.Any) -> typing.Any:
        """Cast a value to the enum, returning the raw value that was passed if value not found."""
        try:
            return cls._value_to_member_map_[value]
        except KeyError:
            # If we can't find the value, just return what got casted in
            return value

Cast a value to the enum, returning the raw value that was passed if value not found.

#  def capitalize(self, /):

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

#  def casefold(self, /):

Return a version of the string suitable for caseless comparisons.

#  def center(self, width, fillchar=' ', /):

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

#  def count(unknown):

S.count(sub[, start[, end]]) -> int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

#  def encode(self, /, encoding='utf-8', errors='strict'):

Encode the string using the codec registered for encoding.

encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

#  def endswith(unknown):

S.endswith(suffix[, start[, end]]) -> bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

#  def expandtabs(self, /, tabsize=8):

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

#  def find(unknown):

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

#  def format(unknown):

S.format(args, *kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').

#  def format_map(unknown):

S.format_map(mapping) -> str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').

#  def index(unknown):

S.index(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

#  def isalnum(self, /):

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

#  def isalpha(self, /):

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

#  def isascii(self, /):

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

#  def isdecimal(self, /):

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

#  def isdigit(self, /):

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

#  def isidentifier(self, /):

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as "def" or "class".

#  def islower(self, /):

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

#  def isnumeric(self, /):

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

#  def isprintable(self, /):

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

#  def isspace(self, /):

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

#  def istitle(self, /):

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

#  def isupper(self, /):

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

#  def join(self, iterable, /):

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'

#  def ljust(self, width, fillchar=' ', /):

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

#  def lower(self, /):

Return a copy of the string converted to lowercase.

#  def lstrip(self, chars=None, /):

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

#  def maketrans(unknown):

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

#  def partition(self, sep, /):

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

#  def removeprefix(self, prefix, /):

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

#  def removesuffix(self, suffix, /):

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

#  def replace(self, old, new, count=-1, /):

Return a copy with all occurrences of substring old replaced by new.

count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

#  def rfind(unknown):

S.rfind(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

#  def rindex(unknown):

S.rindex(sub[, start[, end]]) -> int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

#  def rjust(self, width, fillchar=' ', /):

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

#  def rpartition(self, sep, /):

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

#  def rsplit(self, /, sep=None, maxsplit=-1):

Return a list of the words in the string, using sep as the delimiter string.

sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

Splits are done starting at the end of the string and working to the front.

#  def rstrip(self, chars=None, /):

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

#  def split(self, /, sep=None, maxsplit=-1):

Return a list of the words in the string, using sep as the delimiter string.

sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

#  def splitlines(self, /, keepends=False):

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

#  def startswith(unknown):

S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

#  def strip(self, chars=None, /):

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

#  def swapcase(self, /):

Convert uppercase characters to lowercase and lowercase characters to uppercase.

#  def title(self, /):

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

#  def translate(self, table, /):

Replace each character in the string using the given translation table.

table Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

#  def upper(self, /):

Return a copy of the string converted to uppercase.

#  def zfill(self, width, /):

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

#  def get_token_id(token: str) -> hikari.snowflakes.Snowflake:
View Source
def get_token_id(token: str) -> snowflakes.Snowflake:
    """Try to get the bot ID stored in a token.

    Returns
    -------
    hikari.snowflakes.Snowflake
        The ID that was extracted from the token.

    Raises
    ------
    ValueError
        If the passed token has an unexpected format.
    """
    try:
        segment = token.split(".", 1)[0]
        # I don't trust Discord to always provide the right amount of padding here as they don't
        # with the middle field so just to be safe we will add padding here if necessary to avoid
        # base64.b64decode raising a length or padding error.
        segment += "=" * (len(segment) % 4)
        return snowflakes.Snowflake(base64.b64decode(segment))

    except (TypeError, ValueError, IndexError) as exc:
        raise ValueError("Unexpected token format") from exc

Try to get the bot ID stored in a token.

Returns
Raises
  • ValueError: If the passed token has an unexpected format.