Skip to content

tanjun.abc#

Interfaces of the objects and clients used within Tanjun.

AnyHooks = Hooks[Context] module-attribute #

Execution hooks for any context.

AutocompleteCallbackSig = collections.Callable[Ellipsis, _CoroT[None]] module-attribute #

Type hint of the callback an autocomplete callback should have.

This will be called when handling autocomplete and should be an asynchronous callback which two positional arguments of type tanjun.abc.AutocompleteContext and str | int | float (with the 2nd argument type being decided by the autocomplete type), returns None and may use dependency injection.

CheckSig = typing.Union[collections.Callable[Ellipsis, _CoroT[bool]], collections.Callable[Ellipsis, bool]] module-attribute #

Type hint of a general context check used with Tanjun tanjun.abc.ExecutableCommand classes.

This may be registered with a tanjun.abc.ExecutableCommand to add a rule which decides whether it should execute for each context passed to it. This should take one positional argument of type tanjun.abc.Context and may either be a synchronous or asynchronous callback which returns bool where returning False or raising tanjun.FailedCheck will indicate that the current context shouldn't lead to an execution.

CommandCallbackSig = collections.Callable[Ellipsis, _CoroT[None]] module-attribute #

Type hint of the callback a callable tanjun.abc.ExecutableCommand instance will operate on.

This will be called when executing a command and will need to take one positional argument of type tanjun.abc.Context where any other required or optional keyword arguments will be based on the parser instance for the command if applicable and dependency injection.

Note

This will have to be asynchronous.

ErrorHookSig = typing.Union[collections.Callable[Ellipsis, typing.Optional[bool]], collections.Callable[Ellipsis, _CoroT[typing.Optional[bool]]]] module-attribute #

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 (not including expected tanjun.TanjunError).

This should take two positional arguments - of type tanjun.abc.Context and Exception - and may be either a synchronous or asynchronous callback which returns bool or None and may take advantage of dependency injection.

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 = typing.Union[collections.Callable[Ellipsis, None], collections.Callable[Ellipsis, _CoroT[None]]] module-attribute #

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

Note

This may be asynchronous or synchronous, dependency injection is supported for this callback's keyword arguments and the positional arguments which are passed dependent on the type of hook this is being registered as.

ListenerCallbackSig = collections.Callable[Ellipsis, _CoroT[None]] module-attribute #

Type hint of a hikari event manager callback.

This is guaranteed one positional arg of type hikari.events.base_events.Event regardless of implementation and must be a coruotine function which returns None.

MenuCommandCallbackSig = collections.Callable[Ellipsis, _CoroT[None]] module-attribute #

Type hint of a context menu command callback.

This is guaranteed two positional; arguments of type tanjun.abc.MenuContext and either hikari.User | hikari.InteractionMember and/or hikari.messages.Message dependent on the type(s) of menu this is.

MenuHooks = Hooks[MenuContext] module-attribute #

Execution hooks for menu commands.

MessageHooks = Hooks[MessageContext] module-attribute #

Execution hooks for messages commands.

MetaEventSig = typing.Union[collections.Callable[Ellipsis, _CoroT[None]], collections.Callable[Ellipsis, None]] module-attribute #

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.

SlashHooks = Hooks[SlashContext] module-attribute #

Execution hooks for slash commands.

AppCommand #

Bases: ExecutableCommand[_AppCommandContextT]

Base class for all application command classes.

build(*, component=None) abstractmethod #

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.

default_member_permissions() abstractmethod property #

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() abstractmethod property #

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() abstractmethod property #

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() abstractmethod property #

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() abstractmethod property #

Name of the command.

set_tracked_command(command) abstractmethod #

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.

tracked_command() property #

Object of the actual command this object tracks if set.

tracked_command_id() abstractmethod property #

ID of the actual command this object tracks if set.

type() abstractmethod property #

The type of this application command.

AppCommandContext #

Bases: Context, abc.ABC

Base class for application command contexts.

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) async abstractmethod #

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.

Note

Since (as of writing) ephemeral responses cannot be deleted by the bot, delete_after is ignored for ephemeral slash command responses.

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.

attachment If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL. attachments If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs. component If provided, builder object of the component to include in this message. components If provided, a sequence of the component builder objects to include in this message. embed If provided, the message embed. embeds If provided, the message embeds. mentions_everyone If provided, whether the message should parse @everyone/@here mentions. 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.

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. tts If provided, whether the message will be sent as a TTS message. 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.
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(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) async abstractmethod #

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.

Note

Since (as of writing) ephemeral responses cannot be deleted by the bot, delete_after is ignored for ephemeral slash command responses.

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.

defaults_to_ephemeral() abstractmethod property #

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.

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

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

expires_at() abstractmethod property #

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() abstractmethod property #

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() abstractmethod property #

Interaction this context is for.

mark_not_found() async abstractmethod #

Mark this context as not found.

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

member() abstractmethod property #

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

set_ephemeral_default(state) abstractmethod #

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

type() abstractmethod property #

Type of application command this context is for.

AutocompleteContext #

Bases: alluka.Context

Interface of an autocomplete context.

author() abstractmethod property #

Object of the user who triggered this autocomplete.

cache() abstractmethod property #

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

channel_id() abstractmethod property #

ID of the channel this autocomplete was triggered in.

client() abstractmethod property #

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

created_at() abstractmethod property #

When this context was created.

Note

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

events() abstractmethod property #

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

fetch_channel() async abstractmethod #

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() async abstractmethod #

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.

focused() abstractmethod property #

The option being autocompleted.

get_channel() abstractmethod #

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 #

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.

guild_id() abstractmethod property #

ID of the guild this autocomplete was triggered in.

Will be None for all DM autocomplete executions.

has_responded() abstractmethod property #

Whether the choices have been set for this autocomplete.

interaction() abstractmethod property #

Interaction this context is for.

member() abstractmethod property #

Guild member object of this autocomplete's author.

Will be None for DM autocomplete executions.

options() abstractmethod property #

Mapping of option names to the values provided for them.

rest() abstractmethod property #

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

server() abstractmethod property #

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

set_choices(choices=Ellipsis, /, **kwargs) async abstractmethod #

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.

shard() abstractmethod property #

Shard that triggered the context.

Note

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

shards() abstractmethod property #

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

voice() property #

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

BaseSlashCommand #

Bases: AppCommand[SlashContext], abc.ABC

Base class for all slash command classes.

build(*, component=None) abstractmethod #

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(*, parent=None) abstractmethod #

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.

parent() abstractmethod property #

Object of the group this command is in.

tracked_command() property #

Object of the actual command this object tracks if set.

type() abstractmethod property #

The type of this command.

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.

add_client_callback(name, callback) abstractmethod #

Add 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 register.

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.

TYPE: MetaEventSig

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

add_component(component) abstractmethod #

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(event_type, callback) abstractmethod #

Add a listener to the client.

PARAMETER DESCRIPTION
event_type

The event type to add a listener for.

TYPE: type[hikari.Event]

callback

The callback to register as a listener.

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

TYPE: ListenerCallbackSig

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

cache() abstractmethod property #

Hikari cache instance this command client was initialised with.

check_message_name(name) abstractmethod #

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

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

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

check_slash_name(name) abstractmethod #

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(*, application=None, guild=hikari.UNDEFINED) async abstractmethod #

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

components() abstractmethod property #

Collection of the components this command client is using.

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

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(commands, /, command_ids=None, *, application=None, guild=hikari.UNDEFINED, message_ids=None, user_ids=None, force=False) async abstractmethod #

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(command_ids=None, *, application=None, guild=hikari.UNDEFINED, message_ids=None, user_ids=None, force=False) async abstractmethod #

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.

default_app_cmd_permissions() abstractmethod property #

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() abstractmethod property #

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.

dispatch_client_callback(name, /, *args) async abstractmethod #

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.

dms_enabled_for_app_cmds() abstractmethod property #

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

This defaults to True.

events() abstractmethod property #

Object of the event manager this client was initialised with.

This is used for executing message commands if set.

get_callback_override(callback) abstractmethod #

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(name) abstractmethod #

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(name) abstractmethod #

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(type_) abstractmethod #

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.

injector() abstractmethod property #

The attached alluka dependency injection client.

is_alive() abstractmethod property #

Whether this client is alive.

iter_commands() abstractmethod #

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(*, global_only=False, type=None) abstractmethod #

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.Literal[hikari.CommandType.MESSAGE, hikari.CommandType.USER, None] DEFAULT: None

RETURNS DESCRIPTION
collections.abc.Iterator[MenuCommand]

Iterator of the menu commands registered to this client.

iter_message_commands() abstractmethod #

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(*, global_only=False) abstractmethod #

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.

listeners() abstractmethod property #

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

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

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(directory, /, *, namespace=None) async abstractmethod #

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(*modules) abstractmethod #

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(*modules) async abstractmethod #

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.

loop() abstractmethod property #

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

metadata() abstractmethod property #

Mutable mapping of the metadata set for this client.

Note

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

prefixes() abstractmethod property #

Collection of the prefixes set for this client.

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

reload_modules(*modules) abstractmethod #

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(*modules) async abstractmethod #

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(callback) abstractmethod #

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(name, callback) abstractmethod #

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(component) abstractmethod #

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(name) abstractmethod #

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(event_type, callback) abstractmethod #

Remove a listener from the client.

PARAMETER DESCRIPTION
event_type

The event type to remove a listener for.

TYPE: type[hikari.Event]

callback

The callback to remove.

TYPE: ListenerCallbackSig

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(type_) abstractmethod #

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.

rest() abstractmethod property #

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

server() abstractmethod property #

Object of the Hikari interaction server provided for this client.

This is used for executing application commands if set.

set_callback_override(callback, override) abstractmethod #

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(key, value) abstractmethod #

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(type_, value) abstractmethod #

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.

shards() abstractmethod property #

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

unload_modules(*modules) abstractmethod #

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.

voice() property #

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

with_client_callback(name) abstractmethod #

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(*event_types) abstractmethod #

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 = 'closed' class-attribute #

Called when the client has finished closing.

No positional arguments are provided for this event.

CLOSING = 'closing' class-attribute #

Called when the client is initially instructed to close.

No positional arguments are provided for this event.

COMPONENT_ADDED = 'component_added' class-attribute #

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 = 'component_removed' class-attribute #

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 = 'menu_command_not_found' class-attribute #

Called when a menu command is not found.

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

MESSAGE_COMMAND_NOT_FOUND = 'message_command_not_found' class-attribute #

Called when a message command is not found.

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

SLASH_COMMAND_NOT_FOUND = 'slash_command_not_found' class-attribute #

Called when a slash command is not found.

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

STARTED = 'started' class-attribute #

Called when the client has finished starting.

No positional arguments are provided for this event.

STARTING = 'starting' class-attribute #

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() abstractmethod property #

Whether this loader will load anything.

has_unload() abstractmethod property #

Whether this loader will unload anything.

load(client) abstractmethod #

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(client) abstractmethod #

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.

add_listener(event, listener) abstractmethod #

Add a listener to this component.

PARAMETER DESCRIPTION
event

The event to listen for.

TYPE: type[hikari.Event]

listener

The listener to add.

TYPE: ListenerCallbackSig

RETURNS DESCRIPTION
Self

The component to enable chained calls.

add_menu_command(command) abstractmethod #

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(command) abstractmethod #

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(command) abstractmethod #

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(name) abstractmethod #

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

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(name) abstractmethod #

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.

client() abstractmethod property #

Tanjun client this component is bound to.

close(*, unbind=False) async abstractmethod #

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.

default_app_cmd_permissions() abstractmethod property #

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() abstractmethod property #

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() abstractmethod property #

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.

execute_autocomplete(ctx) abstractmethod #

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(ctx, /, *, hooks=None) async abstractmethod #

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(ctx, /, *, hooks=None) async abstractmethod #

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(ctx, /, *, hooks=None) async abstractmethod #

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.

listeners() abstractmethod property #

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

loop() abstractmethod property #

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

menu_commands() abstractmethod property #

Collection of the menu commands in this component.

message_commands() abstractmethod property #

Collection of the message commands in this component.

metadata() abstractmethod property #

Mutable mapping of the metadata set for this component.

Note

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

name() abstractmethod property #

Component's unique identifier.

Note

This will be preserved between copies of a component.

open() async abstractmethod #

Start the component.

RAISES DESCRIPTION
RuntimeError

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

remove_listener(event, listener) abstractmethod #

Remove a listener from this component.

PARAMETER DESCRIPTION
event

The event to listen for.

TYPE: type[hikari.Event]

listener

The listener to remove.

TYPE: ListenerCallbackSig

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(command) abstractmethod #

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(command) abstractmethod #

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(command) abstractmethod #

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(key, value) abstractmethod #

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.

slash_commands() abstractmethod property #

Collection of the slash commands in this component.

with_listener(*event_types) abstractmethod #

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(command=None, /, *, copy=False) abstractmethod #

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(command=None, /, *, copy=False) abstractmethod #

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(command=None, /, *, copy=False) abstractmethod #

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() abstractmethod property #

Object of the user who triggered this command.

cache() abstractmethod property #

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

channel_id() abstractmethod property #

ID of the channel this command was triggered in.

client() abstractmethod property #

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

command() abstractmethod property #

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() abstractmethod property #

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() abstractmethod property #

When this context was created.

delete_initial_response() async abstractmethod #

Delete the initial response after invoking this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The last context has no initial response.

delete_last_response() async abstractmethod #

Delete the last response after invoking this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The last context has no responses.

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, replace_attachments=False, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED) async abstractmethod #

Edit the initial response for this context.

Note

Since (as of writing) ephemeral responses cannot be deleted by the bot, delete_after is ignored for ephemeral slash command responses.

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.UndefinedOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

A sequence of attachments to edit the initial response with.

TYPE: hikari.UndefinedOr[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

replace_attachments

Whether to replace the attachments of the response or not.

TYPE: bool DEFAULT: False

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(content=hikari.UNDEFINED, *, delete_after=None, attachment=hikari.UNDEFINED, attachments=hikari.UNDEFINED, component=hikari.UNDEFINED, components=hikari.UNDEFINED, embed=hikari.UNDEFINED, embeds=hikari.UNDEFINED, replace_attachments=False, mentions_everyone=hikari.UNDEFINED, user_mentions=hikari.UNDEFINED, role_mentions=hikari.UNDEFINED) async abstractmethod #

Edit the last response for this context.

Note

Since (as of writing) ephemeral responses cannot be deleted by the bot, delete_after is ignored for ephemeral slash command responses.

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.UndefinedOr[hikari.Resourceish] DEFAULT: hikari.UNDEFINED

attachments

A sequence of attachments to edit the last response with.

TYPE: hikari.UndefinedOr[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

replace_attachments

Whether to replace the attachments of the response or not.

TYPE: bool DEFAULT: False

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.

events() abstractmethod property #

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

fetch_channel() async abstractmethod #

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() async abstractmethod #

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() async abstractmethod #

Fetch the initial response for this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The response was not found.

fetch_last_response() async abstractmethod #

Fetch the last response for this context.

RAISES DESCRIPTION
LookupError, hikari.NotFoundError

The response was not found.

get_channel() abstractmethod #

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 #

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.

guild_id() abstractmethod property #

ID of the guild this command was executed in.

Will be None for all DM command executions.

has_responded() abstractmethod property #

Whether an initial response has been made for this context.

is_human() abstractmethod property #

Whether this command execution was triggered by a human.

Will be False for bot and webhook triggered commands.

member() abstractmethod property #

Guild member object of this command's author.

Will be None for DM command executions.

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) async abstractmethod #

Respond to this context.

Note

Since (as of writing) ephemeral responses cannot be deleted by the bot, delete_after is ignored for ephemeral slash command responses.

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.

rest() abstractmethod property #

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

server() abstractmethod property #

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

shard() abstractmethod property #

Shard that triggered the context.

Note

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

shards() abstractmethod property #

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

triggering_name() abstractmethod property #

Command name this execution was triggered with.

voice() property #

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

ExecutableCommand #

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

Base class for all commands that can be executed.

add_check(check) abstractmethod #

Add a check to the command.

PARAMETER DESCRIPTION
check

The check to add.

TYPE: CheckSig

RETURNS DESCRIPTION
Self

This command to enable chained calls

checks() abstractmethod property #

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

component() abstractmethod property #

Component that the command is registered with.

copy() abstractmethod #

Create a copy of this command.

RETURNS DESCRIPTION
Self

A copy of this command.

hooks() abstractmethod property #

Hooks that are triggered when the command is executed.

metadata() abstractmethod property #

Mutable mapping of metadata set for this command.

Note

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

remove_check(check) abstractmethod #

Remove a check from the command.

PARAMETER DESCRIPTION
check

The check to remove.

TYPE: CheckSig

RAISES DESCRIPTION
ValueError

If the provided check isn't found.

RETURNS DESCRIPTION
Self

This command to enable chained calls

set_hooks(hooks) abstractmethod #

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(key, value) abstractmethod #

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(callback) abstractmethod #

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

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_on_parser_error(callback) abstractmethod #

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

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_on_success(callback) abstractmethod #

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

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_post_execution(callback) abstractmethod #

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

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

add_pre_execution(callback) abstractmethod #

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

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

with_on_error(callback) abstractmethod #

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

RETURNS DESCRIPTION
ErrorHookSig

The hook callback which was added.

with_on_parser_error(callback) abstractmethod #

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

RETURNS DESCRIPTION
HookSig

The callback which was added.

with_on_success(callback) abstractmethod #

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

RETURNS DESCRIPTION
HookSig

The success callback which was added.

with_post_execution(callback) abstractmethod #

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

RETURNS DESCRIPTION
HookSig

The post-execution callback which was seaddedt.

with_pre_execution(callback) abstractmethod #

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

RETURNS DESCRIPTION
HookSig

The pre-execution callback which was added.

MenuCommand #

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

A contextmenu command.

build(*, component=None) abstractmethod #

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.

callback() abstractmethod property #

Callback which is called during execution.

tracked_command() abstractmethod property #

Object of the actual command this object tracks if set.

type() abstractmethod property #

The menu type(s) this is for.

MenuContext #

Bases: AppCommandContext, abc.ABC

Interface of a menu command context.

command() abstractmethod property #

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.

resolve_to_member(*, default=Ellipsis) abstractmethod #

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 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 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(command) abstractmethod #

Set the command for this context.

PARAMETER DESCRIPTION
command

The command this context is for.

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

target() abstractmethod property #

Object of the entity this menu targets.

target_id() abstractmethod property #

ID of the entity this menu command context targets.

type() abstractmethod property #

The type of context menu this context is for.

MessageCommand #

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

Standard interface of a message command.

callback() abstractmethod property #

Callback which is called during execution.

Note

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

copy(*, parent=None) abstractmethod #

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.

names() abstractmethod property #

Collection of this command's names.

parent() abstractmethod property #

Parent group of this command if applicable.

parser() abstractmethod property #

Parser for this command.

set_parent(parent) abstractmethod #

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(parser) abstractmethod #

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[_CommandCallbackSigT], abc.ABC

Standard interface of a message command group.

add_command(command) abstractmethod #

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.

commands() abstractmethod property #

Collection of the commands in this group.

Note

This may include command groups.

remove_command(command) abstractmethod #

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(command) abstractmethod #

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() abstractmethod property #

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() abstractmethod property #

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

message() abstractmethod property #

Message that triggered the context.

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) async abstractmethod #

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.

triggering_name() abstractmethod property #

Command name that triggered the context.

triggering_prefix() abstractmethod property #

Prefix that triggered the context.

MessageParser #

Bases: abc.ABC

Base class for a message parser.

copy() abstractmethod #

Copy the parser.

RETURNS DESCRIPTION
Self

A copy of the parser.

parse(ctx) async abstractmethod #

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(callback_name, names) abstractmethod #

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[_CommandCallbackSigT]

A command that can be executed in a slash context.

callback() abstractmethod property #

Callback which is called during execution.

float_autocompletes() abstractmethod property #

Collection of the float option autocompletes.

int_autocompletes() abstractmethod property #

Collection of the integer option autocompletes.

str_autocompletes() abstractmethod property #

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.

add_command(command) abstractmethod #

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.

commands() abstractmethod property #

Collection of the commands in this group.

remove_command(command) abstractmethod #

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(command) abstractmethod #

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() abstractmethod property #

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() abstractmethod property #

Mapping of option names to the values provided for them.

set_command(command) abstractmethod #

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.

boolean() abstractmethod #

Get the boolean value of this option.

RAISES DESCRIPTION
TypeError

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

float() abstractmethod #

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 #

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.

name() abstractmethod property #

Name of this option.

resolve_to_attachment() abstractmethod #

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 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(*, default=Ellipsis) abstractmethod #

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 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 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 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 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 #

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 #

Get the string value of this option.

RAISES DESCRIPTION
TypeError

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

type() abstractmethod property #

Type of this option.

value() abstractmethod property #

Value provided for this option.

Note

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