Application and entities related to discord's OAuth2 flow.

This module

Expand source code
Browse git
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Application and entities related to discord's OAuth2 flow."""

from __future__ import annotations

__all__: typing.List[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)
    """`builtins.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)
    """`builtins.True` if the connection has been verified."""

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

    is_activity_visible: bool = attr.field(eq=False, hash=False, repr=False)
    """`builtins.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)
    """`builtins.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 `builtins.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 `builtins.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]:
        """Team icon URL.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `builtins.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 : builtins.str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : builtins.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 `builtins.None` if no icon exists.

        Raises
        ------
        builtins.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.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `builtins.None` if no cover image exists.
        """
        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 : builtins.str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : builtins.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 `builtins.None` if no cover image exists.

        Raises
        ------
        builtins.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)
    """`builtins.True` if the bot associated with this application is public."""

    is_bot_code_grant_required: bool = attr.field(eq=False, hash=False, repr=False)
    """`builtins.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 `builtins.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.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `builtins.None` if no cover image exists.
        """
        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 : builtins.str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : builtins.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 `builtins.None` if no cover image exists.

        Raises
        ------
        builtins.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)
    """`builtins.True` if the bot associated with this application is public.

    Will be `builtins.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)
    """`builtins.True` if this application's bot is requiring code grant for invites.

    Will be `builtins.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 `builtins.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 `builtins.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
    ------
    builtins.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

Functions

def get_token_id(
    token: str,
) -> Snowflake: ...

Try to get the bot ID stored in a token.

Returns

Snowflake
The ID that was extracted from the token.

Raises

ValueError
If the passed token has an unexpected format.
Expand source code
Browse git
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
    ------
    builtins.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

Classes

dataclass Application

class Application (
    *,
    id: snowflakes.Snowflake,
    name: str,
    description: Optional[str],
    icon_hash: Optional[str],
    app: traits.RESTAware,
    is_bot_public: bool,
    is_bot_code_grant_required: bool,
    owner: users.User,
    rpc_origins: Optional[Sequence[str]],
    flags: ApplicationFlags,
    public_key: bytes,
    team: Optional[Team],
    cover_image_hash: Optional[str],
    terms_of_service_url: Optional[str],
    privacy_policy_url: Optional[str],
): ...

Represents the information of an Oauth2 Application.

Method generated by attrs for class Application.

Expand source code
Browse git
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)
    """`builtins.True` if the bot associated with this application is public."""

    is_bot_code_grant_required: bool = attr.field(eq=False, hash=False, repr=False)
    """`builtins.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 `builtins.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.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `builtins.None` if no cover image exists.
        """
        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 : builtins.str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : builtins.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 `builtins.None` if no cover image exists.

        Raises
        ------
        builtins.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,
        )
Method resolution order
dataclass Application
That's this class!
dataclass PartialApplication

A partial representation of a Discord application …

abstract class Unique

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

extern class abc.ABC

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

Variables and properties
property apptraits.RESTAware

The client application that models may use for procedures.

property cover_image_hashOptional[str]

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

property cover_image_urlOptional[files.URL]

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

Returns

Optional[URL]
The URL, or None if no cover image exists.
property created_atdatetime.datetime

When the object was created.

property descriptionOptional[str]

The description of this application, if any.

property flagsApplicationFlags

The flags for this application.

property icon_hashOptional[str]

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

property icon_urlOptional[files.URL]

Team icon URL, if there is one.

Returns

Optional[URL]
The URL, or None if no icon exists.
property idsnowflakes.Snowflake

The ID of this entity.

property is_bot_code_grant_requiredbool

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

property is_bot_publicbool

True if the bot associated with this application is public.

property namestr

The name of this application.

property ownerusers.User

The application's owner.

property privacy_policy_urlOptional[str]

The URL of this application's privacy policy.

property public_keybytes

The key used for verifying interaction and GameSDK payload signatures.

property rpc_originsOptional[Sequence[str]]

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

property teamOptional[Team]

The team this application belongs to.

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

property terms_of_service_urlOptional[str]

The URL of this application's terms of service.

Methods
def make_cover_image_url(
    *,
    ext: str = 'png',
    size: int = 4096,
) -> 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

Optional[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).
Expand source code
Browse git
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 : builtins.str
        The extension to use for this URL, defaults to `png`.
        Supports `png`, `jpeg`, `jpg` and `webp`.
    size : builtins.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 `builtins.None` if no cover image exists.

    Raises
    ------
    builtins.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,
    )
def make_icon_url(
    *,
    ext: str = 'png',
    size: int = 4096,
) -> Optional[files.URL]: ...

Inherited from: PartialApplication.make_icon_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

Optional[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).

enum flag ApplicationFlags

class ApplicationFlags (
    value: int = 0,
): ...

The known application flag bits.

Expand source code
Browse git
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."""
Method resolution order
enum flag ApplicationFlags
That's this class!
extern class int

int([x]) -> integer int(x, base=10) -> integer …

enum flag Flag

Clone of Python's enum.Flag implementation …

Variables and properties
property namestr

Return the name of the flag combination as a str.

property valueint

Return the int value of the flag.

const EMBEDDED = 131072

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

const GUILD_MEMBERS_INTENT = 32768

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

const GUILD_PRESENCES_INTENT = 8192

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

const MESSAGE_CONTENT_INTENT = 262144

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

const MESSAGE_CONTENT_INTENT_LIMITED = 524288

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

const VERIFICATION_PENDING_GUILD_LIMIT = 65536

Denotes that the application's verification is pending.

const VERIFIED_FOR_GUILD_MEMBERS_INTENT = 16384

Denotes that a verified application can use the GUILD_MEMBERS intent.

const VERIFIED_FOR_GUILD_PRESENCES = 4096

Denotes that a verified application can use the GUILD_PRESENCES intent.

Methods
def all(
    self: _T,
    *flags: _T,
) -> bool: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.all. Visit that link to view the full documentation!
def any(
    self: _T,
    *flags: _T,
) -> bool: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.any. Visit that link to view the full documentation!
def difference(
    self: _T,
    other: Union[_T, int],
) -> ~_T: ...

Perform a set difference with the other set …

This function is defined explicitly at hikari.internal.enums.Flag.difference. Visit that link to view the full documentation!
def intersection(
    self: _T,
    other: Union[_T, int],
) -> ~_T: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.intersection. Visit that link to view the full documentation!
def invert(
    self: _T,
) -> ~_T: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.invert. Visit that link to view the full documentation!
def is_disjoint(
    self: _T,
    other: Union[_T, int],
) -> bool: ...

Return whether two sets have a intersection or not …

This function is defined explicitly at hikari.internal.enums.Flag.is_disjoint. Visit that link to view the full documentation!
def is_subset(
    self: _T,
    other: Union[_T, int],
) -> bool: ...

Return whether another set contains this set or not …

This function is defined explicitly at hikari.internal.enums.Flag.is_subset. Visit that link to view the full documentation!
def is_superset(
    self: _T,
    other: Union[_T, int],
) -> bool: ...

Return whether this set contains another set or not.

This function is defined explicitly at hikari.internal.enums.Flag.is_superset. Visit that link to view the full documentation!
def isdisjoint(
    self: _T,
    other: Union[_T, int],
) -> bool: ...

Return whether two sets have a intersection or not …

This function is defined explicitly at hikari.internal.enums.Flag.is_disjoint. Visit that link to view the full documentation!
def issubset(
    self: _T,
    other: Union[_T, int],
) -> bool: ...

Return whether another set contains this set or not …

This function is defined explicitly at hikari.internal.enums.Flag.is_subset. Visit that link to view the full documentation!
def issuperset(
    self: _T,
    other: Union[_T, int],
) -> bool: ...

Return whether this set contains another set or not.

This function is defined explicitly at hikari.internal.enums.Flag.is_superset. Visit that link to view the full documentation!
def none(
    self: _T,
    *flags: _T,
) -> bool: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.none. Visit that link to view the full documentation!
def split(
    self: _T,
) -> Sequence[~_T]: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.split. Visit that link to view the full documentation!
def symmetric_difference(
    self: _T,
    other: Union[_T, int],
) -> ~_T: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.symmetric_difference. Visit that link to view the full documentation!
def symmetricdifference(
    self: _T,
    other: Union[_T, int],
) -> ~_T: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.symmetric_difference. Visit that link to view the full documentation!
def union(
    self: _T,
    other: Union[_T, int],
) -> ~_T: ...

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

This function is defined explicitly at hikari.internal.enums.Flag.union. Visit that link to view the full documentation!

dataclass AuthorizationApplication

class AuthorizationApplication (
    *,
    id: 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],
): ...

The application model found attached to AuthorizationInformation.

Method generated by attrs for class AuthorizationApplication.

Expand source code
Browse git
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)
    """`builtins.True` if the bot associated with this application is public.

    Will be `builtins.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)
    """`builtins.True` if this application's bot is requiring code grant for invites.

    Will be `builtins.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."""
Method resolution order
dataclass AuthorizationApplication
That's this class!
dataclass PartialApplication

A partial representation of a Discord application …

abstract class Unique

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

extern class abc.ABC

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

Variables and properties
property created_atdatetime.datetime

When the object was created.

property description : Optional[str]

The description of this application, if any.

property icon_hash : Optional[str]

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

property icon_urlOptional[files.URL]

Team icon URL, if there is one.

Returns

Optional[URL]
The URL, or None if no icon exists.
property idSnowflake

The ID of this entity.

property 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.

property 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.

property namestr

The name of this application.

property privacy_policy_url : Optional[str]

The URL of this application's privacy policy.

property public_keybytes

The key used for verifying interaction and GameSDK payload signatures.

property terms_of_service_url : Optional[str]

The URL of this application's terms of service.

Methods
def make_icon_url(
    *,
    ext: str = 'png',
    size: int = 4096,
) -> Optional[files.URL]: ...

Inherited from: PartialApplication.make_icon_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

Optional[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).

dataclass AuthorizationInformation

class AuthorizationInformation (
    *,
    application: AuthorizationApplication,
    expires_at: datetime.datetime,
    scopes: Sequence[Union[OAuth2Scopestr]],
    user: Optional[users.User],
): ...

Model for the data returned by Get Current Authorization Information.

Method generated by attrs for class AuthorizationInformation.

Expand source code
Browse git
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."""
Variables and properties
property applicationAuthorizationApplication

The current application.

property expires_atdatetime.datetime

When the access token this data was retrieved with expires.

property scopesSequence[Union[OAuth2Scope, str]]

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

property userOptional[users.User]

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

enum ConnectionVisibility

class ConnectionVisibility (
    value: Any,
): ...

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

Expand source code
Browse git
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."""
Method resolution order
enum ConnectionVisibility
That's this class!
extern class int

int([x]) -> integer int(x, base=10) -> integer …

enum Enum

Clone of Python's enum.Enum implementation …

Variables and properties
property namestr

Return the name of the enum member as a str.

property value

Return the value of the enum member.

const EVERYONE = 1

Everyone can see the connection.

const NONE = 0

Implies that only you can see the corresponding connection.

dataclass InviteApplication

class InviteApplication (
    *,
    id: snowflakes.Snowflake,
    name: str,
    description: Optional[str],
    icon_hash: Optional[str],
    app: traits.RESTAware,
    cover_image_hash: Optional[str],
    public_key: bytes,
): ...

Represents the information of an Invite Application.

Method generated by attrs for class InviteApplication.

Expand source code
Browse git
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.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `builtins.None` if no cover image exists.
        """
        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 : builtins.str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : builtins.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 `builtins.None` if no cover image exists.

        Raises
        ------
        builtins.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,
        )
Method resolution order
dataclass InviteApplication
That's this class!
dataclass PartialApplication

A partial representation of a Discord application …

abstract class Unique

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

extern class abc.ABC

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

Variables and properties
property apptraits.RESTAware

The client application that models may use for procedures.

property cover_image_hashOptional[str]

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

property cover_image_urlOptional[files.URL]

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

Returns

Optional[URL]
The URL, or None if no cover image exists.
property created_atdatetime.datetime

When the object was created.

property descriptionOptional[str]

The description of this application, if any.

property icon_hashOptional[str]

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

property icon_urlOptional[files.URL]

Team icon URL, if there is one.

Returns

Optional[URL]
The URL, or None if no icon exists.
property idsnowflakes.Snowflake

The ID of this entity.

property namestr

The name of this application.

property public_keybytes

The key used for verifying interaction and GameSDK payload signatures.

Methods
def make_cover_image_url(
    *,
    ext: str = 'png',
    size: int = 4096,
) -> 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

Optional[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).
Expand source code
Browse git
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 : builtins.str
        The extension to use for this URL, defaults to `png`.
        Supports `png`, `jpeg`, `jpg` and `webp`.
    size : builtins.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 `builtins.None` if no cover image exists.

    Raises
    ------
    builtins.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,
    )
def make_icon_url(
    *,
    ext: str = 'png',
    size: int = 4096,
) -> Optional[files.URL]: ...

Inherited from: PartialApplication.make_icon_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

Optional[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).

dataclass OAuth2AuthorizationToken

class OAuth2AuthorizationToken (
    *,
    access_token: str,
    token_type: Union[TokenTypestr],
    expires_in: datetime.timedelta,
    scopes: Sequence[Union[OAuth2Scopestr]],
    refresh_token: int,
    webhook: Optional[webhooks.IncomingWebhook],
    guild: Optional[guilds.RESTGuild],
): ...

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

Method generated by attrs for class OAuth2AuthorizationToken.

Expand source code
Browse git
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 `builtins.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 `builtins.None`.
    """
Method resolution order
dataclass OAuth2AuthorizationToken
That's this class!
dataclass PartialOAuth2Token

Model for partial OAuth2 token data returned by the API …

Variables and properties
property access_tokenstr

Access token issued by the authorization server.

property expires_indatetime.timedelta

Lifetime of this access token.

property guildOptional[guilds.RESTGuild]

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.

property refresh_tokenint

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

property scopesSequence[Union[OAuth2Scope, str]]

Scopes the access token has access to.

property token_typeUnion[TokenType, str]

Type of token issued by the authorization server.

property webhookOptional[webhooks.IncomingWebhook]

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.

dataclass OAuth2ImplicitToken

class OAuth2ImplicitToken (
    *,
    access_token: str,
    token_type: Union[TokenTypestr],
    expires_in: datetime.timedelta,
    scopes: Sequence[Union[OAuth2Scopestr]],
    state: Optional[str],
): ...

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

Method generated by attrs for class OAuth2ImplicitToken.

Expand source code
Browse git
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."""
Method resolution order
dataclass OAuth2ImplicitToken
That's this class!
dataclass PartialOAuth2Token

Model for partial OAuth2 token data returned by the API …

Variables and properties
property access_tokenstr

Access token issued by the authorization server.

property expires_indatetime.timedelta

Lifetime of this access token.

property scopesSequence[Union[OAuth2Scope, str]]

Scopes the access token has access to.

property stateOptional[str]

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

property token_typeUnion[TokenType, str]

Type of token issued by the authorization server.

enum OAuth2Scope

class OAuth2Scope (
    value: Any,
): ...

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.

Expand source code
Browse git
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."""
Method resolution order
enum OAuth2Scope
That's this class!
extern class str

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str …

enum Enum

Clone of Python's enum.Enum implementation …

Variables and properties
property namestr

Return the name of the enum member as a str.

property value

Return the value of the enum member.

const ACTIVITIES_READ = 'activities.read'

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

Note

You must be whitelisted to use this scope.

const 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.

const APPLICATIONS_BUILDS_READ = 'applications.builds.read'

Enables reading build data for a user's applications.

Note

You must be whitelisted to use this scope.

const APPLICATIONS_BUILDS_UPLOAD = 'applications.builds.upload'

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

Note

You must be whitelisted to use this scope.

const 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 BOT in-order to join an application into a guild as an application command providing integration.

const APPLICATIONS_COMMANDS_UPDATE = 'applications.commands.update'

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

const APPLICATIONS_ENTITLEMENTS = 'applications.entitlements'

Enables reading entitlements for a user's applications.

const 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.

const BOT = 'bot'

Enables adding a bot application to a guild.

Note

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

const CONNECTIONS = 'connections'

Enables viewing third-party linked accounts such as Twitch.

const EMAIL = 'email'

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

const GROUP_DM_JOIN = 'gdm.join'

Enables joining users into a group DM.

Warning

This cannot add the bot to a group DM.

const GUILDS = 'guilds'

Enables viewing the guilds the user is in.

const 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.

const GUILDS_MEMBERS_READ = 'guilds.members.read'

Used to read the current user's guild members.

const IDENTIFY = 'identify'

Enables viewing info about itself.

Note

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

const RELATIONSHIPS_READ = 'relationships.read'

Enables viewing a user's friend list.

Note

You must be whitelisted to use this scope.

const RPC = 'rpc'

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

Note

You must be whitelisted to use this scope.

const RPC_MESSAGES_READ = 'messages.read'

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

const 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.

const WEBHOOK_INCOMING = 'webhook.incoming'

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

This is used during authorization code grants.

dataclass OwnConnection

class OwnConnection (
    *,
    id: str,
    name: str,
    type: str,
    is_revoked: bool,
    integrations: Sequence[guilds.PartialIntegration],
    is_verified: bool,
    is_friend_sync_enabled: bool,
    is_activity_visible: bool,
    visibility: Union[ConnectionVisibilityint],
): ...

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

Returned by the GET Current User Connections endpoint.

Method generated by attrs for class OwnConnection.

Expand source code
Browse git
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)
    """`builtins.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)
    """`builtins.True` if the connection has been verified."""

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

    is_activity_visible: bool = attr.field(eq=False, hash=False, repr=False)
    """`builtins.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."""
Variables and properties
property idstr

The string ID of the third party connected account.

Warning

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

property integrations : Sequence[PartialIntegration]

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

property is_activity_visiblebool

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

property is_friend_sync_enabledbool

True if friends should be added based on this connection.

property is_revokedbool

True if the connection has been revoked.

property is_verifiedbool

True if the connection has been verified.

property namestr

The username of the connected account.

property typestr

The type of service this connection is for.

property visibility : Union[ConnectionVisibilityint]

The visibility of the connection.

dataclass OwnGuild

class OwnGuild (
    *,
    app: traits.RESTAware,
    id: snowflakes.Snowflake,
    icon_hash: Optional[str],
    name: str,
    features: Sequence[Union[strguilds.GuildFeature]],
    is_owner: bool,
    my_permissions: permissions_.Permissions,
): ...

Represents a user bound partial guild object.

Method generated by attrs for class OwnGuild.

Expand source code
Browse git
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)
    """`builtins.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."""
Method resolution order
dataclass OwnGuild
That's this class!
dataclass PartialGuild

Base object for any partial guild objects …

abstract class Unique

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

extern class abc.ABC

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

Variables and properties
property apptraits.RESTAware

The client application that models may use for procedures.

property created_atdatetime.datetime

When the object was created.

property featuresSequence[Union[str, guilds.GuildFeature]]

A list of the features in this guild.

property icon_hashOptional[str]

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

property icon_urlOptional[files.URL]

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

property idsnowflakes.Snowflake

The ID of this entity.

property is_ownerbool

True when the current user owns this guild.

property my_permissionspermissions_.Permissions

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

property namestr

The name of the guild.

property 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
async def ban(
    user: snowflakes.SnowflakeishOr[users.PartialUser],
    *,
    delete_message_days: undefined.UndefinedOr[int] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> None: ...

Inherited from: PartialGuild.ban

Ban the given user from this guild.

Parameters

user : Snowflakeish[PartialUser]
The user to ban from the guild

Other Parameters

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

Raises

BadRequestError
If any of the fields that are passed have an invalid value.
ForbiddenError
If you are missing the BAN_MEMBERS permission.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild or user are not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def create_category(
    name: str,
    *,
    position: undefined.UndefinedOr[int] = UNDEFINED,
    permission_overwrites: undefined.UndefinedOr[Sequence[channels_.PermissionOverwrite]] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> GuildCategory: ...

Inherited from: PartialGuild.create_category

Create a category in the guild.

Parameters

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

Other Parameters

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

Returns

GuildCategory
The created category.

Raises

BadRequestError
If any of the fields that are passed have an invalid value.
ForbiddenError
If you are missing the MANAGE_CHANNEL permission.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def create_news_channel(
    name: str,
    *,
    position: undefined.UndefinedOr[int] = UNDEFINED,
    topic: undefined.UndefinedOr[str] = UNDEFINED,
    nsfw: undefined.UndefinedOr[bool] = UNDEFINED,
    rate_limit_per_user: undefined.UndefinedOr[time.Intervalish] = UNDEFINED,
    permission_overwrites: undefined.UndefinedOr[Sequence[channels_.PermissionOverwrite]] = UNDEFINED,
    category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> GuildNewsChannel: ...

Inherited from: PartialGuild.create_news_channel

Create a news channel in the guild.

Parameters

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

Other Parameters

position : UndefinedOr[int]
If provided, the position of the channel (relative to the category, if any).
topic : UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
nsfw : UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
rate_limit_per_user : UndefinedOr[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 : UndefinedOr[Sequence[PermissionOverwrite]]
If provided, the permission overwrites for the channel.
category : UndefinedOr[SnowflakeishOr[GuildCategory]]
The category to create the channel under. This may be the object or the ID of an existing category.
reason : UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters.

Returns

GuildNewsChannel
The created channel.

Raises

BadRequestError
If any of the fields that are passed have an invalid value.
ForbiddenError
If you are missing the MANAGE_CHANNEL permission.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def create_stage_channel(
    name: str,
    *,
    position: undefined.UndefinedOr[int] = UNDEFINED,
    user_limit: undefined.UndefinedOr[int] = UNDEFINED,
    bitrate: undefined.UndefinedOr[int] = UNDEFINED,
    permission_overwrites: undefined.UndefinedOr[Sequence[channels_.PermissionOverwrite]] = UNDEFINED,
    region: undefined.UndefinedOr[Union[voices_.VoiceRegion, str]] = UNDEFINED,
    category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> channels_.GuildStageChannel: ...

Inherited from: PartialGuild.create_stage_channel

Create a stage channel in the guild.

Parameters

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

Other Parameters

position : UndefinedOr[int]
If provided, the position of the channel (relative to the category, if any).
user_limit : UndefinedOr[int]
If provided, the maximum users in the channel at once. Must be between 0 and 99 with 0 meaning no limit.
bitrate : UndefinedOr[int]
If provided, the bitrate for the channel. Must be between 8000 and 96000 or 8000 and 128000 for VIP servers.
permission_overwrites : UndefinedOr[Sequence[PermissionOverwrite]]
If provided, the permission overwrites for the channel.
region : UndefinedOr[Union[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 : UndefinedOr[SnowflakeishOr[GuildCategory]]
The category to create the channel under. This may be the object or the ID of an existing category.
reason : UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters.

Returns

GuildStageChannel
The created channel.

Raises

BadRequestError
If any of the fields that are passed have an invalid value.
ForbiddenError
If you are missing the MANAGE_CHANNEL permission.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def create_sticker(
    name: str,
    tag: str,
    image: files.Resourceish,
    *,
    description: undefined.UndefinedOr[str] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> stickers.GuildSticker: ...

Inherited from: PartialGuild.create_sticker

Create a sticker in a guild.

Parameters

name : str
The name for the sticker.
tag : str
The tag for the sticker.
image : Resourceish

The 320x320 image for the sticker. Maximum upload size is 500kb. This can be a still or an animated PNG or a Lottie.

Note

Lottie support is only available for verified and partnered servers.

Other Parameters

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

Returns

GuildSticker
The created sticker.

Raises

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.
ForbiddenError
If you are missing MANAGE_EMOJIS_AND_STICKERS in the server.
NotFoundError
If the guild is not found.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def create_text_channel(
    name: str,
    *,
    position: undefined.UndefinedOr[int] = UNDEFINED,
    topic: undefined.UndefinedOr[str] = UNDEFINED,
    nsfw: undefined.UndefinedOr[bool] = UNDEFINED,
    rate_limit_per_user: undefined.UndefinedOr[time.Intervalish] = UNDEFINED,
    permission_overwrites: undefined.UndefinedOr[Sequence[channels_.PermissionOverwrite]] = UNDEFINED,
    category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> GuildTextChannel: ...

Inherited from: PartialGuild.create_text_channel

Create a text channel in the guild.

Parameters

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

Other Parameters

position : UndefinedOr[int]
If provided, the position of the channel (relative to the category, if any).
topic : UndefinedOr[str]
If provided, the channels topic. Maximum 1024 characters.
nsfw : UndefinedOr[bool]
If provided, whether to mark the channel as NSFW.
rate_limit_per_user : UndefinedOr[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 : UndefinedOr[Sequence[PermissionOverwrite]]
If provided, the permission overwrites for the channel.
category : UndefinedOr[SnowflakeishOr[GuildCategory]]
The category to create the channel under. This may be the object or the ID of an existing category.
reason : UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters.

Returns

GuildTextChannel
The created channel.

Raises

BadRequestError
If any of the fields that are passed have an invalid value.
ForbiddenError
If you are missing the MANAGE_CHANNEL permission.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def create_voice_channel(
    name: str,
    *,
    position: undefined.UndefinedOr[int] = UNDEFINED,
    user_limit: undefined.UndefinedOr[int] = UNDEFINED,
    bitrate: undefined.UndefinedOr[int] = UNDEFINED,
    video_quality_mode: undefined.UndefinedOr[Union[channels_.VideoQualityMode, int]] = UNDEFINED,
    permission_overwrites: undefined.UndefinedOr[Sequence[channels_.PermissionOverwrite]] = UNDEFINED,
    region: undefined.UndefinedOr[Union[voices_.VoiceRegion, str]] = UNDEFINED,
    category: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildCategory]] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> channels_.GuildVoiceChannel: ...

Inherited from: PartialGuild.create_voice_channel

Create a voice channel in a guild.

Parameters

guild : SnowflakeishOr[PartialGuild]
The guild to create the channel in. This may be the object or the ID of an existing guild.
name : str
The channels name. Must be between 2 and 1000 characters.

Other Parameters

position : UndefinedOr[int]
If provided, the position of the channel (relative to the category, if any).
user_limit : UndefinedOr[int]
If provided, the maximum users in the channel at once. Must be between 0 and 99 with 0 meaning no limit.
bitrate : 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 : UndefinedOr[Union[VideoQualityMode, int]]
If provided, the new video quality mode for the channel.
permission_overwrites : UndefinedOr[Sequence[PermissionOverwrite]]
If provided, the permission overwrites for the channel.
region : UndefinedOr[Union[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 : UndefinedOr[SnowflakeishOr[GuildCategory]]
The category to create the channel under. This may be the object or the ID of an existing category.
reason : UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters.

Returns

GuildVoiceChannel
The created channel.

Raises

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

Inherited from: PartialGuild.delete_channel

Delete a channel in the guild.

Note

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

Parameters

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

Returns

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).
ForbiddenError
If you are missing the MANAGE_CHANNEL permission in the channel.
NotFoundError
If the channel is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.

Note

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

async def delete_sticker(
    sticker: snowflakes.SnowflakeishOr[stickers.PartialSticker],
    *,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> None: ...

Inherited from: PartialGuild.delete_sticker

Delete a sticker in a guild.

Parameters

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

Other Parameters

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

Raises

ForbiddenError
If you are missing MANAGE_EMOJIS_AND_STICKERS in the server.
NotFoundError
If the guild or the sticker are not found.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def edit(
    *,
    name: undefined.UndefinedOr[str] = UNDEFINED,
    verification_level: undefined.UndefinedOr[GuildVerificationLevel] = UNDEFINED,
    default_message_notifications: undefined.UndefinedOr[GuildMessageNotificationsLevel] = UNDEFINED,
    explicit_content_filter_level: undefined.UndefinedOr[GuildExplicitContentFilterLevel] = UNDEFINED,
    afk_channel: undefined.UndefinedOr[snowflakes.SnowflakeishOr[channels_.GuildVoiceChannel]] = UNDEFINED,
    afk_timeout: undefined.UndefinedOr[time.Intervalish] = UNDEFINED,
    icon: undefined.UndefinedNoneOr[files.Resourceish] = UNDEFINED,
    owner: undefined.UndefinedOr[snowflakes.SnowflakeishOr[users.PartialUser]] = UNDEFINED,
    splash: undefined.UndefinedNoneOr[files.Resourceish] = UNDEFINED,
    banner: undefined.UndefinedNoneOr[files.Resourceish] = UNDEFINED,
    system_channel: undefined.UndefinedNoneOr[snowflakes.SnowflakeishOr[channels_.GuildTextChannel]] = UNDEFINED,
    rules_channel: undefined.UndefinedNoneOr[snowflakes.SnowflakeishOr[channels_.GuildTextChannel]] = UNDEFINED,
    public_updates_channel: undefined.UndefinedNoneOr[snowflakes.SnowflakeishOr[channels_.GuildTextChannel]] = UNDEFINED,
    preferred_locale: undefined.UndefinedOr[Union[str, locales.Locale]] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> RESTGuild: ...

Inherited from: PartialGuild.edit

Edits the guild.

Parameters

name : UndefinedOr[str]
If provided, the new name for the guild.
verification_level : UndefinedOr[GuildVerificationLevel]
If provided, the new verification level.
default_message_notifications : UndefinedOr[GuildMessageNotificationsLevel]
If provided, the new default message notifications level.
explicit_content_filter_level : UndefinedOr[GuildExplicitContentFilterLevel]
If provided, the new explicit content filter level.
afk_channel : UndefinedOr[SnowflakeishOr[GuildVoiceChannel]]
If provided, the new afk channel. Requires afk_timeout to be set to work.
afk_timeout : UndefinedOr[Intervalish]
If provided, the new afk timeout.
icon : UndefinedOr[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 : UndefinedOr[SnowflakeishOr[PartialUser]]]

If provided, the new guild owner.

Warning

You need to be the owner of the server to use this.

splash : UndefinedNoneOr[Resourceish]
If provided, the new guild splash. Must be a 16:9 image and the guild must have the INVITE_SPLASH feature.
banner : UndefinedNoneOr[Resourceish]
If provided, the new guild banner. Must be a 16:9 image and the guild must have the BANNER feature.
system_channel : UndefinedNoneOr[SnowflakeishOr[GuildTextChannel]]
If provided, the new system channel.
rules_channel : UndefinedNoneOr[SnowflakeishOr[GuildTextChannel]]
If provided, the new rules channel.
public_updates_channel : UndefinedNoneOr[SnowflakeishOr[GuildTextChannel]]
If provided, the new public updates channel.
preferred_locale : UndefinedNoneOr[str]
If provided, the new preferred locale.
reason : UndefinedOr[str]
If provided, the reason that will be recorded in the audit logs. Maximum of 512 characters.

Returns

RESTGuild
The edited guild.

Raises

BadRequestError
If any of the fields that are passed have an invalid value. Or you are missing the
ForbiddenError
If you are missing the MANAGE_GUILD permission or if you tried to pass ownership without being the server owner.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
async def edit_sticker(
    sticker: snowflakes.SnowflakeishOr[stickers.PartialSticker],
    *,
    name: undefined.UndefinedOr[str] = UNDEFINED,
    description: undefined.UndefinedOr[str] = UNDEFINED,
    tag: undefined.UndefinedOr[str] = UNDEFINED,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> GuildSticker: ...

Inherited from: PartialGuild.edit_sticker

Edit a sticker in a guild.

Parameters

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

Other Parameters

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

Returns

GuildSticker
The edited sticker.

Raises

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

Inherited from: PartialGuild.fetch_emoji

Fetch an emoji from the guild.

Parameters

emoji : SnowflakeishOr[CustomEmoji]
The emoji to fetch. This can be a CustomEmoji or the ID of an existing emoji.

Returns

KnownCustomEmoji
The requested emoji.

Raises

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

Inherited from: PartialGuild.fetch_emojis

Fetch the emojis of the guild.

Returns

Sequence[KnownCustomEmoji]
The requested emojis.

Raises

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

Inherited from: PartialGuild.fetch_roles

Fetch the roles of the guild.

Returns

Sequence[Role]
The requested roles.

Raises

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

Inherited from: PartialGuild.fetch_self

Fetch the guild.

Returns

RESTGuild
The requested guild.

Raises

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

Inherited from: PartialGuild.fetch_sticker

Fetch a sticker from the guild.

Parameters

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

Returns

GuildSticker
The requested sticker.

Raises

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

Inherited from: PartialGuild.fetch_stickers

Fetch the stickers of the guild.

Returns

Sequence[GuildSticker]
The requested stickers.

Raises

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

Inherited from: PartialGuild.kick

Kicks the given user from this guild.

Parameters

user : Snowflakeish[PartialUser]
The user to kick from the guild

Other Parameters

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

Raises

BadRequestError
If any of the fields that are passed have an invalid value.
ForbiddenError
If you are missing the KICK_MEMBERS permission.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
NotFoundError
If the guild or user are not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
def make_icon_url(
    *,
    ext: Optional[str] = None,
    size: int = 4096,
) -> Optional[files.URL]: ...

Inherited from: PartialGuild.make_icon_url

Generate the guild's icon URL, if set.

Parameters

ext : 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

Optional[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(
    user: snowflakes.SnowflakeishOr[users.PartialUser],
    *,
    reason: undefined.UndefinedOr[str] = UNDEFINED,
) -> None: ...

Inherited from: PartialGuild.unban

Unban the given user from this guild.

Parameters

user : Snowflakeish[PartialUser]
The user to unban from the guild

Other Parameters

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

Raises

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

dataclass PartialOAuth2Token

class PartialOAuth2Token (
    *,
    access_token: str,
    token_type: Union[TokenTypestr],
    expires_in: datetime.timedelta,
    scopes: Sequence[Union[OAuth2Scopestr]],
): ...

Model for partial OAuth2 token data returned by the API.

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

Method generated by attrs for class PartialOAuth2Token.

Expand source code
Browse git
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
Subclasses
dataclass OAuth2AuthorizationToken

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

dataclass OAuth2ImplicitToken

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

Variables and properties
property access_tokenstr

Access token issued by the authorization server.

property expires_indatetime.timedelta

Lifetime of this access token.

property scopesSequence[Union[OAuth2Scope, str]]

Scopes the access token has access to.

property token_typeUnion[TokenType, str]

Type of token issued by the authorization server.

dataclass Team

class Team (
    *,
    app: traits.RESTAware,
    id: snowflakes.Snowflake,
    name: str,
    icon_hash: Optional[str],
    members: Mapping[snowflakes.SnowflakeTeamMember],
    owner_id: snowflakes.Snowflake,
): ...

Represents a development team, along with all its members.

Method generated by attrs for class Team.

Expand source code
Browse git
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 `builtins.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]:
        """Team icon URL.

        Returns
        -------
        typing.Optional[hikari.files.URL]
            The URL, or `builtins.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 : builtins.str
            The extension to use for this URL, defaults to `png`.
            Supports `png`, `jpeg`, `jpg` and `webp`.
        size : builtins.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 `builtins.None` if no icon exists.

        Raises
        ------
        builtins.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,
        )
Method resolution order
dataclass Team
That's this class!
abstract class Unique

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

extern class abc.ABC

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

Variables and properties
property apptraits.RESTAware

The client application that models may use for procedures.

property created_atdatetime.datetime

When the object was created.

property icon_hashOptional[str]

The CDN hash of this team's icon.

If no icon is provided, this will be None.

property icon_urlOptional[files.URL]

Team icon URL.

Returns

Optional[URL]
The URL, or None if no icon exists.
property idsnowflakes.Snowflake

The ID of this entity.

property membersMapping[snowflakes.Snowflake, TeamMember]

A mapping containing each member in this team.

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

property namestr

The name of this team.

property owner_idsnowflakes.Snowflake

The ID of this team's owner.

Methods
def make_icon_url(
    *,
    ext: str = 'png',
    size: int = 4096,
) -> 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

Optional[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).
Expand source code
Browse git
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 : builtins.str
        The extension to use for this URL, defaults to `png`.
        Supports `png`, `jpeg`, `jpg` and `webp`.
    size : builtins.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 `builtins.None` if no icon exists.

    Raises
    ------
    builtins.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,
    )

dataclass TeamMember

class TeamMember (
    *,
    membership_state: Union[TeamMembershipStateint],
    permissions: Sequence[str],
    team_id: snowflakes.Snowflake,
    user: users.User,
): ...

Represents a member of a Team.

Method generated by attrs for class TeamMember.

Expand source code
Browse git
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 `builtins.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
Method resolution order
dataclass TeamMember
That's this class!
abstract class User

Interface for any user-like object …

abstract class PartialUser

A partial interface for a user …

abstract class Unique

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

extern class abc.ABC

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

Variables and properties
property accent_colorOptional[colors.Color]

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

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

property accent_colourOptional[colors.Color]

Alias for the accent_color field.

property apptraits.RESTAware

Return the app that is bound to the user object.

property avatar_hash : Optional[str]

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

property avatar_urlOptional[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.

property banner_hash : Optional[str]

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

property banner_urlOptional[files.URL]

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

May be None if no custom banner is set.

property created_atdatetime.datetime

When the object was created.

property default_avatar_urlfiles.URL

Default avatar URL for this user.

property discriminatorstr

Discriminator for the user.

property display_avatar_urlfiles.URL

Display avatar URL for this user.

property flagsUserFlag

Flag bits that are set for the user.

property idSnowflake

Return the ID of this entity.

Returns

Snowflake
The snowflake ID of this object.
property is_botbool

True if this user is a bot account, False otherwise.

property is_systembool

True if this user is a system account, False otherwise.

property membership_state : Union[TeamMembershipStateint]

The state of this user's membership.

property mentionstr

Return a raw mention string for the given user.

Example

>>> some_user.mention
'<@123456789123456789>'

Returns

str
The mention string to use.
property 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.

property team_idSnowflake

The ID of the team this member belongs to.

property userUser

The user representation of this team member.

property usernamestr

Username for the user.

Methods
async def fetch_dm_channel() -> channels.DMChannel: ...

Inherited from: User.fetch_dm_channel

Fetch the DM channel for this user.

Returns

DMChannel
The requested channel.

Raises

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

Inherited from: User.fetch_self

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

Returns

User
The requested user object.

Raises

NotFoundError
If the user is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.
def make_avatar_url(
    *,
    ext: Optional[str] = None,
    size: int = 4096,
) -> Optional[files.URL]: ...

Inherited from: User.make_avatar_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 : 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

Optional[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(
    *,
    ext: Optional[str] = None,
    size: int = 4096,
) -> Optional[files.URL]: ...

Inherited from: User.make_banner_url

Generate the banner URL for this user, if set.

If no custom banner is set, this returns None.

Parameters

ext : 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

Optional[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(
    content: undefined.UndefinedOr[Any] = UNDEFINED,
    *,
    attachment: undefined.UndefinedOr[files.Resourceish] = UNDEFINED,
    attachments: undefined.UndefinedOr[Sequence[files.Resourceish]] = UNDEFINED,
    component: undefined.UndefinedOr[special_endpoints.ComponentBuilder] = UNDEFINED,
    components: undefined.UndefinedOr[Sequence[special_endpoints.ComponentBuilder]] = UNDEFINED,
    embed: undefined.UndefinedOr[embeds_.Embed] = UNDEFINED,
    embeds: undefined.UndefinedOr[Sequence[embeds_.Embed]] = UNDEFINED,
    tts: undefined.UndefinedOr[bool] = UNDEFINED,
    reply: undefined.UndefinedOr[snowflakes.SnowflakeishOr[messages.PartialMessage]] = UNDEFINED,
    mentions_everyone: undefined.UndefinedOr[bool] = UNDEFINED,
    mentions_reply: undefined.UndefinedOr[bool] = UNDEFINED,
    user_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[PartialUser], bool]] = UNDEFINED,
    role_mentions: undefined.UndefinedOr[Union[snowflakes.SnowflakeishSequence[guilds.PartialRole], bool]] = UNDEFINED,
) -> messages.Message: ...

Inherited from: User.send

Send a message to this user in DM's.

Parameters

content : UndefinedOr[Any]

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

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

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

Other Parameters

attachment : UndefinedOr[Resourceish],
If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.
attachments : UndefinedOr[Sequence[Resourceish]],
If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.
component : UndefinedOr[ComponentBuilder]
If provided, builder object of the component to include in this message.
components : UndefinedOr[Sequence[ComponentBuilder]]
If provided, a sequence of the component builder objects to include in this message.
embed : UndefinedOr[Embed]
If provided, the message embed.
embeds : UndefinedOr[Sequence[Embed]]
If provided, the message embeds.
tts : UndefinedOr[bool]
If provided, whether the message will be read out by a screen reader using Discord's TTS (text-to-speech) system.
reply : UndefinedOr[SnowflakeishOr[PartialMessage]]
If provided, the message to reply to.
mentions_everyone : UndefinedOr[bool]
If provided, whether the message should parse @everyone/@here mentions.
mentions_reply : 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 : UndefinedOr[Union[SnowflakeishSequence[PartialUser], bool]]
If provided, and True, all user mentions will be detected. If provided, and False, all user mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialUser derivatives to enforce mentioning specific users.
role_mentions : UndefinedOr[Union[SnowflakeishSequence[PartialRole], bool]]
If provided, and True, all role mentions will be detected. If provided, and False, all role mentions will be ignored if appearing in the message body. Alternatively this may be a collection of Snowflake, or PartialRole derivatives to enforce mentioning specific roles.

Note

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 WebResource such as URL, Attachment, 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 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 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).

Returns

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.
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.
UnauthorizedError
If you are unauthorized to make the request (invalid/missing token).
ForbiddenError
If you are missing the SEND_MESSAGES in the channel or the person you are trying to message has the DM's disabled.
NotFoundError
If the user is not found.
RateLimitTooLongError
Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.
RateLimitedError
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.
InternalServerError
If an internal error occurs on Discord while handling the request.

enum TeamMembershipState

class TeamMembershipState (
    value: Any,
): ...

Represents the state of a user's team membership.

Expand source code
Browse git
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."""
Method resolution order
enum TeamMembershipState
That's this class!
extern class int

int([x]) -> integer int(x, base=10) -> integer …

enum Enum

Clone of Python's enum.Enum implementation …

Variables and properties
property namestr

Return the name of the enum member as a str.

property value

Return the value of the enum member.

const ACCEPTED = 2

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

const INVITED = 1

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

enum TokenType

class TokenType (
    value: Any,
): ...

Token types used within Hikari clients.

Expand source code
Browse git
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."""
Method resolution order
enum TokenType
That's this class!
extern class str

str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str …

enum Enum

Clone of Python's enum.Enum implementation …

Variables and properties
property namestr

Return the name of the enum member as a str.

property value

Return the value of the enum member.

const BASIC = 'Basic'

OAuth2 basic token type.

const BEARER = 'Bearer'

OAuth2 bearer token type.

const BOT = 'Bot'

Bot token type.