Skip to content

tanjun.abc#

Interfaces of the objects and clients used within Tanjun.

AnyCheckSig module-attribute #

AnyCheckSig = CheckSig['Context']

Type hint of a check callback for any command type.

AnyHooks module-attribute #

AnyHooks = Hooks[Context]

Execution hooks for any context.

AutocompleteCallbackSig module-attribute #

AutocompleteCallbackSig = AutocompleteSig[_AutocompleteValueT]

Deprecated alias of AutocompleteSig.

AutocompleteSig module-attribute #

AutocompleteSig = Callable[Concatenate['AutocompleteContext', _AutocompleteValueT, ...], _CoroT[None]]

Type hint of the signature an autocomplete callback should have.

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

CheckSig module-attribute #

CheckSig = Callable[Concatenate[_ContextT_contra, ...], _MaybeAwaitable[bool]]

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

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

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

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

CommandCallbackSig module-attribute #

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

Deprecated type hint used to represent any command callback.

ErrorHookSig module-attribute #

ErrorHookSig = Callable[Concatenate[_ContextT_contra, Exception, ...], _MaybeAwaitable[Optional[bool]]]

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

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

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

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

HookSig module-attribute #

HookSig = Callable[Concatenate[_ContextT_contra, ...], _MaybeAwaitable[None]]

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

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

ListenerCallbackSig module-attribute #

ListenerCallbackSig = Callable[Concatenate[_EventT, ...], _CoroT[None]]

Type hint of a hikari event manager callback.

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

MenuCallbackSig module-attribute #

MenuCallbackSig = Callable[Concatenate['MenuContext', _MenuValueT, ...], _CoroT[None]]

Type hint of a context menu command callback.

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

MenuCommandCallbackSig module-attribute #

MenuCommandCallbackSig = MenuCallbackSig[_MenuValueT]

Deprecated alias of MenuCallbackSig.

MenuHooks module-attribute #

MenuHooks = Hooks[MenuContext]

Execution hooks for menu commands.

MessageCallbackSig module-attribute #

MessageCallbackSig = _CommandCallbackSig['MessageContext']

Type hint of a message command callback.

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

MessageHooks module-attribute #

MessageHooks = Hooks[MessageContext]

Execution hooks for messages commands.

MetaEventSig module-attribute #

MetaEventSig = Callable[..., Union[_CoroT[None], None]]

Type hint of a client callback.

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

NO_DEFAULT module-attribute #

NO_DEFAULT = NO_DEFAULT

Singleton used to mark an argument as having no default.

NO_PASS module-attribute #

NO_PASS = NO_PASS

Singleton used to mark an argument as being not passed when it isn't provided.

NoDefault module-attribute #

NoDefault = Literal[NO_DEFAULT]

Type hint of tanjun.abc.NO_DEFAULT.

ParserHookSig module-attribute #

ParserHookSig = Callable[Concatenate[_ContextT_contra, 'errors.ParserError', ...], _MaybeAwaitable[Optional[bool]]]

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

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

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

Parser errors are always suppressed (unlike general errors).

SlashCallbackSig module-attribute #

SlashCallbackSig = _CommandCallbackSig['SlashContext']

Type hint of a slash command callback.

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

SlashHooks module-attribute #

SlashHooks = Hooks[SlashContext]

Execution hooks for slash commands.

AppCommand #

Bases: ExecutableCommand[_AppCommandContextT]

Base class for all application command classes.

checks abstractmethod property #

checks

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

component abstractmethod property #

component

Component that the command is registered with.

default_member_permissions abstractmethod property #

default_member_permissions

The default guild member permissions required to use this command.

Warning

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

Warning

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

defaults_to_ephemeral abstractmethod property #

defaults_to_ephemeral

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

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.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.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

is_dm_enabled abstractmethod property #

is_dm_enabled

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 #

is_global

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.

is_nsfw property #

is_nsfw

Whether a command should only be accessible in channels marked as NSFW.

metadata abstractmethod property #

metadata

Mutable mapping of metadata set for this command.

Note

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

name abstractmethod property #

name

Name of the command.

tracked_command abstractmethod property #

tracked_command

Object of the actual command this object tracks if set.

tracked_command_id abstractmethod property #

tracked_command_id

ID of the actual command this object tracks if set.

type abstractmethod property #

type

The type of this application command.

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

Parameters:

  • *checks (CheckSig[_ContextT_co], default: () ) –

    The checks to add.

Returns:

  • Self

    This command to enable chained calls

build abstractmethod #

build(*, component=None)

Get a builder object for this command.

Parameters:

  • component (Optional[Component], default: None ) –

    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.

Returns:

  • CommandBuilder

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

copy abstractmethod #

copy()

Create a copy of this command.

Returns:

  • Self

    A copy of this command.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

Parameters:

  • check (CheckSig[_ContextT_co]) –

    The check to remove.

Raises:

  • ValueError

    If the provided check isn't found.

Returns:

  • Self

    This command to enable chained calls

set_hooks abstractmethod #

set_hooks(hooks)

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

Parameters:

  • hooks (Hooks[Context] | None) –

    The hooks that are triggered when the command is executed.

Returns:

  • Self

    This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The command instance to enable chained calls.

set_tracked_command abstractmethod #

set_tracked_command(command)

Set the global command this tracks.

Parameters:

  • command (PartialCommand) –

    Object of the global command this tracks.

Returns:

  • Self

    The command instance to enable chained calls.

AppCommandContext #

Bases: Context, ABC

Base class for application command contexts.

author abstractmethod property #

author

Object of the user who triggered this command.

cache abstractmethod property #

cache

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

channel_id abstractmethod property #

channel_id

ID of the channel this command was triggered in.

client abstractmethod property #

client

Tanjun Client implementation this context was spawned by.

command abstractmethod property #

command

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 #

component

Object of the 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 #

created_at

When this context was created.

defaults_to_ephemeral abstractmethod property #

defaults_to_ephemeral

Whether the context is marked as defaulting to ephemeral response.

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.respond unless the flags field is provided for the methods which support it.

events abstractmethod property #

events

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

expires_at abstractmethod property #

expires_at

When this application command context expires.

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

guild_id abstractmethod property #

guild_id

ID of the guild this command was executed in.

Will be None for all DM command executions.

has_been_deferred abstractmethod property #

has_been_deferred

Whether the initial response for this context has been deferred.

Warning

If this is True when AppCommandContext.has_responded is False then AppCommandContext.edit_initial_response will need to be used to create the initial response rather than AppCommandContext.create_initial_response.

has_responded abstractmethod property #

has_responded

Whether an initial response has been made for this context.

interaction abstractmethod property #

interaction

Interaction this context is for.

is_human abstractmethod property #

is_human

Whether this command execution was triggered by a human.

Will be False for bot and webhook triggered commands.

member abstractmethod property #

member

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

rest abstractmethod property #

rest

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

server abstractmethod property #

server

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

shard abstractmethod property #

shard

Shard that triggered the context.

Note

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

shards abstractmethod property #

shards

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

triggering_name abstractmethod property #

triggering_name

Command name this execution was triggered with.

type abstractmethod property #

type

Type of application command this context is for.

voice abstractmethod property #

voice

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

create_followup abstractmethod async #

create_followup(content=hikari.UNDEFINED, *, delete_after=None, ephemeral=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, tts=hikari.UNDEFINED, flags=hikari.UNDEFINED)

Create a followup response for this context.

Warning

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

Parameters:

Returns:

  • Message

    The created message object.

Raises:

  • NotFoundError

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

  • BadRequestError

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

  • ValueError

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

    If the interaction will have expired before delete_after is reached.

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

create_initial_response abstractmethod async #

create_initial_response(content=hikari.UNDEFINED, *, delete_after=None, ephemeral=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, flags=hikari.UNDEFINED, tts=hikari.UNDEFINED)

Create the initial response for this context.

Warning

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

Parameters:

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • NotFoundError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

create_modal_response abstractmethod async #

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

Send a modal as the initial response for this context.

Warning

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

Parameters:

Raises:

  • ValueError

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

  • BadRequestError

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

  • UnauthorizedError

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

  • NotFoundError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

defer abstractmethod async #

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

Defer the initial response for this context.

Note

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

Parameters:

  • ephemeral (Optional[bool], default: None ) –

    Whether the deferred response should be ephemeral.

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

  • flags (Union[UndefinedType, int, MessageFlag], default: UNDEFINED ) –

    The flags to use for the initial response.

delete_initial_response abstractmethod async #

delete_initial_response()

Delete the initial response after invoking this context.

Raises:

delete_last_response abstractmethod async #

delete_last_response()

Delete the last response after invoking this context.

Raises:

edit_initial_response abstractmethod async #

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

Edit the initial response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

edit_last_response abstractmethod async #

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

Edit the last response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using Context.get_channelif you have the CacheComponents.GUILD_CHANNELS cache component enabled.

Returns:

  • TextableChannel

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

Raises:

  • UnauthorizedError

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

  • ForbiddenError

    If you are missing the READ_MESSAGES permission in the channel.

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using Context.get_guild if you have the CacheComponents.GUILDS cache component enabled.

Returns:

  • Guild | None

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

Raises:

fetch_initial_response abstractmethod async #

fetch_initial_response()

Fetch the initial response for this context.

Raises:

fetch_last_response abstractmethod async #

fetch_last_response()

Fetch the last response for this context.

Raises:

get_channel abstractmethod #

get_channel()

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

Note

This method requires the CacheComponents.GUILD_CHANNELS cache component.

Returns:

  • TextableGuildChannel | None

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

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires the CacheComponents.GUILDS cache component.

Returns:

  • Guild | None

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

mark_not_found abstractmethod async #

mark_not_found()

Mark this context as not found.

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

respond abstractmethod async #

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

Respond to this context.

Parameters:

Returns:

  • Message | None

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

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

set_ephemeral_default abstractmethod #

set_ephemeral_default(state)

Set the ephemeral default state for this context.

Parameters:

  • state (bool) –

    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.

AutocompleteContext #

Bases: Context

Interface of an autocomplete context.

author abstractmethod property #

author

Object of the user who triggered this autocomplete.

cache abstractmethod property #

cache

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

channel_id abstractmethod property #

channel_id

ID of the channel this autocomplete was triggered in.

client abstractmethod property #

client

Tanjun Client implementation this context was spawned by.

created_at abstractmethod property #

created_at

When this context was created.

Note

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

events abstractmethod property #

events

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

focused abstractmethod property #

focused

The option being autocompleted.

guild_id abstractmethod property #

guild_id

ID of the guild this autocomplete was triggered in.

Will be None for all DM autocomplete executions.

has_responded abstractmethod property #

has_responded

Whether the choices have been set for this autocomplete.

interaction abstractmethod property #

interaction

Interaction this context is for.

member abstractmethod property #

member

Guild member object of this autocomplete's author.

Will be None for DM autocomplete executions.

options abstractmethod property #

options

Mapping of option names to the values provided for them.

rest abstractmethod property #

rest

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

server abstractmethod property #

server

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

shard abstractmethod property #

shard

Shard that triggered the context.

Note

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

shards abstractmethod property #

shards

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

triggering_name abstractmethod property #

triggering_name

Full command name this autocomplete was triggered for.

voice abstractmethod property #

voice

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

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using AutocompleteContext.get_channel if you have the CacheComponents.GUILD_CHANNELS cache component enabled.

Returns:

  • TextableChannel

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

Raises:

  • UnauthorizedError

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

  • ForbiddenError

    If you are missing the READ_MESSAGES permission in the channel.

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using AutocompleteContext.get_guild if you have the CacheComponents.GUILDS cache component enabled.

Returns:

  • Guild | None

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

Raises:

get_channel abstractmethod #

get_channel()

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

Note

This method requires the CacheComponents.GUILD_CHANNELS cache component.

Returns:

  • TextableGuildChannel | None

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

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires the CacheComponents.GUILDS cache component.

Returns:

  • Guild | None

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

set_choices abstractmethod async #

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

Set the choices for this autocomplete.

Note

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

Parameters:

  • choices (Mapping[str, str | float | int], default: ... ) –

    Mapping of string option names to their values.

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

  • **kwargs (str | float | int, default: {} ) –

    Keyword arguments mapping string option names to their values.

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

Raises:

  • RuntimeError

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

  • ValueError

    If more than 25 choices are passed.

BaseSlashCommand #

Bases: AppCommand[SlashContext], ABC

Base class for all slash command classes.

checks abstractmethod property #

checks

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

component abstractmethod property #

component

Component that the command is registered with.

default_member_permissions abstractmethod property #

default_member_permissions

The default guild member permissions required to use this command.

Warning

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

Warning

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

defaults_to_ephemeral abstractmethod property #

defaults_to_ephemeral

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

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.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.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

is_dm_enabled abstractmethod property #

is_dm_enabled

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 #

is_global

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.

is_nsfw property #

is_nsfw

Whether a command should only be accessible in channels marked as NSFW.

metadata abstractmethod property #

metadata

Mutable mapping of metadata set for this command.

Note

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

name abstractmethod property #

name

Name of the command.

parent abstractmethod property #

parent

Object of the group this command is in.

tracked_command abstractmethod property #

tracked_command

Object of the actual command this object tracks if set.

tracked_command_id abstractmethod property #

tracked_command_id

ID of the actual command this object tracks if set.

type abstractmethod property #

type

The type of this command.

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

Parameters:

  • *checks (CheckSig[_ContextT_co], default: () ) –

    The checks to add.

Returns:

  • Self

    This command to enable chained calls

build abstractmethod #

build(*, component=None)

Get a builder object for this command.

Parameters:

  • component (Optional[Component], default: None ) –

    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.

Returns:

  • SlashCommandBuilder

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

copy abstractmethod #

copy(*, parent=None)

Create a copy of this command.

Parameters:

Returns:

  • Self

    The copy.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

Parameters:

  • check (CheckSig[_ContextT_co]) –

    The check to remove.

Raises:

  • ValueError

    If the provided check isn't found.

Returns:

  • Self

    This command to enable chained calls

set_hooks abstractmethod #

set_hooks(hooks)

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

Parameters:

  • hooks (Hooks[Context] | None) –

    The hooks that are triggered when the command is executed.

Returns:

  • Self

    This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The command instance to enable chained calls.

set_tracked_command abstractmethod #

set_tracked_command(command)

Set the global command this tracks.

Parameters:

  • command (PartialCommand) –

    Object of the global command this tracks.

Returns:

  • Self

    The command instance to enable chained calls.

Client #

Bases: ABC

Abstract interface of a Tanjun client.

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

cache abstractmethod property #

cache

Hikari cache instance this command client was initialised with.

components abstractmethod property #

components

Collection of the components this command client is using.

default_app_cmd_permissions abstractmethod property #

default_app_cmd_permissions

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

This may be overridden by Component.default_app_cmd_permissions and 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 #

defaults_to_ephemeral

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

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.respond unless the flags field is provided for the methods which support it.

This defaults to False.

Note

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

dms_enabled_for_app_cmds abstractmethod property #

dms_enabled_for_app_cmds

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

This defaults to True.

Note

This may be overridden by AppCommand.is_dm_enabled and Component.dms_enabled_for_app_cmds.

events abstractmethod property #

events

Object of the event manager this client was initialised with.

This is used for executing message commands if set.

injector abstractmethod property #

injector

The attached alluka dependency injection client.

is_alive abstractmethod property #

is_alive

Whether this client is alive.

is_case_sensitive abstractmethod property #

is_case_sensitive

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

listeners abstractmethod property #

listeners

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

loop abstractmethod property #

loop

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

metadata abstractmethod property #

metadata

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 #

prefixes

Collection of the prefixes set for this client.

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

rest abstractmethod property #

rest

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

server abstractmethod property #

server

Object of the Hikari interaction server provided for this client.

This is used for executing application commands if set.

shards abstractmethod property #

shards

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

voice abstractmethod property #

voice

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

add_client_callback abstractmethod #

add_client_callback(name, /, *callbacks)

Add a client callback.

Parameters:

  • name (Union[str, ClientCallbackNames]) –

    The name this callback is being registered to.

    This is case-insensitive.

  • *callbacks (MetaEventSig, default: () ) –

    The callbacks to register.

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

Returns:

  • Self

    The client instance to enable chained calls.

add_component abstractmethod #

add_component(component)

Add a component to this client.

Parameters:

  • component (Component) –

    The component to move to this client.

Returns:

  • Self

    The client instance to allow chained calls.

add_listener abstractmethod #

add_listener(event_type, /, *callbacks)

Add a listener to the client.

Parameters:

  • event_type (type[Event]) –

    The event type to add a listener for.

  • *callbacks (ListenerCallbackSig[_EventT], default: () ) –

    The callbacks to register as a listener.

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

Returns:

  • Self

    The client instance to enable chained calls.

check_message_name abstractmethod #

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

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

Note

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

Parameters:

  • name (str) –

    The name to match commands against.

  • case_sensitive (bool, default: True ) –

    Whether to match case sensitively.

Returns:

  • Iterator[tuple[str, MessageCommand]]

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

check_slash_name abstractmethod #

check_slash_name(name)

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

Note

This won't check the commands within command groups.

Parameters:

  • name (str) –

    Name to check against.

Returns:

clear_application_commands abstractmethod async #

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

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

Note

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

Parameters:

declare_application_command abstractmethod async #

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

Declare a single slash command for a bot.

Warning

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

Parameters:

Returns:

  • PartialCommand

    API representation of the command that was registered.

declare_application_commands abstractmethod async #

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

Declare a collection of slash commands for a bot.

Note

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

Parameters:

  • commands (Iterable[Union[AppCommand[Any], CommandBuilder]]) –

    Iterable of the commands objects or builders to register.

  • command_ids (Optional[Mapping[str, SnowflakeishOr[PartialCommand]]], default: None ) –

    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.

  • application (Optional[SnowflakeishOr[PartialApplication]], default: None ) –

    The application to register the commands with.

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

  • guild (UndefinedOr[SnowflakeishOr[PartialGuild]], default: UNDEFINED ) –

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

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

  • message_ids (Optional[Mapping[str, SnowflakeishOr[PartialCommand]]], default: None ) –

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

  • user_ids (Optional[Mapping[str, SnowflakeishOr[PartialCommand]]], default: None ) –

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

  • force (bool, default: False ) –

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

Returns:

  • Sequence[PartialCommand]

    API representations of the commands which were registered.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

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

declare_global_commands abstractmethod async #

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

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

Warning

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

Note

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

Parameters:

  • command_ids (Optional[Mapping[str, SnowflakeishOr[PartialCommand]]], default: None ) –

    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.

  • application (Optional[SnowflakeishOr[PartialApplication]], default: None ) –

    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 Client.rest.

  • guild (UndefinedOr[SnowflakeishOr[PartialGuild]], default: UNDEFINED ) –

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

    If left as None global commands will be set.

  • message_ids (Optional[Mapping[str, SnowflakeishOr[PartialCommand]]], default: None ) –

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

  • user_ids (Optional[Mapping[str, SnowflakeishOr[PartialCommand]]], default: None ) –

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

  • force (bool, default: False ) –

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

Returns:

  • Sequence[PartialCommand]

    API representations of the set commands.

dispatch_client_callback abstractmethod async #

dispatch_client_callback(name, /, *args)

Dispatch a client callback.

Parameters:

  • name (Union[str, ClientCallbackNames]) –

    The name of the callback to dispatch.

  • *args (Any, default: () ) –

    Positional arguments to pass to the callback(s).

Raises:

  • KeyError

    If no callbacks are registered for the given name.

get_callback_override abstractmethod #

get_callback_override(callback)

Get the override for a specific injected callback.

Parameters:

  • callback (CallbackSig[_T]) –

    The injected callback to get the override for.

Returns:

  • CallbackSig | None

    The override if found, else None.

get_client_callbacks abstractmethod #

get_client_callbacks(name)

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

Parameters:

Returns:

  • Collection[MetaEventSig]

    Collection of the callbacks for the provided name.

get_component_by_name abstractmethod #

get_component_by_name(name)

Get a component from this client by name.

Parameters:

  • name (str) –

    Name to get a component by.

Returns:

  • Component | None

    The component instance if found, else None.

get_type_dependency abstractmethod #

get_type_dependency(type_, /, *, default=...)

Get the implementation for an injected type.

Parameters:

  • type_ (type[_T]) –

    The associated type.

  • default (_DefaultT, default: ... ) –

    The default value to return if the type is not implemented.

Returns:

  • _T | _DefaultT

    The resolved type if found.

    If the type isn't implemented then the value of default will be returned if it is provided.

Raises:

  • KeyError

    If no dependency was found when no default was provided.

iter_commands abstractmethod #

iter_commands()

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

Returns:

iter_menu_commands abstractmethod #

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

Iterator over the menu commands registered to this client.

Parameters:

  • global_only (bool, default: False ) –

    Whether to only iterate over global menu commands.

  • type (Optional[CommandType], default: None ) –

    Menu command type to filter by.

Returns:

  • Iterator[MenuCommand]

    Iterator of the menu commands registered to this client.

iter_message_commands abstractmethod #

iter_message_commands()

Iterate over all the message commands registered to this client.

Returns:

  • Iterator[MessageCommand]

    Iterator of all the message commands registered to this client.

iter_slash_commands abstractmethod #

iter_slash_commands(*, global_only=False)

Iterate over all the slash commands registered to this client.

Parameters:

  • global_only (bool, default: False ) –

    Whether to only iterate over global slash commands.

Returns:

  • Iterator[BaseSlashCommand]

    Iterator of the slash commands registered to this client.

load_directory abstractmethod #

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

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

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

Parameters:

  • directory (Union[str, Path]) –

    Name of the directory to load modules from.

  • namespace (Optional[str], default: None ) –

    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 Client.load_modules if passed.

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

Returns:

  • Self

    This client instance to enable chained calls.

Raises:

  • 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 FailedModuleLoad.__cause__.

    Modules with no loaders are ignored.

  • ModuleNotFoundError

    If any of the modules aren't found.

load_directory_async abstractmethod async #

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

Asynchronous variant of Client.load_directory.

Unlike 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 Client.load_directory.

load_modules abstractmethod #

load_modules(*modules)

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

Note

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

Examples:

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

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

or

loader = tanjun.Component(name="trans component").load_from_scope().make_loader()

Parameters:

  • *modules (Union[str, Path], default: () ) –

    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.

Returns:

  • Self

    This client instance to enable chained calls.

Raises:

load_modules_async abstractmethod async #

load_modules_async(*modules)

Asynchronous variant of Client.load_modules.

Unlike 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 Client.load_modules.

reload_modules abstractmethod #

reload_modules(*modules)

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

Note

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

Examples:

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

Parameters:

  • *modules (Union[str, Path], default: () ) –

    Paths of one or more module to unload.

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

Returns:

  • Self

    This client instance to enable chained calls.

Raises:

reload_modules_async abstractmethod async #

reload_modules_async(*modules)

Asynchronous variant of Client.reload_modules.

Unlike 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 Client.reload_modules.

remove_callback_override abstractmethod #

remove_callback_override(callback)

Remove a callback override.

Parameters:

  • callback (CallbackSig[_T]) –

    The injected callback to remove the override for.

Returns:

  • Self

    The client instance to allow chaining.

Raises:

  • KeyError

    If no override is found for the callback.

remove_client_callback abstractmethod #

remove_client_callback(name, callback)

Remove a client callback.

Parameters:

  • name (Union[str, ClientCallbackNames]) –

    The name this callback is being registered to.

    This is case-insensitive.

  • callback (MetaEventSig) –

    The callback to remove from the client's callbacks.

Raises:

  • KeyError

    If the provided name isn't found.

  • ValueError

    If the provided callback isn't found.

Returns:

  • Self

    The client instance to enable chained calls.

remove_component abstractmethod #

remove_component(component)

Remove a component from this client.

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

Parameters:

  • component (Component) –

    The component to remove from this client.

Raises:

  • ValueError

    If the provided component isn't found.

Returns:

  • Self

    The client instance to allow chained calls.

remove_component_by_name abstractmethod #

remove_component_by_name(name)

Remove a component from this client by name.

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

Parameters:

  • name (str) –

    Name of the component to remove from this client.

Raises:

  • KeyError

    If the provided component name isn't found.

remove_listener abstractmethod #

remove_listener(event_type, callback)

Remove a listener from the client.

Parameters:

Raises:

  • KeyError

    If the provided event type isn't found.

  • ValueError

    If the provided callback isn't found.

Returns:

  • Self

    The client instance to enable chained calls.

remove_type_dependency abstractmethod #

remove_type_dependency(type_)

Remove a type dependency.

Parameters:

  • type_ (type[Any]) –

    The associated type.

Returns:

  • Self

    The client instance to allow chaining.

Raises:

  • KeyError

    If type is not registered.

set_callback_override abstractmethod #

set_callback_override(callback, override)

Override a specific injected callback.

Parameters:

  • callback (CallbackSig[_T]) –

    The injected callback to override.

  • override (CallbackSig[_T]) –

    The callback to use instead.

Returns:

  • Self

    The client instance to allow chaining.

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the client's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The client instance to enable chained calls.

set_type_dependency abstractmethod #

set_type_dependency(type_, value)

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

Parameters:

  • type_ (type[_T]) –

    The type of the dependency to add an implementation for.

  • value (_T) –

    The value of the dependency.

Returns:

  • Self

    The client instance to allow chaining.

unload_modules abstractmethod #

unload_modules(*modules)

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

Note

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

Examples:

For this to work the module has to have at least one unloading enabled 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()

Parameters:

  • *modules (Union[str, Path], default: () ) –

    Path of one or more modules to unload.

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

Returns:

  • Self

    This client instance to enable chained calls.

Raises:

with_client_callback abstractmethod #

with_client_callback(name)

Add a client callback through a decorator call.

Examples:

client = tanjun.Client.from_rest_bot(bot)

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

Parameters:

Returns:

  • Callable[[MetaEventSig], MetaEventSig]

    Decorator callback used to register the client callback.

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

with_listener abstractmethod #

with_listener(*event_types)

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

Examples:

client = tanjun.Client.from_gateway_bot(bot)

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

Parameters:

  • *event_types (type[Event], default: () ) –

    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.

Returns:

  • 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.Event regardless of client implementation detail.

Raises:

  • ValueError

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

ClientCallbackNames #

Bases: str, Enum

Enum of the standard client callback names.

These should be dispatched by all Client implementations.

CLOSED class-attribute instance-attribute #

CLOSED = 'closed'

Called when the client has finished closing.

No positional arguments are provided for this event.

CLOSING class-attribute instance-attribute #

CLOSING = 'closing'

Called when the client is initially instructed to close.

No positional arguments are provided for this event.

COMPONENT_ADDED class-attribute instance-attribute #

COMPONENT_ADDED = 'component_added'

Called when a component is added to an active client.

Warning

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

The first positional argument is the Component being added.

COMPONENT_REMOVED class-attribute instance-attribute #

COMPONENT_REMOVED = 'component_removed'

Called when a component is added to an active client.

Warning

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

The first positional argument is the Component being removed.

MENU_COMMAND_NOT_FOUND class-attribute instance-attribute #

MENU_COMMAND_NOT_FOUND = 'menu_command_not_found'

Called when a menu command is not found.

MenuContext is provided as the first positional argument.

MESSAGE_COMMAND_NOT_FOUND class-attribute instance-attribute #

MESSAGE_COMMAND_NOT_FOUND = 'message_command_not_found'

Called when a message command is not found.

MessageContext is provided as the first positional argument.

SLASH_COMMAND_NOT_FOUND class-attribute instance-attribute #

SLASH_COMMAND_NOT_FOUND = 'slash_command_not_found'

Called when a slash command is not found.

SlashContext is provided as the first positional argument.

STARTED class-attribute instance-attribute #

STARTED = 'started'

Called when the client has finished starting.

No positional arguments are provided for this event.

STARTING class-attribute instance-attribute #

STARTING = 'starting'

Called when the client is initially instructed to start.

No positional arguments are provided for this event.

ClientLoader #

Bases: ABC

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

has_load abstractmethod property #

has_load

Whether this loader will load anything.

has_unload abstractmethod property #

has_unload

Whether this loader will unload anything.

load abstractmethod #

load(client)

Load logic into a client instance.

Parameters:

  • client (Client) –

    The client to load commands and listeners for.

Returns:

  • bool

    Whether anything was loaded.

unload abstractmethod #

unload(client)

Unload logic from a client instance.

Parameters:

  • client (Client) –

    The client to unload commands and listeners from.

Returns:

  • bool

    Whether anything was unloaded.

Component #

Bases: ABC

Standard interface of a Tanjun component.

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

client abstractmethod property #

client

Tanjun client this component is bound to.

default_app_cmd_permissions abstractmethod property #

default_app_cmd_permissions

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

This may be overridden by 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 #

defaults_to_ephemeral

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

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.respond unless the flags field is provided for the methods which support it.

Note

This may be overridden by 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 #

dms_enabled_for_app_cmds

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

Note

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

is_case_sensitive abstractmethod property #

is_case_sensitive

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

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

listeners abstractmethod property #

listeners

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

loop abstractmethod property #

loop

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

menu_commands abstractmethod property #

menu_commands

Collection of the menu commands in this component.

message_commands abstractmethod property #

message_commands

Collection of the message commands in this component.

metadata abstractmethod property #

metadata

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 #

name

Component's unique identifier.

Note

This will be preserved between copies of a component.

slash_commands abstractmethod property #

slash_commands

Collection of the slash commands in this component.

add_listener abstractmethod #

add_listener(event, /, *callbacks)

Add a listener to this component.

Parameters:

Returns:

  • Self

    The component to enable chained calls.

add_menu_command abstractmethod #

add_menu_command(command)

Add a menu command to this component.

Parameters:

Returns:

  • Self

    The component to enable chained calls.

add_message_command abstractmethod #

add_message_command(command)

Add a message command to this component.

Parameters:

Returns:

  • Self

    The component to enable chained calls.

add_slash_command abstractmethod #

add_slash_command(command)

Add a slash command to this component.

Parameters:

Returns:

  • Self

    The component to enable chained calls.

check_message_name abstractmethod #

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

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

Note

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

Note

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

Parameters:

  • name (str) –

    The name to check for command matches.

  • case_sensitive (bool, default: True ) –

    Whether to perform a case-sensitive match.

Returns:

  • Iterator[tuple[str, MessageCommand[Any]]]

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

check_slash_name abstractmethod #

check_slash_name(name)

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

Note

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

Parameters:

  • name (str) –

    The name to check for command matches.

Returns:

close abstractmethod async #

close(*, unbind=False)

Close the component.

Parameters:

  • unbind (bool, default: False ) –

    Whether to unbind from the client after this is closed.

Raises:

execute_autocomplete abstractmethod #

execute_autocomplete(ctx)

Execute an autocomplete context.

Note

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

Parameters:

Returns:

  • Coroutine[Any, Any, None] | None

    Coroutine used to wait for the command execution to finish.

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

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

execute_menu abstractmethod async #

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

Execute a menu context.

Parameters:

Returns:

  • Coroutine[Any, 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:

  • CommandError

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

  • HaltExecution

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

execute_message abstractmethod async #

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

Execute a message context.

Parameters:

Returns:

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

  • CommandError

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

  • HaltExecution

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

execute_slash abstractmethod async #

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

Execute a slash context.

Parameters:

Returns:

  • Coroutine[Any, 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:

  • CommandError

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

  • HaltExecution

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

open abstractmethod async #

open()

Start the component.

Raises:

  • RuntimeError

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

remove_listener abstractmethod #

remove_listener(event, listener)

Remove a listener from this component.

Parameters:

Raises:

  • ValueError

    If the listener is not registered for the provided event.

Returns:

  • Self

    The component to enable chained calls.

remove_menu_command abstractmethod #

remove_menu_command(command)

Remove a menu command from this component.

Parameters:

Returns:

  • Self

    The component to enable chained calls.

remove_message_command abstractmethod #

remove_message_command(command)

Remove a message command from this component.

Parameters:

Raises:

  • ValueError

    If the provided command isn't found.

Returns:

  • Self

    The component to enable chained calls.

remove_slash_command abstractmethod #

remove_slash_command(command)

Remove a slash command from this component.

Parameters:

Raises:

  • ValueError

    If the provided command isn't found.

Returns:

  • Self

    The component to enable chained calls.

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the component's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The component instance to enable chained calls.

with_listener abstractmethod #

with_listener(*event_types)

Add a listener to this component through a decorator call.

Parameters:

  • *event_types (type[Event], default: () ) –

    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.

Returns:

Raises:

  • ValueError

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

with_menu_command abstractmethod #

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

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

Parameters:

  • command (MenuCommand, default: None ) –

    The command to add.

  • copy (bool, default: False ) –

    Whether to copy the command before adding it.

Returns:

with_message_command abstractmethod #

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

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

Parameters:

  • command (MessageCommand, default: None ) –

    The command to add.

  • copy (bool, default: False ) –

    Whether to copy the command before adding it.

Returns:

with_slash_command abstractmethod #

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

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

Parameters:

  • command (BaseSlashCommand, default: None ) –

    The command to add.

  • copy (bool, default: False ) –

    Whether to copy the command before adding it.

Returns:

Context #

Bases: Context

Interface for the context of a command execution.

author abstractmethod property #

author

Object of the user who triggered this command.

cache abstractmethod property #

cache

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

channel_id abstractmethod property #

channel_id

ID of the channel this command was triggered in.

client abstractmethod property #

client

Tanjun Client implementation this context was spawned by.

command abstractmethod property #

command

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 #

component

Object of the 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 #

created_at

When this context was created.

events abstractmethod property #

events

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

guild_id abstractmethod property #

guild_id

ID of the guild this command was executed in.

Will be None for all DM command executions.

has_responded abstractmethod property #

has_responded

Whether an initial response has been made for this context.

is_human abstractmethod property #

is_human

Whether this command execution was triggered by a human.

Will be False for bot and webhook triggered commands.

member abstractmethod property #

member

Guild member object of this command's author.

Will be None for DM command executions.

rest abstractmethod property #

rest

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

server abstractmethod property #

server

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

shard abstractmethod property #

shard

Shard that triggered the context.

Note

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

shards abstractmethod property #

shards

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

triggering_name abstractmethod property #

triggering_name

Command name this execution was triggered with.

voice abstractmethod property #

voice

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

delete_initial_response abstractmethod async #

delete_initial_response()

Delete the initial response after invoking this context.

Raises:

delete_last_response abstractmethod async #

delete_last_response()

Delete the last response after invoking this context.

Raises:

edit_initial_response abstractmethod async #

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

Edit the initial response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

edit_last_response abstractmethod async #

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

Edit the last response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using Context.get_channelif you have the CacheComponents.GUILD_CHANNELS cache component enabled.

Returns:

  • TextableChannel

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

Raises:

  • UnauthorizedError

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

  • ForbiddenError

    If you are missing the READ_MESSAGES permission in the channel.

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using Context.get_guild if you have the CacheComponents.GUILDS cache component enabled.

Returns:

  • Guild | None

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

Raises:

fetch_initial_response abstractmethod async #

fetch_initial_response()

Fetch the initial response for this context.

Raises:

fetch_last_response abstractmethod async #

fetch_last_response()

Fetch the last response for this context.

Raises:

get_channel abstractmethod #

get_channel()

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

Note

This method requires the CacheComponents.GUILD_CHANNELS cache component.

Returns:

  • TextableGuildChannel | None

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

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires the CacheComponents.GUILDS cache component.

Returns:

  • Guild | None

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

respond abstractmethod async #

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

Respond to this context.

Parameters:

Returns:

  • Message | None

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

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

ExecutableCommand #

Bases: ABC, Generic[_ContextT_co]

Base class for all commands that can be executed.

checks abstractmethod property #

checks

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

component abstractmethod property #

component

Component that the command is registered with.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

metadata abstractmethod property #

metadata

Mutable mapping of metadata set for this command.

Note

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

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

Parameters:

  • *checks (CheckSig[_ContextT_co], default: () ) –

    The checks to add.

Returns:

  • Self

    This command to enable chained calls

copy abstractmethod #

copy()

Create a copy of this command.

Returns:

  • Self

    A copy of this command.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

Parameters:

  • check (CheckSig[_ContextT_co]) –

    The check to remove.

Raises:

  • ValueError

    If the provided check isn't found.

Returns:

  • Self

    This command to enable chained calls

set_hooks abstractmethod #

set_hooks(hooks)

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

Parameters:

  • hooks (Hooks[Context] | None) –

    The hooks that are triggered when the command is executed.

Returns:

  • Self

    This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The command instance to enable chained calls.

Hooks #

Bases: ABC, Generic[_ContextT_contra]

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

add_on_error abstractmethod #

add_on_error(callback)

Add an error callback to this hook object.

Note

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

Parameters:

  • callback (ErrorHookSig[_ContextT_contra]) –

    The callback to add to this hook.

    This callback should take two positional arguments (of type 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.

Returns:

  • Self

    The hook object to enable method chaining.

add_on_parser_error abstractmethod #

add_on_parser_error(callback)

Add a parser error callback to this hook object.

Parameters:

  • callback (ParserHookSig[_ContextT_contra]) –

    The callback to add to this hook.

    This callback should take two positional arguments (of type 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.

Returns:

  • Self

    The hook object to enable method chaining.

add_on_success abstractmethod #

add_on_success(callback)

Add a success callback to this hook object.

Parameters:

  • callback (HookSig[_ContextT_contra]) –

    The callback to add to this hook.

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

Returns:

  • Self

    The hook object to enable method chaining.

add_post_execution abstractmethod #

add_post_execution(callback)

Add a post-execution callback to this hook object.

Parameters:

  • callback (HookSig[_ContextT_contra]) –

    The callback to add to this hook.

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

Returns:

  • Self

    The hook object to enable method chaining.

add_pre_execution abstractmethod #

add_pre_execution(callback)

Add a pre-execution callback for this hook object.

Parameters:

  • callback (HookSig[_ContextT_contra]) –

    The callback to add to this hook.

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

Returns:

  • Self

    The hook object to enable method chaining.

with_on_error abstractmethod #

with_on_error(callback)

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

Note

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

Examples:

hooks = AnyHooks()

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

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

Parameters:

  • callback (ErrorHookSig) –

    The callback to add to this hook.

    This callback should take two positional arguments (of type 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.

Returns:

with_on_parser_error abstractmethod #

with_on_parser_error(callback)

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

Examples:

hooks = AnyHooks()

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

Parameters:

  • callback (ParserHookSig) –

    The parser error callback to add to this hook.

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

Returns:

  • HookSig

    The callback which was added.

with_on_success abstractmethod #

with_on_success(callback)

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

Examples:

hooks = AnyHooks()

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

Parameters:

  • callback (HookSig) –

    The success callback to add to this hook.

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

Returns:

  • HookSig

    The success callback which was added.

with_post_execution abstractmethod #

with_post_execution(callback)

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

Examples:

hooks = AnyHooks()

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

Parameters:

  • callback (HookSig) –

    The post-execution callback to add to this hook.

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

Returns:

  • HookSig

    The post-execution callback which was seaddedt.

with_pre_execution abstractmethod #

with_pre_execution(callback)

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

Examples:

hooks = AnyHooks()

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

Parameters:

  • callback (HookSig) –

    The pre-execution callback to add to this hook.

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

Returns:

  • HookSig

    The pre-execution callback which was added.

MenuCommand #

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

A contextmenu command.

callback abstractmethod property #

callback

Callback which is called during execution.

checks abstractmethod property #

checks

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

component abstractmethod property #

component

Component that the command is registered with.

default_member_permissions abstractmethod property #

default_member_permissions

The default guild member permissions required to use this command.

Warning

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

Warning

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

defaults_to_ephemeral abstractmethod property #

defaults_to_ephemeral

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

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.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.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

is_dm_enabled abstractmethod property #

is_dm_enabled

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 #

is_global

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.

is_nsfw property #

is_nsfw

Whether a command should only be accessible in channels marked as NSFW.

metadata abstractmethod property #

metadata

Mutable mapping of metadata set for this command.

Note

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

name abstractmethod property #

name

Name of the command.

tracked_command abstractmethod property #

tracked_command

Object of the actual command this object tracks if set.

tracked_command_id abstractmethod property #

tracked_command_id

ID of the actual command this object tracks if set.

type abstractmethod property #

type

The menu type(s) this is for.

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

Parameters:

  • *checks (CheckSig[_ContextT_co], default: () ) –

    The checks to add.

Returns:

  • Self

    This command to enable chained calls

build abstractmethod #

build(*, component=None)

Get a builder object for this command.

Parameters:

  • component (Optional[Component], default: None ) –

    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.

Returns:

  • ContextMenuCommandBuilder

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

copy abstractmethod #

copy()

Create a copy of this command.

Returns:

  • Self

    A copy of this command.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

Parameters:

  • check (CheckSig[_ContextT_co]) –

    The check to remove.

Raises:

  • ValueError

    If the provided check isn't found.

Returns:

  • Self

    This command to enable chained calls

set_hooks abstractmethod #

set_hooks(hooks)

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

Parameters:

  • hooks (Hooks[Context] | None) –

    The hooks that are triggered when the command is executed.

Returns:

  • Self

    This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The command instance to enable chained calls.

set_tracked_command abstractmethod #

set_tracked_command(command)

Set the global command this tracks.

Parameters:

  • command (PartialCommand) –

    Object of the global command this tracks.

Returns:

  • Self

    The command instance to enable chained calls.

MenuContext #

Bases: AppCommandContext, ABC

Interface of a menu command context.

author abstractmethod property #

author

Object of the user who triggered this command.

cache abstractmethod property #

cache

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

channel_id abstractmethod property #

channel_id

ID of the channel this command was triggered in.

client abstractmethod property #

client

Tanjun Client implementation this context was spawned by.

command abstractmethod property #

command

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.

component abstractmethod property #

component

Object of the 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 #

created_at

When this context was created.

defaults_to_ephemeral abstractmethod property #

defaults_to_ephemeral

Whether the context is marked as defaulting to ephemeral response.

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.respond unless the flags field is provided for the methods which support it.

events abstractmethod property #

events

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

expires_at abstractmethod property #

expires_at

When this application command context expires.

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

guild_id abstractmethod property #

guild_id

ID of the guild this command was executed in.

Will be None for all DM command executions.

has_been_deferred abstractmethod property #

has_been_deferred

Whether the initial response for this context has been deferred.

Warning

If this is True when AppCommandContext.has_responded is False then AppCommandContext.edit_initial_response will need to be used to create the initial response rather than AppCommandContext.create_initial_response.

has_responded abstractmethod property #

has_responded

Whether an initial response has been made for this context.

interaction abstractmethod property #

interaction

Interaction this context is for.

is_human abstractmethod property #

is_human

Whether this command execution was triggered by a human.

Will be False for bot and webhook triggered commands.

member abstractmethod property #

member

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

rest abstractmethod property #

rest

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

server abstractmethod property #

server

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

shard abstractmethod property #

shard

Shard that triggered the context.

Note

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

shards abstractmethod property #

shards

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

target abstractmethod property #

target

Object of the entity this menu targets.

target_id abstractmethod property #

target_id

ID of the entity this menu command context targets.

triggering_name abstractmethod property #

triggering_name

Command name this execution was triggered with.

type abstractmethod property #

type

The type of context menu this context is for.

voice abstractmethod property #

voice

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

create_followup abstractmethod async #

create_followup(content=hikari.UNDEFINED, *, delete_after=None, ephemeral=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, tts=hikari.UNDEFINED, flags=hikari.UNDEFINED)

Create a followup response for this context.

Warning

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

Parameters:

Returns:

  • Message

    The created message object.

Raises:

  • NotFoundError

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

  • BadRequestError

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

  • ValueError

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

    If the interaction will have expired before delete_after is reached.

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

create_initial_response abstractmethod async #

create_initial_response(content=hikari.UNDEFINED, *, delete_after=None, ephemeral=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, flags=hikari.UNDEFINED, tts=hikari.UNDEFINED)

Create the initial response for this context.

Warning

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

Parameters:

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • NotFoundError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

create_modal_response abstractmethod async #

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

Send a modal as the initial response for this context.

Warning

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

Parameters:

Raises:

  • ValueError

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

  • BadRequestError

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

  • UnauthorizedError

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

  • NotFoundError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

defer abstractmethod async #

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

Defer the initial response for this context.

Note

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

Parameters:

  • ephemeral (Optional[bool], default: None ) –

    Whether the deferred response should be ephemeral.

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

  • flags (Union[UndefinedType, int, MessageFlag], default: UNDEFINED ) –

    The flags to use for the initial response.

delete_initial_response abstractmethod async #

delete_initial_response()

Delete the initial response after invoking this context.

Raises:

delete_last_response abstractmethod async #

delete_last_response()

Delete the last response after invoking this context.

Raises:

edit_initial_response abstractmethod async #

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

Edit the initial response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

edit_last_response abstractmethod async #

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

Edit the last response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using Context.get_channelif you have the CacheComponents.GUILD_CHANNELS cache component enabled.

Returns:

  • TextableChannel

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

Raises:

  • UnauthorizedError

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

  • ForbiddenError

    If you are missing the READ_MESSAGES permission in the channel.

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using Context.get_guild if you have the CacheComponents.GUILDS cache component enabled.

Returns:

  • Guild | None

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

Raises:

fetch_initial_response abstractmethod async #

fetch_initial_response()

Fetch the initial response for this context.

Raises:

fetch_last_response abstractmethod async #

fetch_last_response()

Fetch the last response for this context.

Raises:

get_channel abstractmethod #

get_channel()

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

Note

This method requires the CacheComponents.GUILD_CHANNELS cache component.

Returns:

  • TextableGuildChannel | None

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

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires the CacheComponents.GUILDS cache component.

Returns:

  • Guild | None

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

mark_not_found abstractmethod async #

mark_not_found()

Mark this context as not found.

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

resolve_to_member abstractmethod #

resolve_to_member(*, default=...)

Resolve a user context menu context to a member object.

Returns:

Raises:

  • TypeError

    If the context is not a user menu context.

  • LookupError

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

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

resolve_to_message abstractmethod #

resolve_to_message()

Resolve a message context menu to a message object.

Returns:

  • Message

    The resolved message.

Raises:

  • TypeError

    if the context is not for a message menu.

resolve_to_user abstractmethod #

resolve_to_user()

Resolve a user context menu context to a user object.

Returns:

Raises:

  • TypeError

    If the context is not a user menu context.

respond abstractmethod async #

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

Respond to this context.

Parameters:

Returns:

  • Message | None

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

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

set_command abstractmethod #

set_command(command)

Set the command for this context.

Parameters:

set_ephemeral_default abstractmethod #

set_ephemeral_default(state)

Set the ephemeral default state for this context.

Parameters:

  • state (bool) –

    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.

MessageCommand #

Bases: ExecutableCommand[MessageContext], ABC, Generic[_MessageCallbackSigT]

Standard interface of a message command.

callback abstractmethod property #

callback

Callback which is called during execution.

Note

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

checks abstractmethod property #

checks

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

component abstractmethod property #

component

Component that the command is registered with.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

metadata abstractmethod property #

metadata

Mutable mapping of metadata set for this command.

Note

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

names abstractmethod property #

names

Collection of this command's names.

parent abstractmethod property #

parent

Parent group of this command if applicable.

parser abstractmethod property #

parser

Parser for this command.

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

Parameters:

  • *checks (CheckSig[_ContextT_co], default: () ) –

    The checks to add.

Returns:

  • Self

    This command to enable chained calls

copy abstractmethod #

copy(*, parent=None)

Create a copy of this command.

Parameters:

Returns:

  • Self

    The copy.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

Parameters:

  • check (CheckSig[_ContextT_co]) –

    The check to remove.

Raises:

  • ValueError

    If the provided check isn't found.

Returns:

  • Self

    This command to enable chained calls

set_hooks abstractmethod #

set_hooks(hooks)

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

Parameters:

  • hooks (Hooks[Context] | None) –

    The hooks that are triggered when the command is executed.

Returns:

  • Self

    This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The command instance to enable chained calls.

set_parent abstractmethod #

set_parent(parent)

Set the parent of this command.

Parameters:

Returns:

  • Self

    The command instance to enable chained calls.

set_parser abstractmethod #

set_parser(parser)

Set the for this message command.

Parameters:

Returns:

  • Self

    The command instance to enable chained calls.

Raises:

  • ValueError

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

MessageCommandGroup #

Bases: MessageCommand[_MessageCallbackSigT], ABC

Standard interface of a message command group.

callback abstractmethod property #

callback

Callback which is called during execution.

Note

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

checks abstractmethod property #

checks

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

commands abstractmethod property #

commands

Collection of the commands in this group.

Note

This may include command groups.

component abstractmethod property #

component

Component that the command is registered with.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

metadata abstractmethod property #

metadata

Mutable mapping of metadata set for this command.

Note

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

names abstractmethod property #

names

Collection of this command's names.

parent abstractmethod property #

parent

Parent group of this command if applicable.

parser abstractmethod property #

parser

Parser for this command.

add_check abstractmethod #

add_check(*checks)

Add a check to the command.

Parameters:

  • *checks (CheckSig[_ContextT_co], default: () ) –

    The checks to add.

Returns:

  • Self

    This command to enable chained calls

add_command abstractmethod #

add_command(command)

Add a command to this group.

Parameters:

Returns:

  • Self

    The group instance to enable chained calls.

copy abstractmethod #

copy(*, parent=None)

Create a copy of this command.

Parameters:

Returns:

  • Self

    The copy.

remove_check abstractmethod #

remove_check(check)

Remove a check from the command.

Parameters:

  • check (CheckSig[_ContextT_co]) –

    The check to remove.

Raises:

  • ValueError

    If the provided check isn't found.

Returns:

  • Self

    This command to enable chained calls

remove_command abstractmethod #

remove_command(command)

Remove a command from this group.

Parameters:

Raises:

  • ValueError

    If the provided command isn't found.

Returns:

  • Self

    The group instance to enable chained calls.

set_hooks abstractmethod #

set_hooks(hooks)

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

Parameters:

  • hooks (Hooks[Context] | None) –

    The hooks that are triggered when the command is executed.

Returns:

  • Self

    This command to enable chained calls

set_metadata abstractmethod #

set_metadata(key, value)

Set a field in the command's metadata.

Parameters:

  • key (Any) –

    Metadata key to set.

  • value (Any) –

    Metadata value to set.

Returns:

  • Self

    The command instance to enable chained calls.

set_parent abstractmethod #

set_parent(parent)

Set the parent of this command.

Parameters:

Returns:

  • Self

    The command instance to enable chained calls.

set_parser abstractmethod #

set_parser(parser)

Set the for this message command.

Parameters:

Returns:

  • Self

    The command instance to enable chained calls.

Raises:

  • ValueError

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

with_command abstractmethod #

with_command(command)

Add a command to this group through a decorator call.

Parameters:

Returns:

MessageContext #

Bases: Context, ABC

Interface of a message command specific context.

author abstractmethod property #

author

Object of the user who triggered this command.

cache abstractmethod property #

cache

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

channel_id abstractmethod property #

channel_id

ID of the channel this command was triggered in.

client abstractmethod property #

client

Tanjun Client implementation this context was spawned by.

command abstractmethod property #

command

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.

component abstractmethod property #

component

Object of the 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.

content abstractmethod property #

content

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

created_at abstractmethod property #

created_at

When this context was created.

events abstractmethod property #

events

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

guild_id abstractmethod property #

guild_id

ID of the guild this command was executed in.

Will be None for all DM command executions.

has_responded abstractmethod property #

has_responded

Whether an initial response has been made for this context.

is_human abstractmethod property #

is_human

Whether this command execution was triggered by a human.

Will be False for bot and webhook triggered commands.

member abstractmethod property #

member

Guild member object of this command's author.

Will be None for DM command executions.

message abstractmethod property #

message

Message that triggered the context.

rest abstractmethod property #

rest

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

server abstractmethod property #

server

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

shard abstractmethod property #

shard

Shard that triggered the context.

Note

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

shards abstractmethod property #

shards

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

triggering_name abstractmethod property #

triggering_name

Command name this execution was triggered with.

triggering_prefix abstractmethod property #

triggering_prefix

Prefix that triggered the context.

voice abstractmethod property #

voice

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

delete_initial_response abstractmethod async #

delete_initial_response()

Delete the initial response after invoking this context.

Raises:

delete_last_response abstractmethod async #

delete_last_response()

Delete the last response after invoking this context.

Raises:

edit_initial_response abstractmethod async #

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

Edit the initial response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

edit_last_response abstractmethod async #

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

Edit the last response for this context.

Parameters:

Returns:

  • Message

    The message that has been edited.

Raises:

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_channel abstractmethod async #

fetch_channel()

Fetch the channel the context was invoked in.

Note

This performs an API call. Consider using Context.get_channelif you have the CacheComponents.GUILD_CHANNELS cache component enabled.

Returns:

  • TextableChannel

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

Raises:

  • UnauthorizedError

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

  • ForbiddenError

    If you are missing the READ_MESSAGES permission in the channel.

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • RateLimitTooLongError

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

  • InternalServerError

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

fetch_guild abstractmethod async #

fetch_guild()

Fetch the guild the context was invoked in.

Note

This performs an API call. Consider using Context.get_guild if you have the CacheComponents.GUILDS cache component enabled.

Returns:

  • Guild | None

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

Raises:

fetch_initial_response abstractmethod async #

fetch_initial_response()

Fetch the initial response for this context.

Raises:

fetch_last_response abstractmethod async #

fetch_last_response()

Fetch the last response for this context.

Raises:

get_channel abstractmethod #

get_channel()

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

Note

This method requires the CacheComponents.GUILD_CHANNELS cache component.

Returns:

  • TextableGuildChannel | None

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

get_guild abstractmethod #

get_guild()

Fetch the guild that the context was invoked in.

Note

This method requires the CacheComponents.GUILDS cache component.

Returns:

  • Guild | None

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

respond abstractmethod async #

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

Respond to this context.

Parameters:

Returns:

  • Message

    The message that has been created.

Raises:

  • 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 or both sticker and stickers are passed.

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

MessageParser #

Bases: ABC

Base class for a message parser.

copy abstractmethod #

copy()

Copy the parser.

Returns:

  • Self

    A copy of the parser.

parse abstractmethod async #

parse(ctx)

Parse a message context.

Warning

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

Parameters:

Returns:

  • dict[str, Any]

    Dictionary of argument names to the parsed values for them.

Raises:

validate_arg_keys abstractmethod #

validate_arg_keys(callback_name, names)

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

Parameters:

  • callback_name (str) –

    The callback's name for use in raised errors.

  • names (Container[str]) –

    Key names of the callback's keyword arguments.

Raises:

  • ValueError

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

SlashCommand #

Bases: BaseSlashCommand, ABC, Generic[_SlashCallbackSigT]

A command that can be executed in a slash context.

callback abstractmethod property #

callback

Callback which is called during execution.

checks abstractmethod property #

checks

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

component abstractmethod property #

component

Component that the command is registered with.

default_member_permissions abstractmethod property #

default_member_permissions

The default guild member permissions required to use this command.

Warning

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

Warning

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

defaults_to_ephemeral abstractmethod property #

defaults_to_ephemeral

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

This effects calls to AppCommandContext.create_followup, AppCommandContext.create_initial_response, AppCommandContext.defer and AppCommandContext.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.

float_autocompletes abstractmethod property #

float_autocompletes

Collection of the float option autocompletes.

hooks abstractmethod property #

hooks

Hooks that are triggered when the command is executed.

int_autocompletes abstractmethod property #

int_autocompletes

Collection of the integer option autocompletes.

is_dm_enabled abstractmethod property #

is_dm_enabled

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 #

is_global

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.

is_nsfw property