Skip to content

tanjun.abc#

Interfaces of the objects and clients used within Tanjun.

AnyCheckSig module-attribute #

AnyCheckSig = _CheckSig['Context', Ellipsis]

Type hint of a check callback for any command type.

AnyHooks module-attribute #

AnyHooks = Hooks[Context]

Execution hooks for any context.

AutocompleteCallbackSig module-attribute #

AutocompleteCallbackSig = AutocompleteSig[_AutocompleteValueT]

Deprecated alias of tanjun.abc.AutocompleteSig.

AutocompleteSig module-attribute #

AutocompleteSig = _AutocompleteSig[_AutocompleteValueT, Ellipsis]

Type hint of the signature an autocomplete callback should have.

This represents the signature async def (tanjun.abc.AutocompleteContext, int | str | float) -> None where dependency injection is supported.

CheckSig module-attribute #

CheckSig = _CheckSig[_ContextT_contra, Ellipsis]

Type hint of a generic context check used with Tanjun commands.

This may be registered with a command, client or component to add a rule which decides whether it should execute for each context passed to it.

This represents the signatures def (tanjun.abc.Context, ...) -> bool | None and async def (tanjun.abc.Context, ...) -> bool | None where dependency injection is supported.

Check callbacks may either return False to indicate that the current command(s) don't match the context (without stopping execution) or raise tanjun.FailedCheck to indicate that command execution should be halted early and marked as not found.

CommandCallbackSig module-attribute #

CommandCallbackSig = collections.Callable[Ellipsis, _CoroT[None]]

Deprecated type hint used to represent any command callback.

ErrorHookSig module-attribute #

ErrorHookSig = _ErrorHookSig[_ContextT_contra, Ellipsis]

Type hint of the callback used as a unexpected command error hook.

This will be called whenever an unexpected Exception is raised during the execution stage of a command (ignoring tanjun.ParserError and expected tanjun.TanjunError subclasses).

This represents the signatures def (tanjun.abc.Context, Exception, ...) -> bool | None and async def (tanjun.abc.Context, Exception, ...) -> bool | None where dependency injection is supported.

True is returned to indicate that the exception should be suppressed and False is returned to indicate that the exception should be re-raised.

HookSig module-attribute #

HookSig = _HookSig[_ContextT_contra, Ellipsis]

Type hint of the callback used as a general command hook.

This represents the signatures def (tanjun.abc.Context, ...) -> None and async def (tanjun.abc.Context, ...) -> None where dependency injection is supported.

ListenerCallbackSig module-attribute #

ListenerCallbackSig = _ListenerCallbackSig[_EventT, Ellipsis]

Type hint of a hikari event manager callback.

This represents the signature async def (hikari.Event, ...) -> None where dependency injection is supported.

MenuCallbackSig module-attribute #

MenuCallbackSig = _ManuCallbackSig['MenuContext', _MenuValueT, Ellipsis]

Type hint of a context menu command callback.

This represents the signature async def (tanjun.abc.MenuContext, hikari.Message, ...) -> None or async def (tanjun.abc.MenuContext, hikari.InteractionMember, ...) -> None where dependency injection is supported.

MenuCommandCallbackSig module-attribute #

MenuCommandCallbackSig = MenuCallbackSig[_MenuValueT]

Deprecated alias of tanjun.abc.MenuCallbackSig.

MenuHooks module-attribute #

MenuHooks = Hooks[MenuContext]

Execution hooks for menu commands.

MessageCallbackSig module-attribute #

MessageCallbackSig = _CommandCallbackSig['MessageContext', Ellipsis]

Type hint of a message command callback.

This represents the signature async def (tanjun.abc.MessageContext, ...) -> None where dependency injection is supported.

MessageHooks module-attribute #

MessageHooks = Hooks[MessageContext]

Execution hooks for messages commands.

MetaEventSig module-attribute #

MetaEventSig = collections.Callable[Ellipsis, typing.Union[_CoroT[None], None]]

Type hint of a client callback.

The positional arguments this is guaranteed depend on the event name its being subscribed to (more information the standard client callbacks can be found at tanjun.abc.ClientCallbackNames) and may be either synchronous or asynchronous but must return None.

ParserHookSig module-attribute #

ParserHookSig = _ParserHookSig[_ContextT_contra, Ellipsis]

Type hint of the callback used as a command parser error hook.

This will be called whenever an parser ParserError is raised during the execution stage of a command.

This represents the signatures def (tanjun.abc.Context, tanjun.ParserError, ...) -> None and async def (tanjun.abc.Context, tanjun.ParserError, ...) -> None where dependency injection is supported.

Parser errors are always suppressed (unlike general errors).

SlashCallbackSig module-attribute #

SlashCallbackSig = _CommandCallbackSig['SlashContext', Ellipsis]

Type hint of a slash command callback.

This represents the signature async def (tanjun.abc.SlashContext, ...) -> None where dependency injection is supported.

SlashHooks module-attribute #

SlashHooks = Hooks[SlashContext]

Execution hooks for slash commands.

AppCommand #

Bases: ExecutableCommand[_AppCommandContextT]

Base class for all application command classes.

default_member_permissions property abstractmethod #

default_member_permissions: typing.Optional[hikari.Permissions]

The default guild member permissions required to use this command.

Warning

This can be overridden by guild staff and does not apply to admins.

Warning

For commands within command groups the state of this flag is inherited regardless of what it's set as on the child command.

defaults_to_ephemeral property abstractmethod #

defaults_to_ephemeral: typing.Optional[bool]

Whether contexts executed by this command should default to ephemeral responses.

This effects calls to [tanjun.abc.SlashContext.create_followup][], [tanjun.abc.SlashContext.create_initial_response][], [tanjun.abc.SlashContext.defer][] and [tanjun.abc.SlashContext.respond][] unless the flags field is provided for the methods which support it.

Note

If this is None then the default from the parent command(s), component or client is used.

is_dm_enabled property abstractmethod #

is_dm_enabled: typing.Optional[bool]

Whether this command is enabled in DM contexts.

Note

If this is None then the default from the parent component or client is used.

Warning

For commands within command groups the state of this flag is inherited regardless of what it's set as on the child command.

is_global property abstractmethod #

is_global: bool

Whether the command should be declared globally or not.

Warning

For commands within command groups the state of this flag is inherited regardless of what it's set as on the child command.

name property abstractmethod #

name: str

Name of the command.

tracked_command property abstractmethod #

tracked_command: typing.Optional[hikari.PartialCommand]

Object of the actual command this object tracks if set.

tracked_command_id property abstractmethod #

tracked_command_id: typing.Optional[hikari.Snowflake]

ID of the actual command this object tracks if set.

type property abstractmethod #

type: hikari.CommandType

The type of this application command.

build abstractmethod #

build(*, component=None)

Get a builder object for this command.

PARAMETER DESCRIPTION
component

The component to inherit config like default_member_permissions and is_dm_enabled from if not explicitly set on the command.

This defaults to the command's linked component.

TYPE: typing.Optional[Component] DEFAULT: None

RETURNS DESCRIPTION
hikari.api.CommandBuilder

A builder object for this command. Use to declare this command on globally or for a specific guild.

set_tracked_command abstractmethod #

set_tracked_command(command)

Set the global command this tracks.

PARAMETER DESCRIPTION
command

Object of the global command this tracks.

TYPE: hikari.PartialCommand

RETURNS DESCRIPTION
Self

The command instance to enable chained calls.

AppCommandContext #

Bases: Context, abc.ABC

Base class for application command contexts.

defaults_to_ephemeral property abstractmethod #

defaults_to_ephemeral: bool

Whether the context is marked as defaulting to ephemeral response.

This effects calls to [tanjun.abc.SlashContext.create_followup][], [tanjun.abc.SlashContext.create_initial_response][], [tanjun.abc.SlashContext.defer][] and [tanjun.abc.SlashContext.respond][] unless the flags field is provided for the methods which support it.

expires_at property abstractmethod #

expires_at: datetime.datetime

When this application command context expires.

After this time is reached, the message/response methods on this context will always raise hikari.errors.NotFoundError.

has_been_deferred property abstractmethod #

has_been_deferred: bool

Whether the initial response for this context has been deferred.

Warning

If this is True when [tanjun.abc.SlashContext.has_responded][] is False then [tanjun.abc.SlashContext.edit_initial_response][] will need to be used to create the initial response rather than [tanjun.abc.SlashContext.create_initial_response][].

interaction property abstractmethod #

interaction: hikari.CommandInteraction

Interaction this context is for.

member property abstractmethod #

member: typing.Optional[hikari.InteractionMember]

Object of the member that triggered this command if this is in a guild.

type property abstractmethod #

type: hikari.CommandType

Type of application command this context is for.

create_followup abstractmethod async #

create_followup(content=hikari.UNDEFINED, *, delete_after=None, ephemeral=False, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED, tts=hikari.UNDEFINED, flags=hikari.UNDEFINED)

Create a followup response for this context.

Warning

Calling this on a context which hasn't had an initial response yet will lead to a hikari.errors.NotFoundError being raised.

PARAMETER DESCRIPTION
content

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

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

delete_after

If provided, the seconds after which the response message should be deleted.

Slash command responses can only be deleted within 15 minutes of the command being received.

TYPE: typing.Union[datetime.timedelta, float, int, None] DEFAULT: None

ephemeral

Whether the deferred response should be ephemeral.

Passing True here is a shorthand for including 1 << 64 in the passed flags.

TYPE: bool DEFAULT: False

attachment

If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.

TYPE: hikari.UndefinedOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Resourceish]] DEFAULT: hikari.UNDEFINED

component

If provided, builder object of the component to include in this message.

TYPE: hikari.UndefinedOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

If provided, a sequence of the component builder objects to include in this message.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

embed

If provided, the message embed.

TYPE: hikari.UndefinedOr[hikari.Embed] DEFAULT: hikari.UNDEFINED

embeds

If provided, the message embeds.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Embed]] DEFAULT: hikari.UNDEFINED

mentions_everyone

If provided, whether the message should parse @everyone/@here mentions.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

user_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialUser], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

role_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialRole], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

tts

If provided, whether the message will be sent as a TTS message.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

flags

The flags to set for this response.

As of writing this can only flag which can be provided is EPHEMERAL, other flags are just ignored.

TYPE: typing.Union[hikari.UndefinedType, int, hikari.MessageFlag] DEFAULT: hikari.UNDEFINED

RETURNS DESCRIPTION
hikari.Message

The created message object.

RAISES DESCRIPTION
hikari.NotFoundError

If the current interaction is not found or it hasn't had an initial response yet.

hikari.BadRequestError

This can be raised if the file is too large; if the embed exceeds the defined limits; if the message content is specified only and empty or greater than 2000 characters; if neither content, file or embeds are specified. If any invalid snowflake IDs are passed; a snowflake may be invalid due to it being outside of the range of a 64 bit integer.

ValueError

If more than 100 unique objects/entities are passed for role_mentions or `user_mentions.

If the interaction will have expired before delete_after is reached.

If both attachment and attachments are passed or both component and components are passed or both embed and embeds are passed.

create_initial_response abstractmethod async #

create_initial_response(content=hikari.UNDEFINED, *, delete_after=None, ephemeral=False, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED, flags=hikari.UNDEFINED, tts=hikari.UNDEFINED)

Create the initial response for this context.

Warning

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

PARAMETER DESCRIPTION
content

The content to edit the last response with.

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

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

delete_after

If provided, the seconds after which the response message should be deleted.

Slash command responses can only be deleted within 15 minutes of the command being received.

TYPE: typing.Union[datetime.timedelta, float, int, None] DEFAULT: None

ephemeral

Whether the deferred response should be ephemeral.

Passing True here is a shorthand for including 1 << 64 in the passed flags.

TYPE: bool DEFAULT: False

content

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

attachment

If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.

TYPE: hikari.UndefinedOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Resourceish]] DEFAULT: hikari.UNDEFINED

component

If provided, builder object of the component to include in this message.

TYPE: hikari.UndefinedOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

If provided, a sequence of the component builder objects to include in this message.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

embed

If provided, the message embed.

TYPE: hikari.UndefinedOr[hikari.Embed] DEFAULT: hikari.UNDEFINED

embeds

If provided, the message embeds.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Embed]] DEFAULT: hikari.UNDEFINED

flags

If provided, the message flags this response should have.

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

TYPE: typing.Union[int, hikari.MessageFlag, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

tts

If provided, whether the message will be read out by a screen reader using Discord's TTS (text-to-speech) system.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

mentions_everyone

If provided, whether the message should parse @everyone/@here mentions.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

user_mentions

If provided, and True, all user mentions will be detected. If provided, and False, all user mentions will be ignored if appearing in the message body.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialUser], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

role_mentions

If provided, and True, all role mentions will be detected. If provided, and False, all role mentions will be ignored if appearing in the message body.

Alternatively this may be a collection of [hikari.snowflakes.Snowflake], or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialRole], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

RAISES DESCRIPTION
ValueError

If more than 100 unique objects/entities are passed for role_mentions or user_mentions.

If the interaction will have expired before delete_after is reached.

If both attachment and attachments are passed or both component and components are passed or both embed and embeds are passed.

hikari.BadRequestError

This may be raised in several discrete situations, such as messages being empty with no embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; invalid image URLs in embeds.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.NotFoundError

If the interaction is not found or if the interaction's initial response has already been created.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

create_modal_response abstractmethod async #

create_modal_response(title, custom_id, /, *, component=hikari.UNDEFINED, components=hikari.UNDEFINED)

Send a modal as the initial response for this context.

Warning

This must be called as the first response to a context before any deferring.

PARAMETER DESCRIPTION
title

The title that will show up in the modal.

TYPE: str

custom_id

Developer set custom ID used for identifying interactions with this modal.

TYPE: str

component

A component builder to send in this modal.

TYPE: hikari.UndefinedOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

A sequence of component builders to send in this modal.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

RAISES DESCRIPTION
ValueError

If both component and components are specified or if none are specified.

hikari.BadRequestError

When the requests' data is outside Discord's accept ranges/validation.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.NotFoundError

If the interaction is not found or if the interaction's initial response has already been created or deferred.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

defer abstractmethod async #

defer(*, ephemeral=False, flags=hikari.UNDEFINED)

Defer the initial response for this context.

Note

The ephemeral state of the first response is decided by whether the deferral is ephemeral.

PARAMETER DESCRIPTION
ephemeral

Whether the deferred response should be ephemeral.

Passing True here is a shorthand for including 1 << 64 in the passed flags.

TYPE: bool DEFAULT: False

flags

The flags to use for the initial response.

TYPE: typing.Union[hikari.UndefinedType, int, hikari.MessageFlag] DEFAULT: hikari.UNDEFINED

mark_not_found abstractmethod async #

mark_not_found()

Mark this context as not found.

Dependent on how the client is configured this may lead to a not found response message being sent.

set_ephemeral_default abstractmethod #

set_ephemeral_default(state)

Set the ephemeral default state for this context.

PARAMETER DESCRIPTION
state

The new ephemeral default state.

If this is True then all calls to the response creating methods on this context will default to being ephemeral.

TYPE: bool

AutocompleteContext #

Bases: alluka.Context

Interface of an autocomplete context.

author property abstractmethod #

author: hikari.User

Object of the user who triggered this autocomplete.

cache property abstractmethod #

cache: typing.Optional[hikari.api.Cache]

Hikari cache instance this context's client was initialised with.

channel_id property abstractmethod #

channel_id: hikari.Snowflake

ID of the channel this autocomplete was triggered in.

client property abstractmethod #

client: Client

Tanjun tanjun.abc.Client implementation this context was spawned by.

created_at property abstractmethod #

created_at: datetime.datetime

When this context was created.

Note

This will either refer to a message or integration's creation date.

events property abstractmethod #

events: typing.Optional[hikari.api.EventManager]

Object of the event manager this context's client was initialised with.

focused property abstractmethod #

focused: hikari.AutocompleteInteractionOption

The option being autocompleted.

guild_id property abstractmethod #

guild_id: typing.Optional[hikari.Snowflake]

ID of the guild this autocomplete was triggered in.

Will be None for all DM autocomplete executions.

has_responded property abstractmethod #

has_responded: bool

Whether the choices have been set for this autocomplete.

interaction property abstractmethod #

interaction: hikari.AutocompleteInteraction

Interaction this context is for.

member property abstractmethod #

member: typing.Optional[hikari.Member]

Guild member object of this autocomplete's author.

Will be None for DM autocomplete executions.

options property abstractmethod #

options: collections.Mapping[str, hikari.AutocompleteInteractionOption]

Mapping of option names to the values provided for them.

rest property abstractmethod #

rest: hikari.api.RESTClient

Object of the Hikari REST client this context's client was initialised with.

server property abstractmethod #

server: typing.Optional[hikari.api.InteractionServer]

Object of the Hikari interaction server provided for this context's client.

shard property abstractmethod #

shard: typing.Optional[hikari.api.GatewayShard]

Shard that triggered the context.

Note

This will be None if tanjun.abc.AutocompleteContext.shards is also None.

shards property abstractmethod #

shards: typing.Optional[hikari.ShardAware]

Object of the Hikari shard manager this context's client was initialised with.

triggering_name property abstractmethod #

triggering_name: str

Full command name this autocomplete was triggered for.

voice property abstractmethod #

voice: typing.Optional[hikari.api.VoiceComponent]

Object of the Hikari voice component this context's client was initialised with.

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using tanjun.abc.AutocompleteContext.get_channel if you have hikari.api.config.CacheComponents.GUILD_CHANNELS cache component enabled.

RETURNS DESCRIPTION
hikari.TextableChannel

The textable DM or guild channel the context was invoked in.

RAISES DESCRIPTION
hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.ForbiddenError

If you are missing the READ_MESSAGES permission in the channel.

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using tanjun.abc.AutocompleteContext.get_guild if you have hikari.api.config.CacheComponents.GUILDS cache component enabled.

RETURNS DESCRIPTION
hikari.Guild | None

An optional guild the context was invoked in. None will be returned if the context was invoked in a DM channel.

RAISES DESCRIPTION
hikari.ForbiddenError

If you are not part of the guild.

hikari.NotFoundError

If the guild is not found.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

get_channel abstractmethod #

get_channel()

Retrieve the channel the context was invoked in from the cache.

Note

This method requires the hikari.api.config.CacheComponents.GUILD_CHANNELS cache component.

RETURNS DESCRIPTION
hikari.TextableGuildChannel | None

An optional guild channel the context was invoked in. None will be returned if the channel was not found or if it is DM channel.

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires hikari.api.config.CacheComponents.GUILDS cache component enabled.

RETURNS DESCRIPTION
hikari.Guild | None

An optional guild the context was invoked in. None will be returned if the guild was not found.

set_choices abstractmethod async #

set_choices(choices=Ellipsis, /, **kwargs)

Set the choices for this autocomplete.

Note

Only up to (and including) 25 choices may be set for an autocomplete.

PARAMETER DESCRIPTION
choices

Mapping of string option names to their values.

The values should match the focused option's relevant type.

TYPE: collections.abc.Mapping[str, str | float | int] DEFAULT: Ellipsis

**kwargs

Keyword arguments mapping string option names to their values.

The value should match the focused option's relevant type.

TYPE: str | float | int DEFAULT: {}

RAISES DESCRIPTION
RuntimeError

If the context has already had the choices set for it.

ValueError

If more than 25 choices are passed.

BaseSlashCommand #

Bases: AppCommand[SlashContext], abc.ABC

Base class for all slash command classes.

parent property abstractmethod #

parent: typing.Optional[SlashCommandGroup]

Object of the group this command is in.

tracked_command property abstractmethod #

tracked_command: typing.Optional[hikari.SlashCommand]

Object of the actual command this object tracks if set.

type property abstractmethod #

type: typing.Literal[hikari.CommandType.SLASH]

The type of this command.

build abstractmethod #

build(*, component=None)

Get a builder object for this command.

PARAMETER DESCRIPTION
component

The component to inherit config like default_member_permissions and is_dm_enabled from if not explicitly set on the command.

This defaults to the command's linked component.

TYPE: typing.Optional[Component] DEFAULT: None

RETURNS DESCRIPTION
hikari.api.SlashCommandBuilder

A builder object for this command. Use to declare this command on globally or for a specific guild.

copy abstractmethod #

copy(*, parent=None)

Create a copy of this command.

PARAMETER DESCRIPTION
parent

The parent of the copy.

TYPE: typing.Optional[SlashCommandGroup] DEFAULT: None

RETURNS DESCRIPTION
Self

The copy.

Client #

Bases: abc.ABC

Abstract interface of a Tanjun client.

This should manage both message and slash command execution based on the provided hikari clients.

cache property abstractmethod #

cache: typing.Optional[hikari.api.Cache]

Hikari cache instance this command client was initialised with.

components property abstractmethod #

components: collections.Collection[Component]

Collection of the components this command client is using.

default_app_cmd_permissions property abstractmethod #

default_app_cmd_permissions: hikari.Permissions

Default required guild member permissions for the commands in this client.

This may be overridden by tanjun.abc.Component.default_app_cmd_permissions and tanjun.abc.AppCommand.default_member_permissions; this defaults to no required permissions.

Warning

This may be overridden by guild staff and does not apply to admins.

defaults_to_ephemeral property abstractmethod #

defaults_to_ephemeral: bool

Whether slash contexts spawned by this client should default to ephemeral responses.

This effects calls to [tanjun.abc.SlashContext.create_followup][], [tanjun.abc.SlashContext.create_initial_response][], [tanjun.abc.SlashContext.defer][] and [tanjun.abc.SlashContext.respond][] unless the flags field is provided for the methods which support it.

This defaults to False.

Note

This may be overridden by tanjun.abc.AppCommand.defaults_to_ephemeral and tanjun.abc.Component.defaults_to_ephemeral and only effects slash command execution.

dms_enabled_for_app_cmds property abstractmethod #

dms_enabled_for_app_cmds: bool

Whether application commands in this client should be enabled in DMs by default.

This defaults to True.

events property abstractmethod #

events: typing.Optional[hikari.api.EventManager]

Object of the event manager this client was initialised with.

This is used for executing message commands if set.

injector property abstractmethod #

injector: alluka.Client

The attached alluka dependency injection client.

is_alive property abstractmethod #

is_alive: bool

Whether this client is alive.

is_case_sensitive property abstractmethod #

is_case_sensitive: bool

Whether this client should treat message command names case sensitive in search.

listeners property abstractmethod #

listeners: collections.Mapping[type[hikari.Event], collections.Collection[ListenerCallbackSig[typing.Any]]]

Mapping of event types to the listeners registered in this client.

loop property abstractmethod #

loop: typing.Optional[asyncio.AbstractEventLoop]

The loop this client is bound to if it's alive.

metadata property abstractmethod #

metadata: collections.MutableMapping[typing.Any, typing.Any]

Mutable mapping of the metadata set for this client.

Note

Any modifications made to this mutable mapping will be preserved by the client.

prefixes property abstractmethod #

prefixes: collections.Collection[str]

Collection of the prefixes set for this client.

These are only use during message command execution to match commands to this command client.

rest property abstractmethod #

rest: hikari.api.RESTClient

Object of the Hikari REST client this client was initialised with.

server property abstractmethod #

server: typing.Optional[hikari.api.InteractionServer]

Object of the Hikari interaction server provided for this client.

This is used for executing application commands if set.

shards property abstractmethod #

shards: typing.Optional[hikari.ShardAware]

Object of the Hikari shard manager this client was initialised with.

voice property abstractmethod #

voice: typing.Optional[hikari.api.VoiceComponent]

Object of the Hikari voice component this client was initialised with.

add_client_callback abstractmethod #

add_client_callback(name, /, *callbacks)

Add a client callback.

PARAMETER DESCRIPTION
name

The name this callback is being registered to.

This is case-insensitive.

TYPE: typing.Union[str, ClientCallbackNames]

*callbacks

The callbacks to register.

These may be sync or async and must return None. The positional and keyword arguments a callback should expect depend on implementation detail around the name being subscribed to.

TYPE: MetaEventSig DEFAULT: ()

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

add_component abstractmethod #

add_component(component)

Add a component to this client.

PARAMETER DESCRIPTION
component

The component to move to this client.

TYPE: Component

RETURNS DESCRIPTION
Self

The client instance to allow chained calls.

add_listener abstractmethod #

add_listener(event_type, /, *callbacks)

Add a listener to the client.

PARAMETER DESCRIPTION
event_type

The event type to add a listener for.

TYPE: type[hikari.events.base_events.Event]

*callbacks

The callbacks to register as a listener.

These callbacks must be coroutine functions which returns None and always takes one positional arg of the event type passed for event_type regardless of client implementation detail.

TYPE: ListenerCallbackSig[_EventT] DEFAULT: ()

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

check_message_name abstractmethod #

check_message_name(name, /, *, case_sensitive=True)

Check whether a message command name is present in the current client.

Note

Dependent on implementation this may partial check name against the message command's name based on command_name.startswith(name).

PARAMETER DESCRIPTION
name

The name to match commands against.

TYPE: str

case_sensitive

Whether to match case sensitively.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Iterator[tuple[str, MessageCommand]]

Iterator of the matched command names to the matched message command objects.

check_slash_name abstractmethod #

check_slash_name(name)

Check whether a slash command name is present in the current client.

Note

This won't check the commands within command groups.

PARAMETER DESCRIPTION
name

Name to check against.

TYPE: str

RETURNS DESCRIPTION
collections.abc.Iterator[BaseSlashCommand]

Iterator of the matched slash command objects.

clear_application_commands abstractmethod async #

clear_application_commands(*, application=None, guild=hikari.UNDEFINED)

Clear the commands declared either globally or for a specific guild.

Note

The endpoint this uses has a strict ratelimit which, as of writing, only allows for 2 requests per minute (with that ratelimit either being per-guild if targeting a specific guild otherwise globally).

PARAMETER DESCRIPTION
application

The application to clear commands for.

If left as None then this will be inferred from the authorization being used by tanjun.abc.Client.rest.

TYPE: typing.Optional[hikari.SnowflakeishOr[hikari.PartialApplication]] DEFAULT: None

guild

Object or ID of the guild to clear commands for.

If left as None global commands will be cleared.

TYPE: hikari.UndefinedOr[hikari.SnowflakeishOr[hikari.PartialGuild]] DEFAULT: hikari.UNDEFINED

declare_application_command abstractmethod async #

declare_application_command(command, /, command_id=None, *, application=None, guild=hikari.UNDEFINED)

Declare a single slash command for a bot.

Warning

Providing command_id when updating a command helps avoid any permissions set for the command being lose (e.g. when changing the command's name).

PARAMETER DESCRIPTION
command

The command to register.

TYPE: AppCommand[typing.Any]

application

The application to register the command with.

If left as None then this will be inferred from the authorization being used by tanjun.abc.Client.rest.

TYPE: typing.Optional[hikari.SnowflakeishOr[hikari.PartialApplication]] DEFAULT: None

command_id

ID of the command to update.

TYPE: typing.Optional[hikari.Snowflakeish] DEFAULT: None

guild

Object or ID of the guild to register the command with.

If left as None then the command will be registered globally.

TYPE: hikari.UndefinedOr[hikari.SnowflakeishOr[hikari.PartialGuild]] DEFAULT: hikari.UNDEFINED

RETURNS DESCRIPTION
hikari.PartialCommand

API representation of the command that was registered.

declare_application_commands abstractmethod async #

declare_application_commands(commands, /, command_ids=None, *, application=None, guild=hikari.UNDEFINED, message_ids=None, user_ids=None, force=False)

Declare a collection of slash commands for a bot.

Note

The endpoint this uses has a strict ratelimit which, as of writing, only allows for 2 requests per minute (with that ratelimit either being per-guild if targeting a specific guild otherwise globally).

PARAMETER DESCRIPTION
commands

Iterable of the commands objects or builders to register.

TYPE: collections.Iterable[typing.Union[AppCommand[typing.Any], hikari.api.CommandBuilder]]

command_ids

If provided, a mapping of top level command names to IDs of the existing commands to update.

This will be used for all application commands but in cases where commands have overlapping names, message_ids and user_ids will take priority over this for their relevant command type.

While optional, this can be helpful when updating commands as providing the current IDs will prevent changes such as renames from leading to other state set for commands (e.g. permissions) from being lost.

TYPE: typing.Optional[collections.Mapping[str, hikari.SnowflakeishOr[hikari.PartialCommand]]] DEFAULT: None

application

The application to register the commands with.

If left as None then this will be inferred from the authorization being used by tanjun.abc.Client.rest.

TYPE: typing.Optional[hikari.SnowflakeishOr[hikari.PartialApplication]] DEFAULT: None

guild

Object or ID of the guild to register the commands with.

If left as None then the commands will be registered globally.

TYPE: hikari.UndefinedOr[hikari.SnowflakeishOr[hikari.PartialGuild]] DEFAULT: hikari.UNDEFINED

message_ids

If provided, a mapping of message context menu command names to the IDs of existing commands to update.

TYPE: typing.Optional[collections.Mapping[str, hikari.SnowflakeishOr[hikari.PartialCommand]]] DEFAULT: None

user_ids

If provided, a mapping of user context menu command names to the IDs of existing commands to update.

TYPE: typing.Optional[collections.Mapping[str, hikari.SnowflakeishOr[hikari.PartialCommand]]] DEFAULT: None

force

Force this to declare the commands regardless of whether or not they match the current state of the declared commands.

The default behaviour helps avoid issues with the 2 request per minute (per-guild or globally) ratelimit and the other limit of only 200 application command creates per day (per guild or globally).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Sequence[hikari.PartialCommand]

API representations of the commands which were registered.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If conflicting command names are found (multiple commanbds have the same top-level name).
  • If more than 100 top-level commands are passed.

declare_global_commands abstractmethod async #

declare_global_commands(command_ids=None, *, application=None, guild=hikari.UNDEFINED, message_ids=None, user_ids=None, force=False)

Set the global application commands for a bot based on the loaded components.

Warning

This will overwrite any previously set application commands and only targets commands marked as global.

Note

The endpoint this uses has a strict ratelimit which, as of writing, only allows for 2 requests per minute (with that ratelimit either being per-guild if targeting a specific guild otherwise globally).

PARAMETER DESCRIPTION
command_ids

If provided, a mapping of top level command names to IDs of the existing commands to update.

This will be used for all application commands but in cases where commands have overlapping names, message_ids and user_ids will take priority over this for their relevant command type.

TYPE: typing.Optional[collections.Mapping[str, hikari.SnowflakeishOr[hikari.PartialCommand]]] DEFAULT: None

application

Object or ID of the application to set the global commands for.

If left as None then this will be inferred from the authorization being used by tanjun.abc.Client.rest.

TYPE: typing.Optional[hikari.SnowflakeishOr[hikari.PartialApplication]] DEFAULT: None

guild

Object or ID of the guild to set the global commands to.

If left as None global commands will be set.

TYPE: hikari.UndefinedOr[hikari.SnowflakeishOr[hikari.PartialGuild]] DEFAULT: hikari.UNDEFINED

message_ids

If provided, a mapping of message context menu command names to the IDs of existing commands to update.

TYPE: typing.Optional[collections.Mapping[str, hikari.SnowflakeishOr[hikari.PartialCommand]]] DEFAULT: None

user_ids

If provided, a mapping of user context menu command names to the IDs of existing commands to update.

TYPE: typing.Optional[collections.Mapping[str, hikari.SnowflakeishOr[hikari.PartialCommand]]] DEFAULT: None

force

Force this to declare the commands regardless of whether or not they match the current state of the declared commands.

The default behaviour helps avoid issues with the 2 request per minute (per-guild or globally) ratelimit and the other limit of only 200 application command creates per day (per guild or globally).

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Sequence[hikari.commands.PartialCommand]

API representations of the set commands.

dispatch_client_callback abstractmethod async #

dispatch_client_callback(name, /, *args)

Dispatch a client callback.

PARAMETER DESCRIPTION
name

The name of the callback to dispatch.

TYPE: typing.Union[str, ClientCallbackNames]

*args

Positional arguments to pass to the callback(s).

TYPE: typing.Any DEFAULT: ()

RAISES DESCRIPTION
KeyError

If no callbacks are registered for the given name.

get_callback_override abstractmethod #

get_callback_override(callback)

Get the override for a specific injected callback.

PARAMETER DESCRIPTION
callback

The injected callback to get the override for.

TYPE: alluka.CallbackSig[_T]

RETURNS DESCRIPTION
alluka.abc.CallbackSig | None

The override if found, else None.

get_client_callbacks abstractmethod #

get_client_callbacks(name)

Get a collection of the callbacks registered for a specific name.

PARAMETER DESCRIPTION
name

The name to get the callbacks registered for.

This is case-insensitive.

TYPE: typing.Union[str, ClientCallbackNames]

RETURNS DESCRIPTION
collections.abc.Collection[MetaEventSig]

Collection of the callbacks for the provided name.

get_component_by_name abstractmethod #

get_component_by_name(name)

Get a component from this client by name.

PARAMETER DESCRIPTION
name

Name to get a component by.

TYPE: str

RETURNS DESCRIPTION
Component | None

The component instance if found, else None.

get_type_dependency abstractmethod #

get_type_dependency(type_)

Get the implementation for an injected type.

PARAMETER DESCRIPTION
type_

The associated type.

TYPE: type[_T]

RETURNS DESCRIPTION
_T | alluka.abc.Undefined

The resolved type if found, else alluka.abc.UNDEFINED.

iter_commands abstractmethod #

iter_commands()

Iterate over all the commands (both message and slash) registered to this client.

RETURNS DESCRIPTION
collections.abc.Iterator[ExecutableCommand[Context]]

Iterator of all the commands registered to this client.

iter_menu_commands abstractmethod #

iter_menu_commands(*, global_only=False, type=None)

Iterator over the menu commands registered to this client.

PARAMETER DESCRIPTION
global_only

Whether to only iterate over global menu commands.

TYPE: bool DEFAULT: False

type

Menu command type to filter by.

TYPE: typing.Optional[hikari.CommandType] DEFAULT: None

RETURNS DESCRIPTION
collections.abc.Iterator[MenuCommand]

Iterator of the menu commands registered to this client.

iter_message_commands abstractmethod #

iter_message_commands()

Iterate over all the message commands registered to this client.

RETURNS DESCRIPTION
collections.abc.Iterator[MessageCommand]

Iterator of all the message commands registered to this client.

iter_slash_commands abstractmethod #

iter_slash_commands(*, global_only=False)

Iterate over all the slash commands registered to this client.

PARAMETER DESCRIPTION
global_only

Whether to only iterate over global slash commands.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Iterator[BaseSlashCommand]

Iterator of the slash commands registered to this client.

load_directory abstractmethod #

load_directory(directory, /, *, namespace=None)

Load entities into this client from the modules in a directory.

The same loading rules for tanjun.abc.Client.load_modules mostly apply here but modules with no loaders are quietly ignored.

PARAMETER DESCRIPTION
directory

Name of the directory to load modules from.

TYPE: typing.Union[str, pathlib.Path]

namespace

The python namespace this directory's modules should be imported from, if applicable.

This work as {namespace}.{file.name.removesuffix(".py")} and will have the same behaviour as when a str is passed to tanjun.abc.Client.load_modules if passed.

If left as None then this will have the same behaviour as when a pathlib.Path is passed to tanjun.abc.Client.load_modules.

TYPE: typing.Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Self

This client instance to enable chained calls.

RAISES DESCRIPTION
tanjun.FailedModuleLoad

If any of the modules in this directory failed to load.

This includes if it failed to import or if one of its loaders raised. The source error can be found at tanjun.FailedModuleLoad.cause.

Modules with no loaders are ignored.

ModuleNotFoundError

If any of the modules aren't found.

load_directory_async abstractmethod async #

load_directory_async(directory, /, *, namespace=None)

Asynchronous variant of tanjun.abc.Client.load_directory.

Unlike tanjun.abc.Client.load_directory, this method will run blocking code in a background thread.

For more information on the behaviour of this method see the documentation for tanjun.abc.Client.load_directory.

load_modules abstractmethod #

load_modules(*modules)

Load entities into this client from modules based on present loaders.

Note

If an __all__ is present in the target module then it will be used to find loaders.

Examples:

For this to work the target module has to have at least one loader present.

@tanjun.as_loader
def load_module(client: tanjun.Client) -> None:
    client.add_component(component.copy())

or

loader = tanjun.Component(name="trans component").load_from_scope().make_loader()
PARAMETER DESCRIPTION
*modules

Path(s) of the modules to load from.

When str this will be treated as a normal import path which is absolute ("foo.bar.baz"). It's worth noting that absolute module paths may be imported from the current location if the top level module is a valid module file or module directory in the current working directory.

When pathlib.Path the module will be imported directly from the given path. In this mode any relative imports in the target module will fail to resolve.

TYPE: typing.Union[str, pathlib.Path] DEFAULT: ()

RETURNS DESCRIPTION
Self

This client instance to enable chained calls.

RAISES DESCRIPTION
tanjun.FailedModuleLoad

If the new version of a module failed to load.

This includes if it failed to import or if one of its loaders raised. The source error can be found at tanjun.FailedModuleLoad.cause.

tanjun.ModuleStateConflict

If the module is already loaded.

tanjun.ModuleMissingLoaders

If no loaders are found in the module.

ModuleNotFoundError

If the module is not found.

load_modules_async abstractmethod async #

load_modules_async(*modules)

Asynchronous variant of tanjun.abc.Client.load_modules.

Unlike tanjun.abc.Client.load_modules, this method will run blocking code in a background thread.

For more information on the behaviour of this method see the documentation for tanjun.abc.Client.load_modules.

reload_modules abstractmethod #

reload_modules(*modules)

Reload entities in this client based on the loaders in loaded module(s).

Note

If an __all__ is present in the target module then it will be used to find loaders and unloaders.

Examples:

For this to work the module has to have at least one ClientLoader which handles loading and one which handles unloading present.

PARAMETER DESCRIPTION
*modules

Paths of one or more module to unload.

These should be the same paths which were passed to tanjun.abc.Client.load_modules.

TYPE: typing.Union[str, pathlib.Path] DEFAULT: ()

RETURNS DESCRIPTION
Self

This client instance to enable chained calls.

RAISES DESCRIPTION
tanjun.FailedModuleLoad

If the new version of a module failed to load.

This includes if it failed to import or if one of its loaders raised. The source error can be found at tanjun.FailedModuleLoad.cause.

tanjun.FailedModuleUnload

If the old version of a module failed to unload.

This indicates that one of its unloaders raised. The source error can be found at tanjun.FailedModuleUnload.cause.

tanjun.ModuleStateConflict

If the module hasn't been loaded.

tanjun.ModuleMissingLoaders

If no loaders are found in the new state of the module.

tanjun.ModuleMissingUnloaders

If no unloaders are found in the current state of the module.

ModuleNotFoundError

If the module can no-longer be found at the provided path.

reload_modules_async abstractmethod async #

reload_modules_async(*modules)

Asynchronous variant of tanjun.abc.Client.reload_modules.

Unlike tanjun.abc.Client.reload_modules, this method will run blocking code in a background thread.

For more information on the behaviour of this method see the documentation for tanjun.abc.Client.reload_modules.

remove_callback_override abstractmethod #

remove_callback_override(callback)

Remove a callback override.

PARAMETER DESCRIPTION
callback

The injected callback to remove the override for.

TYPE: alluka.CallbackSig[_T]

RETURNS DESCRIPTION
Self

The client instance to allow chaining.

RAISES DESCRIPTION
KeyError

If no override is found for the callback.

remove_client_callback abstractmethod #

remove_client_callback(name, callback)

Remove a client callback.

PARAMETER DESCRIPTION
name

The name this callback is being registered to.

This is case-insensitive.

TYPE: typing.Union[str, ClientCallbackNames]

callback

The callback to remove from the client's callbacks.

TYPE: MetaEventSig

RAISES DESCRIPTION
KeyError

If the provided name isn't found.

ValueError

If the provided callback isn't found.

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

remove_component abstractmethod #

remove_component(component)

Remove a component from this client.

This will unsubscribe any client callbacks, commands and listeners registered in the provided component.

PARAMETER DESCRIPTION
component

The component to remove from this client.

TYPE: Component

RAISES DESCRIPTION
ValueError

If the provided component isn't found.

RETURNS DESCRIPTION
Self

The client instance to allow chained calls.

remove_component_by_name abstractmethod #

remove_component_by_name(name)

Remove a component from this client by name.

This will unsubscribe any client callbacks, commands and listeners registered in the provided component.

PARAMETER DESCRIPTION
name

Name of the component to remove from this client.

TYPE: str

RAISES DESCRIPTION
KeyError

If the provided component name isn't found.

remove_listener abstractmethod #

remove_listener(event_type, callback)

Remove a listener from the client.

PARAMETER DESCRIPTION
event_type

The event type to remove a listener for.

TYPE: type[hikari.events.base_events.Event]

callback

The callback to remove.

TYPE: ListenerCallbackSig[_EventT]

RAISES DESCRIPTION
KeyError

If the provided event type isn't found.

ValueError

If the provided callback isn't found.

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

remove_type_dependency abstractmethod #

remove_type_dependency(type_)

Remove a type dependency.

PARAMETER DESCRIPTION
type_

The associated type.

TYPE: type[typing.Any]

RETURNS DESCRIPTION
Self

The client instance to allow chaining.

RAISES DESCRIPTION
KeyError

If type is not registered.

set_callback_override abstractmethod #

set_callback_override(callback, override)

Override a specific injected callback.

PARAMETER DESCRIPTION
callback

The injected callback to override.

TYPE: alluka.CallbackSig[_T]

override

The callback to use instead.

TYPE: alluka.CallbackSig[_T]

RETURNS DESCRIPTION
Self

The client instance to allow chaining.

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the client's metadata.

PARAMETER DESCRIPTION
key

Metadata key to set.

TYPE: typing.Any

value

Metadata value to set.

TYPE: typing.Any

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_type_dependency abstractmethod #

set_type_dependency(type_, value)

Set a callback to be called to resolve a injected type.

PARAMETER DESCRIPTION
type_

The type of the dependency to add an implementation for.

TYPE: type[_T]

value

The value of the dependency.

TYPE: _T

RETURNS DESCRIPTION
Self

The client instance to allow chaining.

unload_modules abstractmethod #

unload_modules(*modules)

Unload entities from this client based on unloaders in one or more modules.

Note

If an __all__ is present in the target module then it will be used to find unloaders.

Examples:

For this to work the module has to have at least one unloading enabled tanjun.abc.ClientLoader present.

@tanjun.as_unloader
def unload_component(client: tanjun.Client) -> None:
    client.remove_component_by_name(component.name)

or

# make_loader's returned ClientLoader handles both loading and unloading.
loader = tanjun.Component(name="trans component").load_from_scope().make_loader()
PARAMETER DESCRIPTION
*modules

Path of one or more modules to unload.

These should be the same path(s) which were passed to tanjun.abc.Client.load_modules.

TYPE: typing.Union[str, pathlib.Path] DEFAULT: ()

RETURNS DESCRIPTION
Self

This client instance to enable chained calls.

RAISES DESCRIPTION
tanjun.ModuleStateConflict

If the module hasn't been loaded.

tanjun.ModuleMissingUnloaders

If no unloaders are found in the module.

tanjun.FailedModuleUnload

If the old version of a module failed to unload.

This indicates that one of its unloaders raised. The source error can be found at tanjun.FailedModuleUnload.cause.

with_client_callback abstractmethod #

with_client_callback(name)

Add a client callback through a decorator call.

Examples:

client = tanjun.Client.from_rest_bot(bot)

@client.with_client_callback("closed")
async def on_close() -> None:
    raise NotImplementedError
PARAMETER DESCRIPTION
name

The name this callback is being registered to.

This is case-insensitive.

TYPE: typing.Union[str, ClientCallbackNames]

RETURNS DESCRIPTION
collections.abc.Callable[[MetaEventSig], MetaEventSig]

Decorator callback used to register the client callback.

This may be sync or async and must return None. The positional and keyword arguments a callback should expect depend on implementation detail around the name being subscribed to.

with_listener abstractmethod #

with_listener(*event_types)

Add an event listener to this client through a decorator call.

Examples:

client = tanjun.Client.from_gateway_bot(bot)

@client.with_listener(hikari.MessageCreateEvent)
async def on_message_create(event: hikari.MessageCreateEvent) -> None:
    raise NotImplementedError
PARAMETER DESCRIPTION
*event_types

One or more event types to listen for.

If none are provided then the event type(s) will be inferred from the callback's type-hints.

TYPE: type[hikari.Event] DEFAULT: ()

RETURNS DESCRIPTION
collections.abc.Callable[[ListenerCallbackSig], ListenerCallbackSig]

Decorator callback used to register the event callback.

The callback must be a coroutine function which returns None and always takes at least one positional arg of type hikari.events.base_events.Event regardless of client implementation detail.

RAISES DESCRIPTION
ValueError

If nothing was passed for event_types and no subclasses of hikari.events.base_events.Event are found in the type-hint for the callback's first argument.

ClientCallbackNames #

Bases: str, enum.Enum

Enum of the standard client callback names.

These should be dispatched by all tanjun.abc.Client implementations.

CLOSED class-attribute #

CLOSED = 'closed'

Called when the client has finished closing.

No positional arguments are provided for this event.

CLOSING class-attribute #

CLOSING = 'closing'

Called when the client is initially instructed to close.

No positional arguments are provided for this event.

COMPONENT_ADDED class-attribute #

COMPONENT_ADDED = 'component_added'

Called when a component is added to an active client.

Warning

This event isn't dispatched for components which were registered while the client is inactive.

The first positional argument is the tanjun.abc.Component being added.

COMPONENT_REMOVED class-attribute #

COMPONENT_REMOVED = 'component_removed'

Called when a component is added to an active client.

Warning

This event isn't dispatched for components which were removed while the client is inactive.

The first positional argument is the tanjun.abc.Component being removed.

MENU_COMMAND_NOT_FOUND class-attribute #

MENU_COMMAND_NOT_FOUND = 'menu_command_not_found'

Called when a menu command is not found.

tanjun.abc.MenuContext is provided as the first positional argument.

MESSAGE_COMMAND_NOT_FOUND class-attribute #

MESSAGE_COMMAND_NOT_FOUND = 'message_command_not_found'

Called when a message command is not found.

tanjun.abc.MessageContext is provided as the first positional argument.

SLASH_COMMAND_NOT_FOUND class-attribute #

SLASH_COMMAND_NOT_FOUND = 'slash_command_not_found'

Called when a slash command is not found.

tanjun.abc.SlashContext is provided as the first positional argument.

STARTED class-attribute #

STARTED = 'started'

Called when the client has finished starting.

No positional arguments are provided for this event.

STARTING class-attribute #

STARTING = 'starting'

Called when the client is initially instructed to start.

No positional arguments are provided for this event.

ClientLoader #

Bases: abc.ABC

Interface of logic used to load and unload components into a generic client.

has_load property abstractmethod #

has_load: bool

Whether this loader will load anything.

has_unload property abstractmethod #

has_unload: bool

Whether this loader will unload anything.

load abstractmethod #

load(client)

Load logic into a client instance.

PARAMETER DESCRIPTION
client

The client to load commands and listeners for.

TYPE: Client

RETURNS DESCRIPTION
bool

Whether anything was loaded.

unload abstractmethod #

unload(client)

Unload logic from a client instance.

PARAMETER DESCRIPTION
client

The client to unload commands and listeners from.

TYPE: Client

RETURNS DESCRIPTION
bool

Whether anything was unloaded.

Component #

Bases: abc.ABC

Standard interface of a Tanjun component.

This is a collection of message and application commands, and listeners with logic for command search + execution and loading the listeners into a tanjun client.

client property abstractmethod #

client: typing.Optional[Client]

Tanjun client this component is bound to.

default_app_cmd_permissions property abstractmethod #

default_app_cmd_permissions: typing.Optional[hikari.Permissions]

Default required guild member permissions for the commands in this component.

This may be overridden by tanjun.abc.AppCommand.default_member_permissions and if this is None then the default from the parent client is used.

Warning

This may be overridden by guild staff and does not apply to admins.

defaults_to_ephemeral property abstractmethod #

defaults_to_ephemeral: typing.Optional[bool]

Whether slash contexts executed in this component should default to ephemeral responses.

This effects calls to [tanjun.abc.SlashContext.create_followup][], [tanjun.abc.SlashContext.create_initial_response][], [tanjun.abc.SlashContext.defer][] and [tanjun.abc.SlashContext.respond][] unless the flags field is provided for the methods which support it.

Note

This may be overridden by tanjun.abc.AppCommand.defaults_to_ephemeral and only effects slash command execution; if this is None then the default from the parent client is used.

dms_enabled_for_app_cmds property abstractmethod #

dms_enabled_for_app_cmds: typing.Optional[bool]

Whether application commands in this component should be enabled in DMs.

Note

This may be overridden by tanjun.abc.AppCommand.is_dm_enabled and if both that and this are None then the default from the parent client is used.

is_case_sensitive property abstractmethod #

is_case_sensitive: typing.Optional[bool]

Whether this component should treat message command names case sensitive in search.

If this is None then the client's case sensitivity will be used.

listeners property abstractmethod #

listeners: collections.Mapping[type[hikari.Event], collections.Collection[ListenerCallbackSig[typing.Any]]]

Mapping of event types to the listeners registered for them in this component.

loop property abstractmethod #

loop: typing.Optional[asyncio.AbstractEventLoop]

The asyncio loop this client is bound to if it has been opened.

menu_commands property abstractmethod #

menu_commands: collections.Collection[MenuCommand[typing.Any, typing.Any]]

Collection of the menu commands in this component.

message_commands property abstractmethod #

message_commands: collections.Collection[MessageCommand[typing.Any]]

Collection of the message commands in this component.

metadata property abstractmethod #

metadata: collections.MutableMapping[typing.Any, typing.Any]

Mutable mapping of the metadata set for this component.

Note

Any modifications made to this mutable mapping will be preserved by the component.

name property abstractmethod #

name: str

Component's unique identifier.

Note

This will be preserved between copies of a component.

slash_commands property abstractmethod #

slash_commands: collections.Collection[BaseSlashCommand]

Collection of the slash commands in this component.

add_listener abstractmethod #

add_listener(event, /, *callbacks)

Add a listener to this component.

PARAMETER DESCRIPTION
event

The event to listen for.

TYPE: type[hikari.events.base_events.Event]

*callbacks

The callbacks to add.

TYPE: ListenerCallbackSig[_EventT] DEFAULT: ()

RETURNS DESCRIPTION
Self

The component to enable chained calls.

add_menu_command abstractmethod #

add_menu_command(command)

Add a menu command to this component.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: MenuCommand[typing.Any, typing.Any]

RETURNS DESCRIPTION
Self

The component to enable chained calls.

add_message_command abstractmethod #

add_message_command(command)

Add a message command to this component.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: MessageCommand[typing.Any]

RETURNS DESCRIPTION
Self

The component to enable chained calls.

add_slash_command abstractmethod #

add_slash_command(command)

Add a slash command to this component.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: BaseSlashCommand

RETURNS DESCRIPTION
Self

The component to enable chained calls.

check_message_name abstractmethod #

check_message_name(name, /, *, case_sensitive=True)

Check whether a name matches any of this component's registered message commands.

Note

This only checks for name matches against the top level command and will not account for sub-commands.

Note

Dependent on implementation detail this may partial check name against command names using name.startswith(command_name), hence why it also returns the name a command was matched by.

PARAMETER DESCRIPTION
name

The name to check for command matches.

TYPE: str

case_sensitive

Whether to perform a case-sensitive match.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Iterator[tuple[str, MessageCommand[typing.Any]]]

Iterator of tuples of command name matches to the relevant message command objects.

check_slash_name abstractmethod #

check_slash_name(name)

Check whether a name matches any of this component's registered slash commands.

Note

This won't check for sub-commands and will expect name to simply be the top level command name.

PARAMETER DESCRIPTION
name

The name to check for command matches.

TYPE: str

RETURNS DESCRIPTION
collections.abc.Iterator[BaseSlashCommand]

An iterator of the matching slash commands.

close abstractmethod async #

close(*, unbind=False)

Close the component.

PARAMETER DESCRIPTION
unbind

Whether to unbind from the client after this is closed.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
RuntimeError

If the component isn't running.

execute_autocomplete abstractmethod #

execute_autocomplete(ctx)

Execute an autocomplete context.

Note

Unlike the other execute methods, this shouldn't be expected to raise tanjun.HaltExecution nor tanjun.CommandError.

PARAMETER DESCRIPTION
ctx

The context to execute.

TYPE: AutocompleteContext

RETURNS DESCRIPTION
collections.abc.Coroutine[typing.Any, typing.Any, None] | None

Coroutine used to wait for the command execution to finish.

This may be awaited or left to run as a background task.

If this is None then the client should carry on its search for a component with a matching autocomplete.

execute_menu abstractmethod async #

execute_menu(ctx, /, *, hooks=None)

Execute a menu context.

PARAMETER DESCRIPTION
ctx

The context to execute.

TYPE: MenuContext

hooks

Set of hooks to include in this command execution.

TYPE: typing.Optional[collections.MutableSet[MenuHooks]] DEFAULT: None

RETURNS DESCRIPTION
collections.abc.Coroutine[typing.Any, typing.Any, None] | None

Coroutine used to wait for the command execution to finish.

This may be awaited or left to run as a background task.

If this is None then the client should carry on its search for a component with a matching command.

RAISES DESCRIPTION
tanjun.CommandError

To end the command's execution with an error response message.

tanjun.HaltExecution

To indicate that the client should stop searching for commands to execute with the current context.

execute_message abstractmethod async #

execute_message(ctx, /, *, hooks=None)

Execute a message context.

PARAMETER DESCRIPTION
ctx

The context to execute.

TYPE: MessageContext

hooks

Set of hooks to include in this command execution.

TYPE: typing.Optional[collections.MutableSet[MessageHooks]] DEFAULT: None

RETURNS DESCRIPTION
bool

Whether a message command was executed in this component with the provided context.

If False then the client should carry on its search for a component with a matching command.

RAISES DESCRIPTION
tanjun.CommandError

To end the command's execution with an error response message.

tanjun.HaltExecution

To indicate that the client should stop searching for commands to execute with the current context.

execute_slash abstractmethod async #

execute_slash(ctx, /, *, hooks=None)

Execute a slash context.

PARAMETER DESCRIPTION
ctx

The context to execute.

TYPE: SlashContext

hooks

Set of hooks to include in this command execution.

TYPE: typing.Optional[collections.MutableSet[SlashHooks]] DEFAULT: None

RETURNS DESCRIPTION
collections.abc.Coroutine[typing.Any, typing.Any, None] | None

Coroutine used to wait for the command execution to finish.

This may be awaited or left to run as a background task.

If this is None then the client should carry on its search for a component with a matching command.

RAISES DESCRIPTION
tanjun.CommandError

To end the command's execution with an error response message.

tanjun.HaltExecution

To indicate that the client should stop searching for commands to execute with the current context.

open abstractmethod async #

open()

Start the component.

RAISES DESCRIPTION
RuntimeError

If the component is already open. If the component isn't bound to a client.

remove_listener abstractmethod #

remove_listener(event, listener)

Remove a listener from this component.

PARAMETER DESCRIPTION
event

The event to listen for.

TYPE: type[hikari.events.base_events.Event]

listener

The listener to remove.

TYPE: ListenerCallbackSig[_EventT]

RAISES DESCRIPTION
ValueError

If the listener is not registered for the provided event.

RETURNS DESCRIPTION
Self

The component to enable chained calls.

remove_menu_command abstractmethod #

remove_menu_command(command)

Remove a menu command from this component.

PARAMETER DESCRIPTION
command

Object of the menu command to remove.

TYPE: MenuCommand[typing.Any, typing.Any]

RETURNS DESCRIPTION
Self

The component to enable chained calls.

remove_message_command abstractmethod #

remove_message_command(command)

Remove a message command from this component.

PARAMETER DESCRIPTION
command

The command to remove.

TYPE: MessageCommand[typing.Any]

RAISES DESCRIPTION
ValueError

If the provided command isn't found.

RETURNS DESCRIPTION
Self

The component to enable chained calls.

remove_slash_command abstractmethod #

remove_slash_command(command)

Remove a slash command from this component.

PARAMETER DESCRIPTION
command

The command to remove.

TYPE: BaseSlashCommand

RAISES DESCRIPTION
ValueError

If the provided command isn't found.

RETURNS DESCRIPTION
Self

The component to enable chained calls.

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the component's metadata.

PARAMETER DESCRIPTION
key

Metadata key to set.

TYPE: typing.Any

value

Metadata value to set.

TYPE: typing.Any

RETURNS DESCRIPTION
Self

The component instance to enable chained calls.

with_listener abstractmethod #

with_listener(*event_types)

Add a listener to this component through a decorator call.

PARAMETER DESCRIPTION
*event_types

One or more event types to listen for.

If none are provided then the event type(s) will be inferred from the callback's type-hints.

TYPE: type[hikari.Event] DEFAULT: ()

RETURNS DESCRIPTION
collections.abc.Callable[[ListenerCallbackSig], ListenerCallbackSig]

Decorator callback which takes listener to add.

RAISES DESCRIPTION
ValueError

If nothing was passed for event_types and no subclasses of hikari.events.base_events.Event are found in the type-hint for the callback's first argument.

with_menu_command abstractmethod #

with_menu_command(command=None, /, *, copy=False)

Add a menu command to this component through a decorator call.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: MenuCommand DEFAULT: None

copy

Whether to copy the command before adding it.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
MenuCommand

The added command.

with_message_command abstractmethod #

with_message_command(command=None, /, *, copy=False)

Add a message command to this component through a decorator call.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: MessageCommand DEFAULT: None

copy

Whether to copy the command before adding it.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
MessageCommand

The added command.

with_slash_command abstractmethod #

with_slash_command(command=None, /, *, copy=False)

Add a slash command to this component through a decorator call.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: BaseSlashCommand DEFAULT: None

copy

Whether to copy the command before adding it.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
BaseSlashCommand

The added command.

Context #

Bases: alluka.Context

Interface for the context of a command execution.

author property abstractmethod #

author: hikari.User

Object of the user who triggered this command.

cache property abstractmethod #

cache: typing.Optional[hikari.api.Cache]

Hikari cache instance this context's command client was initialised with.

channel_id property abstractmethod #

channel_id: hikari.Snowflake

ID of the channel this command was triggered in.

client property abstractmethod #

client: Client

Tanjun tanjun.abc.Client implementation this context was spawned by.

command property abstractmethod #

command: typing.Optional[ExecutableCommand[Self]]

Object of the command this context is bound to.

Note

This will only be None before this has been bound to a specific command but never during command execution.

component property abstractmethod #

component: typing.Optional[Component]

Object of the tanjun.abc.Component this context is bound to.

Note

This will only be None before this has been bound to a specific command but never during command execution nor checks.

created_at property abstractmethod #

created_at: datetime.datetime

When this context was created.

events property abstractmethod #

events: typing.Optional[hikari.api.EventManager]

Object of the event manager this context's client was initialised with.

guild_id property abstractmethod #

guild_id: typing.Optional[hikari.Snowflake]

ID of the guild this command was executed in.

Will be None for all DM command executions.

has_responded property abstractmethod #

has_responded: bool

Whether an initial response has been made for this context.

is_human property abstractmethod #

is_human: bool

Whether this command execution was triggered by a human.

Will be False for bot and webhook triggered commands.

member property abstractmethod #

member: typing.Optional[hikari.Member]

Guild member object of this command's author.

Will be None for DM command executions.

rest property abstractmethod #

rest: hikari.api.RESTClient

Object of the Hikari REST client this context's client was initialised with.

server property abstractmethod #

server: typing.Optional[hikari.api.InteractionServer]

Object of the Hikari interaction server provided for this context's client.

shard property abstractmethod #

shard: typing.Optional[hikari.api.GatewayShard]

Shard that triggered the context.

Note

This will be None if tanjun.abc.Context.shards is also None.

shards property abstractmethod #

shards: typing.Optional[hikari.ShardAware]

Object of the Hikari shard manager this context's client was initialised with.

triggering_name property abstractmethod #

triggering_name: str

Command name this execution was triggered with.

voice property abstractmethod #

voice: typing.Optional[hikari.api.VoiceComponent]

Object of the Hikari voice component this context's client was initialised with.

delete_initial_response abstractmethod async #

delete_initial_response()

Delete the initial response after invoking this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The last context has no initial response.

delete_last_response abstractmethod async #

delete_last_response()

Delete the last response after invoking this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The last context has no responses.

edit_initial_response abstractmethod async #

edit_initial_response(content=hikari.UNDEFINED, *, delete_after=None, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED)

Edit the initial response for this context.

PARAMETER DESCRIPTION
content

The content to edit the initial response with.

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

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

delete_after

If provided, the seconds after which the response message should be deleted.

Slash command responses can only be deleted within 15 minutes of the command being received.

TYPE: typing.Union[datetime.timedelta, float, int, None] DEFAULT: None

attachment

A singular attachment to edit the initial response with.

TYPE: hikari.UndefinedNoneOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

A sequence of attachments to edit the initial response with.

TYPE: hikari.UndefinedNoneOr[collections.Sequence[hikari.Resourceish]] DEFAULT: hikari.UNDEFINED

component

If provided, builder object of the component to set for this message. This component will replace any previously set components and passing None will remove all components.

TYPE: hikari.UndefinedNoneOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

If provided, a sequence of the component builder objects set for this message. These components will replace any previously set components and passing None or an empty sequence will remove all components.

TYPE: hikari.UndefinedNoneOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

embed

An embed to replace the initial response with.

TYPE: hikari.UndefinedNoneOr[hikari.Embed] DEFAULT: hikari.UNDEFINED

embeds

A sequence of embeds to replace the initial response with.

TYPE: hikari.UndefinedNoneOr[collections.Sequence[hikari.Embed]] DEFAULT: hikari.UNDEFINED

mentions_everyone

If provided, whether the message should parse @everyone/@here mentions.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

user_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialUser], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

role_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialRole], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

RETURNS DESCRIPTION
hikari.Message

The message that has been edited.

RAISES DESCRIPTION
ValueError

If more than 100 unique objects/entities are passed for role_mentions or user_mentions.

If delete_after would be more than 15 minutes after the slash command was called.

If both attachment and attachments are passed or both component and components are passed or both embed and embeds are passed.

hikari.BadRequestError

This may be raised in several discrete situations, such as messages being empty with no attachments or embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; too many attachments; attachments that are too large; invalid image URLs in embeds; too many components.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.ForbiddenError

If you are missing the SEND_MESSAGES in the channel or the person you are trying to message has the DM's disabled.

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

edit_last_response abstractmethod async #

edit_last_response(content=hikari.UNDEFINED, *, delete_after=None, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED)

Edit the last response for this context.

PARAMETER DESCRIPTION
content

The content to edit the last response with.

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

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

delete_after

If provided, the seconds after which the response message should be deleted.

Slash command responses can only be deleted within 15 minutes of the command being received.

TYPE: typing.Union[datetime.timedelta, float, int, None] DEFAULT: None

attachment

A singular attachment to edit the last response with.

TYPE: hikari.UndefinedNoneOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

A sequence of attachments to edit the last response with.

TYPE: hikari.UndefinedNoneOr[collections.Sequence[hikari.Resourceish]] DEFAULT: hikari.UNDEFINED

component

If provided, builder object of the component to set for this message. This component will replace any previously set components and passing None will remove all components.

TYPE: hikari.UndefinedNoneOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

If provided, a sequence of the component builder objects set for this message. These components will replace any previously set components and passing None or an empty sequence will remove all components.

TYPE: hikari.UndefinedNoneOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

embed

An embed to replace the last response with.

TYPE: hikari.UndefinedNoneOr[hikari.Embed] DEFAULT: hikari.UNDEFINED

embeds

A sequence of embeds to replace the last response with.

TYPE: hikari.UndefinedNoneOr[collections.Sequence[hikari.Embed]] DEFAULT: hikari.UNDEFINED

mentions_everyone

If provided, whether the message should parse @everyone/@here mentions.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

user_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialUser], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

role_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialRole], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

RETURNS DESCRIPTION
hikari.Message

The message that has been edited.

RAISES DESCRIPTION
ValueError

If more than 100 unique objects/entities are passed for role_mentions or user_mentions.

If delete_after would be more than 15 minutes after the slash command was called.

If both attachment and attachments are passed or both component and components are passed or both embed and embeds are passed.

hikari.BadRequestError

This may be raised in several discrete situations, such as messages being empty with no attachments or embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; too many attachments; attachments that are too large; invalid image URLs in embeds; too many components.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.ForbiddenError

If you are missing the SEND_MESSAGES in the channel or the person you are trying to message has the DM's disabled.

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using tanjun.abc.Context.get_channel if you have hikari.api.config.CacheComponents.GUILD_CHANNELS cache component enabled.

RETURNS DESCRIPTION
hikari.TextableChannel

The textable DM or guild channel the context was invoked in.

RAISES DESCRIPTION
hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.ForbiddenError

If you are missing the READ_MESSAGES permission in the channel.

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using tanjun.abc.Context.get_guild if you have hikari.api.config.CacheComponents.GUILDS cache component enabled.

RETURNS DESCRIPTION
hikari.Guild | None

An optional guild the context was invoked in. None will be returned if the context was invoked in a DM channel.

RAISES DESCRIPTION
hikari.ForbiddenError

If you are not part of the guild.

hikari.NotFoundError

If the guild is not found.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

fetch_initial_response abstractmethod async #

fetch_initial_response()

Fetch the initial response for this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The response was not found.

fetch_last_response abstractmethod async #

fetch_last_response()

Fetch the last response for this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The response was not found.

get_channel abstractmethod #

get_channel()

Retrieve the channel the context was invoked in from the cache.

Note

This method requires the hikari.api.config.CacheComponents.GUILD_CHANNELS cache component.

RETURNS DESCRIPTION
hikari.TextableGuildChannel | None

An optional guild channel the context was invoked in. None will be returned if the channel was not found or if it is DM channel.

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires hikari.api.config.CacheComponents.GUILDS cache component enabled.

RETURNS DESCRIPTION
hikari.Guild | None

An optional guild the context was invoked in. None will be returned if the guild was not found.

respond abstractmethod async #

respond(content=hikari.UNDEFINED, *, ensure_result=False, delete_after=None, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED)

Respond to this context.

PARAMETER DESCRIPTION
content

The content to respond with.

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

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

ensure_result

Ensure that this call will always return a message object.

If True then this will always return hikari.messages.Message, otherwise this will return hikari.Message | None.

It's worth noting that, under certain scenarios within the slash command flow, this may lead to an extre request being made.

TYPE: bool DEFAULT: False

delete_after

If provided, the seconds after which the response message should be deleted.

Slash command responses can only be deleted within 15 minutes of the command being received.

TYPE: typing.Union[datetime.timedelta, float, int, None] DEFAULT: None

attachment

If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.

TYPE: hikari.UndefinedOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Resourceish]] DEFAULT: hikari.UNDEFINED

component

If provided, builder object of the component to include in this response.

TYPE: hikari.UndefinedOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

If provided, a sequence of the component builder objects to include in this response.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

embed

An embed to respond with.

TYPE: hikari.UndefinedOr[hikari.Embed] DEFAULT: hikari.UNDEFINED

embeds

A sequence of embeds to respond with.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Embed]] DEFAULT: hikari.UNDEFINED

mentions_everyone

If provided, whether the message should parse @everyone/@here mentions.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

user_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialUser], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

role_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialRole], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

RETURNS DESCRIPTION
hikari.Message | None

The message that has been created if it was immedieatly available or ensure_result was set to True, else None.

RAISES DESCRIPTION
ValueError

If more than 100 unique objects/entities are passed for role_mentions or user_mentions.

If delete_after would be more than 15 minutes after the slash command was called.

If both attachment and attachments are passed or both component and components are passed or both embed and embeds are passed.

hikari.BadRequestError

This may be raised in several discrete situations, such as messages being empty with no attachments or embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; too many attachments; attachments that are too large; invalid image URLs in embeds; too many components.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.ForbiddenError

If you are missing the SEND_MESSAGES in the channel or the person you are trying to message has the DM's disabled.

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

ExecutableCommand #

Bases: abc.ABC, typing.Generic[_ContextT_co]

Base class for all commands that can be executed.

checks property abstractmethod #

checks: collections.Collection[CheckSig[_ContextT_co]]

Collection of checks that must be met before the command can be executed.

component property abstractmethod #

component: typing.Optional[Component]

Component that the command is registered with.

hooks property abstractmethod #

hooks: typing.Optional[Hooks[_ContextT_co]]

Hooks that are triggered when the command is executed.

metadata property abstractmethod #

metadata: collections.MutableMapping[typing.Any, typing.Any]

Mutable mapping of metadata set for this command.

Note

Any modifications made to this mutable mapping will be preserved by the command.

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

PARAMETER DESCRIPTION
*checks

The checks to add.

TYPE: CheckSig[_ContextT_co] DEFAULT: ()

RETURNS DESCRIPTION
Self

This command to enable chained calls

copy abstractmethod #

copy()

Create a copy of this command.

RETURNS DESCRIPTION
Self

A copy of this command.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

PARAMETER DESCRIPTION
check

The check to remove.

TYPE: CheckSig[_ContextT_co]

RAISES DESCRIPTION
ValueError

If the provided check isn't found.

RETURNS DESCRIPTION
Self

This command to enable chained calls

set_hooks abstractmethod #

set_hooks(hooks)

Set the hooks that are triggered when the command is executed.

PARAMETER DESCRIPTION
hooks

The hooks that are triggered when the command is executed.

TYPE: Hooks[Context] | None

RETURNS DESCRIPTION
Self

This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

PARAMETER DESCRIPTION
key

Metadata key to set.

TYPE: typing.Any

value

Metadata value to set.

TYPE: typing.Any

RETURNS DESCRIPTION
Self

The command instance to enable chained calls.

Hooks #

Bases: abc.ABC, typing.Generic[_ContextT_contra]

Interface of a collection of callbacks called during set stage of command execution.

add_on_error abstractmethod #

add_on_error(callback)

Add an error callback to this hook object.

Note

This won't be called for expected tanjun.TanjunError derived errors.

PARAMETER DESCRIPTION
callback

The callback to add to this hook.

This callback should take two positional arguments (of type tanjun.abc.Context and Exception) and may be either synchronous or asynchronous.

Returning True indicates that the error should be suppressed, False that it should be re-raised and None that no decision has been made. This will be accounted for along with the decisions other error hooks make by majority rule.

TYPE: ErrorHookSig[_ContextT_contra]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_on_parser_error abstractmethod #

add_on_parser_error(callback)

Add a parser error callback to this hook object.

PARAMETER DESCRIPTION
callback

The callback to add to this hook.

This callback should take two positional arguments (of type tanjun.abc.Context and tanjun.ParserError), return None and may be either synchronous or asynchronous.

It's worth noting that this unlike general error handlers, this will always suppress the error.

TYPE: ParserHookSig[_ContextT_contra]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_on_success abstractmethod #

add_on_success(callback)

Add a success callback to this hook object.

PARAMETER DESCRIPTION
callback

The callback to add to this hook.

This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous.

TYPE: HookSig[_ContextT_contra]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_post_execution abstractmethod #

add_post_execution(callback)

Add a post-execution callback to this hook object.

PARAMETER DESCRIPTION
callback

The callback to add to this hook.

This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous.

TYPE: HookSig[_ContextT_contra]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_pre_execution abstractmethod #

add_pre_execution(callback)

Add a pre-execution callback for this hook object.

PARAMETER DESCRIPTION
callback

The callback to add to this hook.

This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous.

TYPE: HookSig[_ContextT_contra]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

with_on_error abstractmethod #

with_on_error(callback)

Add an error callback to this hook object through a decorator call.

Note

This won't be called for expected tanjun.TanjunError derived errors.

Examples:

hooks = AnyHooks()

@hooks.with_on_error
async def on_error(ctx: tanjun.abc.Context, error: Exception) -> bool:
    if isinstance(error, SomeExpectedType):
        await ctx.respond("You dun goofed")
        return True  # Indicating that it should be suppressed.

    await ctx.respond(f"An error occurred: {error}")
    return False  # Indicating that it should be re-raised
PARAMETER DESCRIPTION
callback

The callback to add to this hook.

This callback should take two positional arguments (of type tanjun.abc.Context and Exception) and may be either synchronous or asynchronous.

Returning True indicates that the error should be suppressed, False that it should be re-raised and None that no decision has been made. This will be accounted for along with the decisions other error hooks make by majority rule.

TYPE: tanjun.abc.ErrorHookSig

RETURNS DESCRIPTION
ErrorHookSig

The hook callback which was added.

with_on_parser_error abstractmethod #

with_on_parser_error(callback)

Add a parser error callback to this hook object through a decorator call.

Examples:

hooks = AnyHooks()

@hooks.with_on_parser_error
async def on_parser_error(ctx: tanjun.abc.Context, error: tanjun.ParserError) -> None:
    await ctx.respond(f"You gave invalid input: {error}")
PARAMETER DESCRIPTION
callback

The parser error callback to add to this hook.

This callback should take two positional arguments (of type tanjun.abc.Context and tanjun.ParserError), return None and may be either synchronous or asynchronous.

TYPE: tanjun.abc.ParserHookSig

RETURNS DESCRIPTION
HookSig

The callback which was added.

with_on_success abstractmethod #

with_on_success(callback)

Add a success callback to this hook object through a decorator call.

Examples:

hooks = AnyHooks()

@hooks.with_on_success
async def on_success(ctx: tanjun.abc.Context) -> None:
    await ctx.respond("You did something")
PARAMETER DESCRIPTION
callback

The success callback to add to this hook.

This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous.

TYPE: tanjun.abc.HookSig

RETURNS DESCRIPTION
HookSig

The success callback which was added.

with_post_execution abstractmethod #

with_post_execution(callback)

Add a post-execution callback to this hook object through a decorator call.

Examples:

hooks = AnyHooks()

@hooks.with_post_execution
async def post_execution(ctx: tanjun.abc.Context) -> None:
    await ctx.respond("You did something")
PARAMETER DESCRIPTION
callback

The post-execution callback to add to this hook.

This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous.

TYPE: tanjun.abc.HookSig

RETURNS DESCRIPTION
HookSig

The post-execution callback which was seaddedt.

with_pre_execution abstractmethod #

with_pre_execution(callback)

Add a pre-execution callback to this hook object through a decorator call.

Examples:

hooks = AnyHooks()

@hooks.with_pre_execution
async def pre_execution(ctx: tanjun.abc.Context) -> None:
    await ctx.respond("You did something")
PARAMETER DESCRIPTION
callback

The pre-execution callback to add to this hook.

This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous.

TYPE: tanjun.abc.HookSig

RETURNS DESCRIPTION
HookSig

The pre-execution callback which was added.

MenuCommand #

Bases: AppCommand[MenuContext], typing.Generic[_MenuCallbackSigT, _MenuTypeT]

A contextmenu command.

callback property abstractmethod #

callback: _MenuCallbackSigT

Callback which is called during execution.

tracked_command property abstractmethod #

tracked_command: typing.Optional[hikari.ContextMenuCommand]

Object of the actual command this object tracks if set.

type property abstractmethod #

type: _MenuTypeT

The menu type(s) this is for.

build abstractmethod #

build(*, component=None)

Get a builder object for this command.

PARAMETER DESCRIPTION
component

The component to inherit config like default_member_permissions and is_dm_enabled from if not explicitly set on the command.

This defaults to the command's linked component.

TYPE: typing.Optional[Component] DEFAULT: None

RETURNS DESCRIPTION
hikari.api.ContextMenuCommandBuilder

A builder object for this command. Use to declare this command on globally or for a specific guild.

MenuContext #

Bases: AppCommandContext, abc.ABC

Interface of a menu command context.

command property abstractmethod #

command: typing.Optional[MenuCommand[typing.Any, typing.Any]]

Command that was invoked.

Note

This should always be set during command check execution and command hook execution but isn't guaranteed for client callbacks nor component/client checks.

target property abstractmethod #

target: typing.Union[hikari.InteractionMember, hikari.User, hikari.Message]

Object of the entity this menu targets.

target_id property abstractmethod #

target_id: hikari.Snowflake

ID of the entity this menu command context targets.

type property abstractmethod #

type: typing.Literal[hikari.CommandType.MESSAGE, hikari.CommandType.USER]

The type of context menu this context is for.

resolve_to_member abstractmethod #

resolve_to_member(*, default=Ellipsis)

Resolve a user context menu context to a member object.

RETURNS DESCRIPTION
hikari.Member

The resolved member.

RAISES DESCRIPTION
TypeError

If the context is not a user menu context.

LookupError

If the member was not found for this user menu context.

This will happen if this was executed in a DM or the target user isn't in the current guild.

resolve_to_message abstractmethod #

resolve_to_message()

Resolve a message context menu to a message object.

RETURNS DESCRIPTION
hikari.Message

The resolved message.

RAISES DESCRIPTION
TypeEror
if the context is not for a message menu.

resolve_to_user abstractmethod #

resolve_to_user()

Resolve a user context menu context to a user object.

RETURNS DESCRIPTION
hikari.User | hikari.Member

The resolved user.

RAISES DESCRIPTION
TypeError

If the context is not a user menu context.

set_command abstractmethod #

set_command(command)

Set the command for this context.

PARAMETER DESCRIPTION
command

The command this context is for.

TYPE: typing.Optional[MenuCommand[typing.Any, typing.Any]]

MessageCommand #

Bases: ExecutableCommand[MessageContext], abc.ABC, typing.Generic[_MessageCallbackSigT]

Standard interface of a message command.

callback property abstractmethod #

callback: _MessageCallbackSigT

Callback which is called during execution.

Note

For command groups, this is called when none of the inner-commands matches the message.

names property abstractmethod #

names: collections.Collection[str]

Collection of this command's names.

parent property abstractmethod #

parent: typing.Optional[MessageCommandGroup[typing.Any]]

Parent group of this command if applicable.

parser property abstractmethod #

parser: typing.Optional[MessageParser]

Parser for this command.

copy abstractmethod #

copy(*, parent=None)

Create a copy of this command.

PARAMETER DESCRIPTION
parent

The parent of the copy.

TYPE: typing.Optional[MessageCommandGroup[typing.Any]] DEFAULT: None

RETURNS DESCRIPTION
Self

The copy.

set_parent abstractmethod #

set_parent(parent)

Set the parent of this command.

PARAMETER DESCRIPTION
parent

The parent of this command.

TYPE: typing.Optional[MessageCommandGroup[typing.Any]]

RETURNS DESCRIPTION
Self

The command instance to enable chained calls.

set_parser abstractmethod #

set_parser(parser)

Set the for this message command.

PARAMETER DESCRIPTION
parser

The parser to set.

TYPE: MessageParser

RETURNS DESCRIPTION
Self

The command instance to enable chained calls.

RAISES DESCRIPTION
ValueError

If this parser's option keys aren't valid for this command when validate_arg_keys is True.

MessageCommandGroup #

Bases: MessageCommand[_MessageCallbackSigT], abc.ABC

Standard interface of a message command group.

commands property abstractmethod #

commands: collections.Collection[MessageCommand[typing.Any]]

Collection of the commands in this group.

Note

This may include command groups.

add_command abstractmethod #

add_command(command)

Add a command to this group.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: MessageCommand[typing.Any]

RETURNS DESCRIPTION
Self

The group instance to enable chained calls.

remove_command abstractmethod #

remove_command(command)

Remove a command from this group.

PARAMETER DESCRIPTION
command

The command to remove.

TYPE: MessageCommand[typing.Any]

RAISES DESCRIPTION
ValueError

If the provided command isn't found.

RETURNS DESCRIPTION
Self

The group instance to enable chained calls.

with_command abstractmethod #

with_command(command)

Add a command to this group through a decorator call.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: MessageCommand

RETURNS DESCRIPTION
MessageCommand

The added command.

MessageContext #

Bases: Context, abc.ABC

Interface of a message command specific context.

command property abstractmethod #

command: typing.Optional[MessageCommand[typing.Any]]

Command that was invoked.

Note

This is always set during command, command check and parser converter execution but isn't guaranteed during client callback nor client/component check execution.

content property abstractmethod #

content: str

Content of the context's message minus the triggering name and prefix.

message property abstractmethod #

message: hikari.Message

Message that triggered the context.

triggering_prefix property abstractmethod #

triggering_prefix: str

Prefix that triggered the context.

respond abstractmethod async #

respond(content=hikari.UNDEFINED, *, ensure_result=True, delete_after=None, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, tts=hikari.UNDEFINED, reply=False, mentions_everyone=hikari.UNDEFINED, mentions_reply=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED)

Respond to this context.

PARAMETER DESCRIPTION
content

The content to respond with.

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

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

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

TYPE: hikari.UndefinedOr[typing.Any] DEFAULT: hikari.UNDEFINED

ensure_result

Ensure this method call will return a message object.

This does nothing for message command contexts as the result w ill always be immedieatly available.

TYPE: bool DEFAULT: True

delete_after

If provided, the seconds after which the response message should be deleted.

TYPE: typing.Union[datetime.timedelta, float, int, None] DEFAULT: None

tts

Whether to respond with tts/text to speech or no.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

reply

Whether to reply instead of sending the content to the context.

Passing True here indicates a reply to tanjun.abc.MessageContext.message.

TYPE: typing.Union[bool, hikari.SnowflakeishOr[hikari.PartialMessage], hikari.UndefinedType] DEFAULT: False

attachment

A singular attachment to respond with.

TYPE: hikari.UndefinedOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

A sequence of attachments to respond with.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Resourceish]] DEFAULT: hikari.UNDEFINED

component

If provided, builder object of the component to include in this message.

TYPE: hikari.UndefinedOr[hikari.api.ComponentBuilder] DEFAULT: hikari.UNDEFINED

components

If provided, a sequence of the component builder objects to include in this message.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.api.ComponentBuilder]] DEFAULT: hikari.UNDEFINED

embed

An embed to respond with.

TYPE: hikari.UndefinedOr[hikari.Embed] DEFAULT: hikari.UNDEFINED

embeds

A sequence of embeds to respond with.

TYPE: hikari.UndefinedOr[collections.Sequence[hikari.Embed]] DEFAULT: hikari.UNDEFINED

mentions_everyone

If provided, whether the message should parse @everyone/@here mentions.

TYPE: hikari.UndefinedOr[bool] DEFAULT: hikari.UNDEFINED

user_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed.

Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialUser], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

role_mentions

If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialRole], bool, hikari.UndefinedType] DEFAULT: hikari.UNDEFINED

RETURNS DESCRIPTION
hikari.Message

The message that has been created.

RAISES DESCRIPTION
ValueError

If more than 100 unique objects/entities are passed for role_mentions or user_mentions.

If the interaction will have expired before delete_after is reached.

If both attachment and attachments are passed or both component and components are passed or both embed and embeds are passed.

hikari.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; if reply is not found or not in the same channel as channel; too many components.

hikari.UnauthorizedError

If you are unauthorized to make the request (invalid/missing token).

hikari.ForbiddenError

If you are missing the SEND_MESSAGES in the channel or the person you are trying to message has the DM's disabled.

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

Raised in the event that a rate limit occurs that is longer than max_rate_limit when making a request.

hikari.RateLimitedError

Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur.

hikari.InternalServerError

If an internal error occurs on Discord while handling the request.

MessageParser #

Bases: abc.ABC

Base class for a message parser.

copy abstractmethod #

copy()

Copy the parser.

RETURNS DESCRIPTION
Self

A copy of the parser.

parse abstractmethod async #

parse(ctx)

Parse a message context.

Warning

This relies on the prefix and command name(s) having been removed from tanjun.abc.MessageContext.content.

PARAMETER DESCRIPTION
ctx

The message context to parse.

TYPE: MessageContext

RETURNS DESCRIPTION
dict[str, typing.Any]

Dictionary of argument names to the parsed values for them.

RAISES DESCRIPTION
tanjun.ParserError

If the message could not be parsed.

validate_arg_keys abstractmethod #

validate_arg_keys(callback_name, names)

Validate that callback's keyword arguments are all valid for this parser.

PARAMETER DESCRIPTION
callback_name

The callback's name for use in raised errors.

TYPE: str

names

Key names of the callback's keyword arguments.

TYPE: collections.Container[str]

RAISES DESCRIPTION
ValueError

If any of the parameter keys aren't valid for this parser.

SlashCommand #

Bases: BaseSlashCommand, abc.ABC, typing.Generic[_SlashCallbackSigT]

A command that can be executed in a slash context.

callback property abstractmethod #

callback: _SlashCallbackSigT

Callback which is called during execution.

float_autocompletes property abstractmethod #

float_autocompletes: collections.Mapping[str, AutocompleteSig[float]]

Collection of the float option autocompletes.

int_autocompletes property abstractmethod #

int_autocompletes: collections.Mapping[str, AutocompleteSig[int]]

Collection of the integer option autocompletes.

str_autocompletes property abstractmethod #

str_autocompletes: collections.Mapping[str, AutocompleteSig[str]]

Collection of the string option autocompletes.

SlashCommandGroup #

Bases: BaseSlashCommand, abc.ABC

Standard interface of a slash command group.

Note

Unlike tanjun.abc.MessageCommandGroup, slash command groups do not have their own callback.

commands property abstractmethod #

commands: collections.Collection[BaseSlashCommand]

Collection of the commands in this group.

add_command abstractmethod #

add_command(command)

Add a command to this group.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: BaseSlashCommand

RETURNS DESCRIPTION
Self

The command group instance to enable chained calls.

remove_command abstractmethod #

remove_command(command)

Remove a command from this group.

PARAMETER DESCRIPTION
command

The command to remove.

TYPE: BaseSlashCommand

RAISES DESCRIPTION
ValueError

If the provided command isn't found.

RETURNS DESCRIPTION
Self

The command group instance to enable chained calls.

with_command abstractmethod #

with_command(command)

Add a command to this group through a decorator call.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: _BaseSlashCommandT

RETURNS DESCRIPTION
BaseSlashCommand

The added command.

SlashContext #

Bases: AppCommandContext, abc.ABC

Interface of a slash command specific context.

command property abstractmethod #

command: typing.Optional[BaseSlashCommand]

Command that was invoked.

Note

This should always be set during command check execution and command hook execution but isn't guaranteed for client callbacks nor component/client checks.

options property abstractmethod #

options: collections.Mapping[str, SlashOption]

Mapping of option names to the values provided for them.

type property abstractmethod #

type: typing.Literal[hikari.CommandType.SLASH]

Type of application command this context is for.

set_command abstractmethod #

set_command(command)

Set the command for this context.

PARAMETER DESCRIPTION
command

The command this context is for.

TYPE: typing.Optional[BaseSlashCommand]

SlashOption #

Bases: abc.ABC

Interface of slash command option with extra logic to help resolve it.

name property abstractmethod #

name: str

Name of this option.

type property abstractmethod #

type: typing.Union[hikari.OptionType, int]

Type of this option.

value property abstractmethod #

value: typing.Union[str, hikari.Snowflake, int, bool, float]

Value provided for this option.

Note

For discord entity option types (user, member, channel and role) this will be the entity's ID.

boolean abstractmethod #

boolean()

Get the boolean value of this option.

RAISES DESCRIPTION
TypeError

If tanjun.abc.SlashOption.type is not BOOLEAN.

float abstractmethod #

float()

Get the float value of this option.

RAISES DESCRIPTION
TypeError

If tanjun.abc.SlashOption.type is not FLOAT.

ValueError

If called on the focused option for an autocomplete interaction when it's a malformed (incomplete) float.

integer abstractmethod #

integer()

Get the integer value of this option.

RAISES DESCRIPTION
TypeError

If tanjun.abc.SlashOption.type is not INTEGER.

ValueError

If called on the focused option for an autocomplete interaction when it's a malformed (incomplete) integer.

resolve_to_attachment abstractmethod #

resolve_to_attachment()

Resolve this option to a channel object.

RETURNS DESCRIPTION
hikari.Attachment

The attachment object.

RAISES DESCRIPTION
TypeError

If the option is not an attachment.

resolve_to_channel abstractmethod #

resolve_to_channel()

Resolve this option to a channel object.

RETURNS DESCRIPTION
hikari.InteractionChannel

The channel object.

RAISES DESCRIPTION
TypeError

If the option is not a channel.

resolve_to_member abstractmethod #

resolve_to_member(*, default=Ellipsis)

Resolve this option to a member object.

PARAMETER DESCRIPTION
default

The default value to return if this option cannot be resolved.

If this is not provided, this method will raise a TypeError if this option cannot be resolved.

TYPE: _T DEFAULT: Ellipsis

RETURNS DESCRIPTION
hikari.InteractionMember | _T

The member object or default if it was provided and this option was a user type but had no member.

RAISES DESCRIPTION
LookupError

If no member was found for this option and a default wasn't provided.

This includes if the option is a mentionable type which targets a member-less user.

This could happen if the user isn't in the current guild or if this command was executed in a DM and this option should still be resolvable to a user.

TypeError

If the option is not a user option and a default wasn't provided.

This includes if the option is a mentionable type but doesn't target a user.

resolve_to_mentionable abstractmethod #

resolve_to_mentionable()

Resolve this option to a mentionable object.

RETURNS DESCRIPTION
hikari.Role | hikari.User | hikari.Member

The mentionable object.

RAISES DESCRIPTION
TypeError

If the option is not a mentionable, user or role type.

resolve_to_role abstractmethod #

resolve_to_role()

Resolve this option to a role object.

RETURNS DESCRIPTION
hikari.Role

The role object.

RAISES DESCRIPTION
TypeError

If the option is not a role.

This includes mentionable options which point towards a user.

resolve_to_user abstractmethod #

resolve_to_user()

Resolve this option to a user object.

Note

This will resolve to a hikari.guilds.Member first if the relevant command was executed within a guild and the option targeted one of the guild's members, otherwise it will resolve to hikari.users.User.

It's also worth noting that hikari.Member inherits from hikari.User meaning that the return value of this can always be treated as a user.

RETURNS DESCRIPTION
hikari.User | hikari.Member

The user object.

RAISES DESCRIPTION
TypeError

If the option is not a user.

This includes mentionable options which point towards a role.

resolve_value abstractmethod #

resolve_value()

Resolve this option to an object value.

RETURNS DESCRIPTION
hikari.Attachment | hikari.InteractionChannel | hikari.InteractionMember | hikari.Role | hikari.User

The object value of this option.

RAISES DESCRIPTION
TypeError

If the option isn't resolvable.

snowflake abstractmethod #

snowflake()

Get the ID of this option.

RAISES DESCRIPTION
TypeError

If tanjun.abc.SlashOption.type is not one of CHANNEL, MENTIONABLE, ROLE or USER.

string abstractmethod #

string()

Get the string value of this option.

RAISES DESCRIPTION
TypeError

If tanjun.abc.SlashOption.type is not STRING.