Skip to content

tanjun#

A flexible command framework designed to extend Hikari.

Examples:

A Tanjun client can be quickly initialised from a Hikari gateway bot through tanjun.Client.from_gateway_bot, this enables both slash (interaction) and message command execution:

bot = hikari.GatewayBot("BOT_TOKEN")

# As a note, unless event_managed=False is passed here then this client
# will be managed based on gateway startup and stopping events.
# mention_prefix=True instructs the client to also set mention prefixes on the
# first startup.
client = tanjun.Client.from_gateway_bot(bot, declare_global_commands=True, mention_prefix=True)

component = tanjun.Component()
client.add_component(component)

# Declare a message command with some basic parser logic.
@component.with_command
@tanjun.with_greedy_argument("name", default="World")
@tanjun.as_message_command("test")
async def test_command(ctx: tanjun.abc.Context, name: str) -> None:
    await ctx.respond(f"Hello, {name}!")

# Declare a ping slash command
@component.with_command
@tanjun.with_user_slash_option("user", "The user facing command option's description", default=None)
@tanjun.as_slash_command("hello", "The command's user facing description")
async def hello(ctx: tanjun.abc.Context, user: hikari.User | None) -> None:
    user = user or ctx.author
    await ctx.respond(f"Hello, {user}!")

Alternatively, the client can also be built from a RESTBot but this will only enable slash (interaction) command execution:

bot = hikari.RESTBot("BOT_TOKEN", "Bot")

# declare_global_commands=True instructs the client to set the global commands
# for the relevant bot on first startup (this will replace any previously
# declared commands).
client = tanjun.Client.from_rest_bot(bot, declare_global_commands=True)

# This will load components from modules based on loader functions.
# For more information on this see [tanjun.as_loader][].
client.load_modules("module.paths")

# Note, unlike a gateway bound bot, the rest bot will not automatically start
# itself due to the lack of Hikari lifetime events in this environment and
# will have to be started after the Hikari client.
async def main() -> None:
    await bot.start()
    async with client:
        await bot.join()

For more extensive examples see the repository's examples.

There are also written tutorials that cover making a bot from scratch through to advanced concepts like Dependency Injection.

AnyHooks = Hooks[tanjun.Context] module-attribute #

Hooks that can be used with any context.

Note

This is shorthand for Hooks[tanjun.abc.Context].

MessageHooks = Hooks[tanjun.MessageContext] module-attribute #

Hooks that can be used with a message context.

Note

This is shorthand for Hooks[tanjun.abc.MessageContext].

MissingDependencyError = alluka.MissingDependencyError module-attribute #

SlashHooks = Hooks[tanjun.SlashContext] module-attribute #

Hooks that can be used with a slash context.

Note

This is shorthand for Hooks[tanjun.abc.SlashContext].

to_channel: typing.Final[ToChannel] = ToChannel() module-attribute #

Convert user input to a hikari.channels.PartialChannel object.

to_colour: typing.Final[collections.Callable[[_ArgumentT], hikari.Color]] = to_color module-attribute #

Convert user input to a hikari.colors.Color object.

to_emoji: typing.Final[ToEmoji] = ToEmoji() module-attribute #

Convert user input to a cached hikari.emojis.KnownCustomEmoji object.

Note

If you just want to convert inpute to a hikari.emojis.Emoji, hikari.emojis.CustomEmoji or hikari.emojis.UnicodeEmoji without making any cache or REST calls then you can just use the relevant hikari.emojis.Emoji.parse, hikari.emojis.CustomEmoji.parse or hikari.emojis.UnicodeEmoji.parse methods.

to_guild: typing.Final[ToGuild] = ToGuild() module-attribute #

Convert user input to a hikari.guilds.Guild object.

to_invite: typing.Final[ToInvite] = ToInvite() module-attribute #

Convert user input to a cached hikari.invites.InviteWithMetadata object.

to_invite_with_metadata: typing.Final[ToInviteWithMetadata] = ToInviteWithMetadata() module-attribute #

Convert user input to a hikari.invites.Invite object.

to_member: typing.Final[ToMember] = ToMember() module-attribute #

Convert user input to a hikari.guilds.Member object.

to_message: typing.Final[ToMessage] = ToMessage() module-attribute #

Convert user input to a hikari.messages.Message object.

to_presence: typing.Final[ToPresence] = ToPresence() module-attribute #

Convert user input to a cached hikari.presences.MemberPresence.

to_role: typing.Final[ToRole] = ToRole() module-attribute #

Convert user input to a hikari.guilds.Role object.

to_snowflake: typing.Final[collections.Callable[[_ArgumentT], hikari.Snowflake]] = parse_snowflake module-attribute #

Convert user input to a hikari.snowflakes.Snowflake.

Note

This also range validates the input.

to_user: typing.Final[ToUser] = ToUser() module-attribute #

Convert user input to a hikari.users.User object.

to_voice_state: typing.Final[ToVoiceState] = ToVoiceState() module-attribute #

Convert user input to a cached hikari.voices.VoiceState.

BucketResource #

Bases: int, enum.Enum

Resource target types used within command calldowns and concurrency limiters.

CHANNEL = 2 class-attribute #

A per-channel resource bucket.

GLOBAL = 7 class-attribute #

A global resource bucket.

GUILD = 6 class-attribute #

A per-guild resource bucket.

When executed in a DM this will be per-DM.

MEMBER = 1 class-attribute #

A per-guild member resource bucket.

When executed in a DM this will be per-DM.

PARENT_CHANNEL = 3 class-attribute #

A per-parent channel resource bucket.

For DM channels this will be per-DM, for guild channels with no parents this'll be per-guild.

TOP_ROLE = 5 class-attribute #

A per-highest role resource bucket.

When executed in a DM this will be per-DM, with this defaulting to targeting the @everyone role if they have no real roles.

USER = 0 class-attribute #

A per-user resource bucket.

Client #

Bases: tanjun.Client

Tanjun's standard tanjun.abc.Client implementation.

This implementation supports dependency injection for checks, command callbacks, prefix getters and event listeners. For more information on how this works see alluka.

Note

By default this client includes a parser error handling hook which will by overwritten if you call tanjun.Client.set_hooks.

__init__(rest, *, cache=None, events=None, server=None, shards=None, voice=None, event_managed=False, injector=None, mention_prefix=False, set_global_commands=False, declare_global_commands=False, command_ids=None, message_ids=None, user_ids=None, _stack_level=0) #

Initialise a Tanjun client.

Note

For a quicker way to initiate this client around a standard bot aware client, see tanjun.Client.from_gateway_bot and tanjun.Client.from_rest_bot.

PARAMETER DESCRIPTION
rest

The Hikari REST client this will use.

TYPE: hikari.api.RESTClient

cache

The Hikari cache client this will use if applicable.

TYPE: typing.Optional[hikari.api.Cache] DEFAULT: None

events

The Hikari event manager client this will use if applicable.

This is necessary for message command dispatch and will also be necessary for interaction command dispatch if server isn't provided.

TYPE: typing.Optional[hikari.api.EventManager] DEFAULT: None

server

The Hikari interaction server client this will use if applicable.

This is used for interaction command dispatch if interaction events aren't being received from the event manager.

TYPE: typing.Optional[hikari.api.InteractionServer] DEFAULT: None

shards

The Hikari shard aware client this will use if applicable.

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

voice

The Hikari voice component this will use if applicable.

TYPE: typing.Optional[hikari.api.VoiceComponent] DEFAULT: None

event_managed

Whether or not this client is managed by the event manager.

An event managed client will be automatically started and closed based on Hikari's lifetime events.

This can only be passed as True if events is also provided.

TYPE: bool DEFAULT: False

injector

The alluka client this should use for dependency injection.

If not provided then the client will initialise its own DI client.

TYPE: typing.Optional[alluka.abc.Client] DEFAULT: None

mention_prefix

Whether or not mention prefixes should be automatically set when this client is first started.

It should be noted that this only applies to message commands.

TYPE: bool DEFAULT: False

declare_global_commands

Whether or not to automatically set global slash commands when this client is first started.

If one or more guild objects/IDs are passed here then the registered global commands will be set on the specified guild(s) at startup rather than globally.

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

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialGuild], hikari.SnowflakeishOr[hikari.PartialGuild], bool] DEFAULT: False

set_global_commands

Deprecated as of v2.1.1a1 alias of declare_global_commands.

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

command_ids

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

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

This field is complementary to declare_global_commands and, while it isn't necessarily required, this will in some situations help avoid permissions which were previously set for a command from being lost after a rename.

This currently isn't supported when multiple guild IDs are passed for declare_global_commands.

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

message_ids

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

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

user_ids

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

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

RAISES DESCRIPTION
ValueError

Raises for the following reasons:

  • If event_managed is True when event_manager is None.
  • If command_ids is passed when multiple guild ids are provided for declare_global_commands.
  • If command_ids is passed when declare_global_commands is False.

add_check(check) #

Add a generic check to this client.

This will be applied to both message and slash command execution.

PARAMETER DESCRIPTION
check

The check to add. This may be either synchronous or asynchronous and must take one positional argument of type tanjun.abc.Context with dependency injection being supported for its keyword arguments.

TYPE: tanjun.CheckSig

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

add_component(component) #

Add a component to this client.

PARAMETER DESCRIPTION
component

The component to move to this client.

TYPE: tanjun.Component

RETURNS DESCRIPTION
Self

The client instance to allow chained calls.

RAISES DESCRIPTION
ValueError

If the component's name is already registered.

add_prefix(prefixes) #

Add a prefix used to filter message command calls.

This will be matched against the first character(s) in a message's content to determine whether the message command search stage of execution should be initiated.

PARAMETER DESCRIPTION
prefixes

Either a single string or an iterable of strings to be used as prefixes.

TYPE: typing.Union[collections.Iterable[str], str]

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

checks() property #

Collection of the level tanjun.abc.Context checks registered to this client.

Note

These may be taking advantage of the standard dependency injection.

close(*, deregister_listeners=True) async #

Close the client.

RAISES DESCRIPTION
RuntimeError

If the client isn't running.

fetch_rest_application_id() async #

Fetch the ID of the application this client is linked to.

RETURNS DESCRIPTION
hikari.Snowflake

The application ID of the application this client is linked to.

from_gateway_bot(bot, /, *, event_managed=True, injector=None, mention_prefix=False, declare_global_commands=False, set_global_commands=False, command_ids=None, message_ids=None, user_ids=None) classmethod #

Build a tanjun.Client from a hikari.traits.GatewayBotAware instance.

Note

This defaults the client to human only mode and sets type dependency injectors for the hikari traits present in bot (including hikari.traits.GatewayBotAware).

PARAMETER DESCRIPTION
bot

The bot client to build from.

This will be used to infer the relevant Hikari clients to use.

TYPE: hikari.GatewayBotAware

event_managed

Whether or not this client is managed by the event manager.

An event managed client will be automatically started and closed based on Hikari's lifetime events.

TYPE: bool DEFAULT: True

injector

The alluka client this should use for dependency injection.

If not provided then the client will initialise its own DI client.

TYPE: typing.Optional[alluka.abc.Client] DEFAULT: None

mention_prefix

Whether or not mention prefixes should be automatically set when this client is first started.

It should be noted that this only applies to message commands.

TYPE: bool DEFAULT: False

declare_global_commands

Whether or not to automatically set global slash commands when this client is first started.

If one or more guild objects/IDs are passed here then the registered global commands will be set on the specified guild(s) at startup rather than globally.

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

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialGuild], hikari.SnowflakeishOr[hikari.PartialGuild], bool] DEFAULT: False

set_global_commands

Deprecated as of v2.1.1a1 alias of declare_global_commands.

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

command_ids

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

This field is complementary to declare_global_commands and, while it isn't necessarily required, this will in some situations help avoid permissions which were previously set for a command from being lost after a rename.

This currently isn't supported when multiple guild IDs are passed for declare_global_commands.

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

message_ids

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

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

user_ids

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

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

from_rest_bot(bot, /, *, declare_global_commands=False, injector=None, set_global_commands=False, command_ids=None, message_ids=None, user_ids=None) classmethod #

Build a tanjun.Client from a hikari.traits.RESTBotAware instance.

Note

This sets type dependency injectors for the hikari traits present in bot (including hikari.traits.RESTBotAware).

PARAMETER DESCRIPTION
bot

The bot client to build from.

TYPE: hikari.RESTBotAware

declare_global_commands

Whether or not to automatically set global slash commands when this client is first started.

If one or more guild objects/IDs are passed here then the registered global commands will be set on the specified guild(s) at startup rather than globally.

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

TYPE: typing.Union[hikari.SnowflakeishSequence[hikari.PartialGuild], hikari.SnowflakeishOr[hikari.PartialGuild], bool] DEFAULT: False

injector

The alluka client this should use for dependency injection.

If not provided then the client will initialise its own DI client.

TYPE: typing.Optional[alluka.abc.Client] DEFAULT: None

set_global_commands

Deprecated as of v2.1.1a1 alias of declare_global_commands.

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

command_ids

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

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

This field is complementary to declare_global_commands and, while it isn't necessarily required, this will in some situations help avoid permissions which were previously set for a command from being lost after a rename.

This currently isn't supported when multiple guild IDs are passed for declare_global_commands.

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

message_ids

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

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

user_ids

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

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

hooks() property #

Top level tanjun.abc.AnyHooks set for this client.

These are called during both message, menu and slash command execution.

interaction_accepts() property #

The types of interactions this client is executing.

is_human_only() property #

Whether this client is only executing for non-bot/webhook users messages.

menu_hooks() property #

Top level tanjun.abc.MenuHooks set for this client.

These are only called during menu command execution.

message_accepts() property #

Type of message create events this command client accepts for execution.

message_hooks() property #

Top level tanjun.abc.MessageHooks set for this client.

These are only called during message command execution.

on_autocomplete_interaction_request(interaction) async #

Execute a command autocomplete based on received REST requests.

PARAMETER DESCRIPTION
interaction

The interaction to execute autocomplete based on.

TYPE: hikari.AutocompleteInteraction

RETURNS DESCRIPTION
hikari.api.InteractionAutocompleteBuilder

The initial response to send back to Discord.

on_command_interaction_request(interaction) async #

Execute an app command based on received REST requests.

PARAMETER DESCRIPTION
interaction

The interaction to execute a command based on.

TYPE: hikari.CommandInteraction

RETURNS DESCRIPTION
hikari.api.InteractionMessageBuilder | hikari.api.InteractionDeferredBuilder

The initial response to send back to Discord.

on_gateway_autocomplete_create(interaction) async #

Execute command autocomplete based on a received gateway interaction create.

PARAMETER DESCRIPTION
interaction

The interaction to execute a command based on.

TYPE: hikari.AutocompleteInteraction

on_gateway_command_create(interaction) async #

Execute an app command based on a received gateway interaction create.

PARAMETER DESCRIPTION
interaction

The interaction to execute a command based on.

TYPE: hikari.CommandInteraction

on_interaction_create_event(event) async #

Handle a gateway interaction create event.

This will execute both application command and autocomplete interactions.

PARAMETER DESCRIPTION
event

The event to execute commands based on.

TYPE: hikari.InteractionCreateEvent

on_message_create_event(event) async #

Execute a message command based on a gateway event.

PARAMETER DESCRIPTION
event

The event to handle.

TYPE: hikari.MessageCreateEvent

open(*, register_listeners=True) async #

Start the client.

If mention_prefix was passed to tanjun.Client.init or tanjun.Client.from_gateway_bot then this function may make a fetch request to Discord if it cannot get the current user from the cache.

RAISES DESCRIPTION
RuntimeError

If the client is already active.

prefix_getter() property #

Prefix getter method set for this client.

For more information on this callback's signature see tanjun.clients.PrefixGetterSig.

prefixes() property #

Collection of the standard prefixes set for this client.

remove_check(check) #

Remove a check from the client.

PARAMETER DESCRIPTION
check

The check to remove.

TYPE: tanjun.CheckSig

RAISES DESCRIPTION
ValueError

If the check was not previously added.

remove_prefix(prefix) #

Remove a message content prefix from the client.

PARAMETER DESCRIPTION
prefix

The prefix to remove.

TYPE: str

RAISES DESCRIPTION
ValueError

If the prefix is not registered with the client.

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_auto_defer_after(time) #

Set when this client should automatically defer execution of commands.

Warning

If time is set to None then automatic deferrals will be disabled. This may lead to unexpected behaviour.

PARAMETER DESCRIPTION
time

The time in seconds to defer interaction command responses after.

TYPE: typing.Optional[float]

set_autocomplete_ctx_maker(maker=context.AutocompleteContext) #

Set the autocomplete context maker to use when creating contexts.

Warning

The caller must return an instance of tanjun.context.AutocompleteContext rather than just any implementation of the AutocompleteContext abc due to this client relying on implementation detail of tanjun.context.AutocompleteContext.

PARAMETER DESCRIPTION
maker

The autocomplete context maker to use.

This is a callback which should match the signature of tanjun.context.AutocompleteContext.init and return an instance of tanjun.context.AutocompleteContext.

TYPE: _AutocompleteContextMakerProto DEFAULT: context.AutocompleteContext

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_default_app_command_permissions(permissions) #

Set the default member permissions needed for this client's commands.

Warning

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

PARAMETER DESCRIPTION
permissions

The default member permissions needed for this client's application commands.

This may be overridden by tanjun.abc.AppCommand.default_member_permissions and tanjun.abc.Component.default_app_cmd_permissions; if this is left as None then this config will be inherited from the parent client.

TYPE: typing.Union[int, hikari.Permissions]

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_dms_enabled_for_app_cmds(state) #

Set whether this clients's commands should be enabled in DMs.

PARAMETER DESCRIPTION
state

Whether to enable this client's commands in DMs.

This may be overridden by tanjun.abc.AppCommand.is_dm_enabled and tanjun.abc.Component.dms_enabled_for_app_cmds; if this is left as None then this config will be inherited from the parent client.

TYPE: bool

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_ephemeral_default(state) #

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

This defaults to False if not explicitly set.

PARAMETER DESCRIPTION
state

Whether slash command contexts executed in this client should should default to ephemeral.

This will be overridden by any response calls which specify flags.

TYPE: bool

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_global_commands(*, application=None, guild=hikari.UNDEFINED, force=False) async #

Alias of [tanjun.Client.declare_global_commands][].

deprecated

Since v2.1.1a1; use [tanjun.Client.declare_global_commands][] instead.

set_hikari_trait_injectors(bot) #

Set type based dependency injection based on the hikari traits found in bot.

This is a short hand for calling [tanjun.Client.add_type_dependency][] for all the hikari trait types bot is valid for with bot.

PARAMETER DESCRIPTION
bot

The hikari client to set dependency injectors for.

TYPE: hikari.RESTAware

set_hooks(hooks) #

Set the general command execution hooks for this client.

The callbacks within this hook will be added to every slash and message command execution started by this client.

PARAMETER DESCRIPTION
hooks

The general command execution hooks to set for this client.

Passing None will remove all hooks.

TYPE: typing.Optional[tanjun.AnyHooks]

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_human_only(value=True) #

Set whether or not message commands execution should be limited to "human" users.

Note

This doesn't apply to interaction commands as these can only be triggered by a "human" (normal user account).

PARAMETER DESCRIPTION
value

Whether or not message commands execution should be limited to "human" users.

Passing True here will prevent message commands from being executed based on webhook and bot messages.

TYPE: bool DEFAULT: True

set_interaction_accepts(accepts) #

Set the kind of interactions this client should execute.

PARAMETER DESCRIPTION
accepts

Bitfield of the interaction types this client should execute.

TYPE: InteractionAcceptsEnum

RAISES DESCRIPTION
RuntimeError

If called while the client is running.

set_interaction_not_found(message) #

Set the response message for when an interaction command is not found.

Warning

Setting this to None may lead to unexpected behaviour (especially when the client is still set to auto-defer interactions) and should only be done if you know what you're doing.

PARAMETER DESCRIPTION
message

The message to respond with when an interaction command isn't found.

TYPE: typing.Optional[str]

set_menu_ctx_maker(maker=context.MenuContext) #

Set the autocomplete context maker to use when creating contexts.

Warning

The caller must return an instance of tanjun.context.MenuContext rather than just any implementation of the MenuContext abc due to this client relying on implementation detail of tanjun.context.MenuContext.

PARAMETER DESCRIPTION
maker

The autocomplete context maker to use.

This is a callback which should match the signature of tanjun.context.MenuContext.init and return an instance of tanjun.context.MenuContext.

TYPE: _MenuContextMakerProto DEFAULT: context.MenuContext

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_menu_hooks(hooks) #

Set the menu command execution hooks for this client.

The callbacks within this hook will be added to every menu command execution started by this client.

PARAMETER DESCRIPTION
hooks

The menu context specific command execution hooks to set for this client.

Passing None will remove the hooks.

TYPE: typing.Optional[tanjun.MenuHooks]

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_menu_not_found(message) #

Set the response message for when a menu command is not found.

Warning

Setting this to None may lead to unexpected behaviour (especially when the client is still set to auto-defer interactions) and should only be done if you know what you're doing.

PARAMETER DESCRIPTION
message

The message to respond with when a menu command isn't found.

TYPE: typing.Optional[str]

set_message_accepts(accepts) #

Set the kind of messages commands should be executed based on.

PARAMETER DESCRIPTION
accepts

The type of messages commands should be executed based on.

TYPE: MessageAcceptsEnum

RAISES DESCRIPTION
RuntimeError

If called while the client is running.

ValueError

If accepts is set to anything other than tanjun.clients.MessageAcceptsEnum.NONE when the client doesn't have a linked event manager.

set_message_ctx_maker(maker=context.MessageContext) #

Set the message context maker to use when creating context for a message.

Warning

The caller must return an instance of tanjun.context.MessageContext rather than just any implementation of the MessageContext abc due to this client relying on implementation detail of tanjun.context.MessageContext.

PARAMETER DESCRIPTION
maker

The message context maker to use.

This is a callback which should match the signature of tanjun.context.MessageContext.init and return an instance of tanjun.context.MessageContext.

TYPE: _MessageContextMakerProto DEFAULT: context.MessageContext

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_message_hooks(hooks) #

Set the message command execution hooks for this client.

The callbacks within this hook will be added to every message command execution started by this client.

PARAMETER DESCRIPTION
hooks

The message context specific command execution hooks to set for this client.

Passing None will remove all hooks.

TYPE: typing.Optional[tanjun.MessageHooks]

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_prefix_getter(getter) #

Set the callback used to retrieve message prefixes set for the relevant guild.

PARAMETER DESCRIPTION
getter

The callback which'll be used to retrieve prefixes for the guild a message context is from. If None is passed here then the callback will be unset.

This should be an async callback which one argument of type tanjun.abc.MessageContext and returns an iterable of string prefixes. Dependency injection is supported for this callback's keyword arguments.

TYPE: typing.Optional[PrefixGetterSig]

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_slash_ctx_maker(maker=context.SlashContext) #

Set the slash context maker to use when creating context for a slash command.

Warning

The caller must return an instance of tanjun.context.SlashContext rather than just any implementation of the SlashContext abc due to this client relying on implementation detail of tanjun.context.SlashContext.

PARAMETER DESCRIPTION
maker

The slash context maker to use.

This is a callback which should match the signature of tanjun.context.SlashContext.init and return an instance of tanjun.context.SlashContext.

TYPE: _SlashContextMakerProto DEFAULT: context.SlashContext

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_slash_hooks(hooks) #

Set the slash command execution hooks for this client.

The callbacks within this hook will be added to every slash command execution started by this client.

PARAMETER DESCRIPTION
hooks

The slash context specific command execution hooks to set for this client.

Passing None will remove the hooks.

TYPE: typing.Optional[tanjun.SlashHooks]

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

set_slash_not_found(message) #

Set the response message for when a slash command is not found.

Warning

Setting this to None may lead to unexpected behaviour (especially when the client is still set to auto-defer interactions) and should only be done if you know what you're doing.

PARAMETER DESCRIPTION
message

The message to respond with when a slash command isn't found.

TYPE: typing.Optional[str]

slash_hooks() property #

Top level tanjun.abc.SlashHooks set for this client.

These are only called during slash command execution.

with_check(check) #

Add a check to this client through a decorator call.

PARAMETER DESCRIPTION
check

The check to add. This may be either synchronous or asynchronous and must take one positional argument of type tanjun.abc.Context with dependency injection being supported for its keyword arguments.

TYPE: tanjun.abc.CheckSig

RETURNS DESCRIPTION
tanjun.abc.CheckSig

The added check.

with_prefix_getter(getter) #

Set the prefix getter callback for this client through decorator call.

Examples:

client = tanjun.Client.from_rest_bot(bot)

@client.with_prefix_getter
async def prefix_getter(ctx: tanjun.abc.MessageContext) -> collections.abc.Iterable[str]:
    raise NotImplementedError
PARAMETER DESCRIPTION
getter

The callback which'll be to retrieve prefixes for the guild a message event is from.

This should be an async callback which one argument of type tanjun.abc.MessageContext and returns an iterable of string prefixes. Dependency injection is supported for this callback's keyword arguments.

TYPE: PrefixGetterSig

RETURNS DESCRIPTION
PrefixGetterSig

The registered callback.

ClientCallbackNames #

Bases: str, enum.Enum

Enum of the standard client callback names.

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

CLOSED = 'closed' class-attribute #

Called when the client has finished closing.

No positional arguments are provided for this event.

CLOSING = 'closing' class-attribute #

Called when the client is initially instructed to close.

No positional arguments are provided for this event.

COMPONENT_ADDED = 'component_added' class-attribute #

Called when a component is added to an active client.

Warning

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

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

COMPONENT_REMOVED = 'component_removed' class-attribute #

Called when a component is added to an active client.

Warning

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

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

MENU_COMMAND_NOT_FOUND = 'menu_command_not_found' class-attribute #

Called when a menu command is not found.

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

MESSAGE_COMMAND_NOT_FOUND = 'message_command_not_found' class-attribute #

Called when a message command is not found.

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

SLASH_COMMAND_NOT_FOUND = 'slash_command_not_found' class-attribute #

Called when a slash command is not found.

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

STARTED = 'started' class-attribute #

Called when the client has finished starting.

No positional arguments are provided for this event.

STARTING = 'starting' class-attribute #

Called when the client is initially instructed to start.

No positional arguments are provided for this event.

CommandError #

Bases: TanjunError

An error which is sent as a response to the command call.

__init__(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) #

Initialise a command error.

PARAMETER DESCRIPTION
content

The content to respond with.

If provided, the message contents. If hikari.undefined.UNDEFINED, then nothing will be sent in the content.

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

delete_after

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

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

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

attachment

A singular attachment to respond with.

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

attachments

A sequence of attachments to respond with.

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

component

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

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

components

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

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

embed

An embed to respond with.

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

embeds

A sequence of embeds to respond with.

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

mentions_everyone

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

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

user_mentions

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

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

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

role_mentions

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

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

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

RAISES DESCRIPTION
ValueError

Raised for any of the following reasons:

  • When both attachment and attachments are provided.
  • When both component and components are passed.
  • When both embed and embeds are passed.
  • If more than 100 entries are passed for role_mentions.
  • If more than 100 entries are passed for user_mentions.

send(ctx, /, *, ensure_result=False) async #

Send this error as a command response.

PARAMETER DESCRIPTION
ctx

The command call context to respond to.

TYPE: tanjun.Context

ensure_result

Ensure that this call will always return a message object.

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

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

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

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

hikari.BadRequestError

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

hikari.UnauthorizedError

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

hikari.ForbiddenError

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

hikari.NotFoundError

If the channel is not found.

hikari.RateLimitTooLongError

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

hikari.RateLimitedError

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

hikari.InternalServerError

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

Component #

Bases: tanjun.Component

Standard implementation of tanjun.abc.Component.

This is a collcetion of commands (both message and slash), hooks and listener callbacks which can be added to a generic client.

Note

This implementation supports dependency injection for its checks, command callbacks and listeners when linked to a client which supports dependency injection.

__init__(*, name=None, strict=False) #

Initialise a new component.

PARAMETER DESCRIPTION
name

The component's identifier.

If not provided then this will be a random string.

TYPE: typing.Optional[str] DEFAULT: None

strict

Whether this component should use a stricter (more optimal) approach for message command search.

When this is True, message command names will not be allowed to contain spaces and will have to be unique to one command within the component.

TYPE: bool DEFAULT: False

add_check(check) #

Add a command check to this component to be used for all its commands.

PARAMETER DESCRIPTION
check

The check to add.

TYPE: tanjun.CheckSig

RETURNS DESCRIPTION
Self

This component to enable method chaining.

add_client_callback(name, callback) #

Add a client callback.

PARAMETER DESCRIPTION
name

The name this callback is being registered to.

This is case-insensitive.

TYPE: typing.Union[str, tanjun.ClientCallbackNames]

callback

The callback to register.

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

TYPE: tanjun.MetaEventSig

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

add_command(command) #

Add a command to this component.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: tanjun.ExecutableCommand[typing.Any]

RETURNS DESCRIPTION
Self

The current component to allow for chaining.

add_message_command(command) #

Add a message command to the component.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: tanjun.MessageCommand[typing.Any]

RETURNS DESCRIPTION
Self

The component to allow method chaining.

RAISES DESCRIPTION
ValueError

If one of the command's name is already registered in a strict component.

add_on_close(callback) #

Add a close callback to this component.

Note

Unlike the closing and closed client callbacks, this is only called for the current component's lifetime and is guaranteed to be called regardless of when the component was added to a client.

PARAMETER DESCRIPTION
callback

The close callback to add to this component.

This should take no positional arguments, return None and may take use injected dependencies.

TYPE: OnCallbackSig

RETURNS DESCRIPTION
Self

The component object to enable call chaining.

add_on_open(callback) #

Add a open callback to this component.

Note

Unlike the starting and started client callbacks, this is only called for the current component's lifetime and is guaranteed to be called regardless of when the component was added to a client.

PARAMETER DESCRIPTION
callback

The open callback to add to this component.

This should take no positional arguments, return None and may take use injected dependencies.

TYPE: OnCallbackSig

RETURNS DESCRIPTION
Self

The component object to enable call chaining.

add_schedule(schedule) #

Add a schedule to the component.

PARAMETER DESCRIPTION
schedule

The schedule to add.

TYPE: schedules_.AbstractSchedule

RETURNS DESCRIPTION
Self

The component itself for chaining.

checks() property #

Collection of the checks being run against every command execution in this component.

get_client_callbacks(name) #

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

PARAMETER DESCRIPTION
name

The name to get the callbacks registered for.

This is case-insensitive.

TYPE: typing.Union[str, tanjun.ClientCallbackNames]

RETURNS DESCRIPTION
collections.abc.Collection[MetaEventSig]

Collection of the callbacks for the provided name.

hooks() property #

The general command hooks set for this component, if any.

load_from_scope(*, include_globals=False, scope=None) #

Load entries such as top-level commands into the component from the calling scope.

Note

This will load schedules which support and commands AbstractComponentLoader (all standard implementations support this) and will ignore commands which are owned by command groups.

Note

This will detect entries from the calling scope which implement tanjun.components.AbstractComponentLoader unless scope is passed but this isn't possible in a stack-less python implementation; in stack-less environments the scope will have to be explicitly passed as scope.

PARAMETER DESCRIPTION
include_globals

Whether to include global variables (along with local) while detecting from the calling scope.

This cannot be True when scope is provided and will only ever be needed when the local scope is different from the global scope.

TYPE: bool DEFAULT: False

scope

The scope to detect entries which implement tanjun.components.AbstractComponentLoader from.

This overrides the default usage of stackframe introspection.

TYPE: typing.Optional[collections.Mapping[str, typing.Any]] DEFAULT: None

RETURNS DESCRIPTION
Self

The current component to allow for chaining.

RAISES DESCRIPTION
RuntimeError

If this is called in a python implementation which doesn't support stack frame inspection when scope is not provided.

ValueError

If scope is provided when include_globals is True.

make_loader(*, copy=True) #

Make a loader/unloader for this component.

This enables loading, unloading and reloading of this component into a client by targeting the module using [tanjun.Client.load_modules][], [tanjun.Client.unload_modules][] and [tanjun.Client.reload_modules][].

PARAMETER DESCRIPTION
copy

Whether to copy the component before loading it into a client.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
tanjun.abc.ClientLoader

The loader for this component.

menu_hooks() property #

The menu command hooks set for this component, if any.

message_hooks() property #

The message command hooks set for this component, if any.

remove_check(check) #

Remove a command check from this component.

PARAMETER DESCRIPTION
check

The check to remove.

TYPE: tanjun.CheckSig

RETURNS DESCRIPTION
Self

This component to enable method chaining.

RAISES DESCRIPTION
ValueError

If the check is not registered with this component.

remove_client_callback(name, callback) #

Remove a client callback.

PARAMETER DESCRIPTION
name

The name this callback is being registered to.

This is case-insensitive.

TYPE: str

callback

The callback to remove from the client's callbacks.

TYPE: tanjun.MetaEventSig

RAISES DESCRIPTION
KeyError

If the provided name isn't found.

ValueError

If the provided callback isn't found.

RETURNS DESCRIPTION
Self

The client instance to enable chained calls.

remove_command(command) #

Remove a command from this component.

PARAMETER DESCRIPTION
command

The command to remove.

TYPE: tanjun.ExecutableCommand[typing.Any]

RETURNS DESCRIPTION
Self

This component to enable method chaining.

remove_schedule(schedule) #

Remove a schedule from the component.

PARAMETER DESCRIPTION
schedule

The schedule to remove

TYPE: schedules_.AbstractSchedule

RETURNS DESCRIPTION
Self

The component itself for chaining.

RAISES DESCRIPTION
ValueError

If the schedule isn't registered.

schedules() property #

Collection of the schedules registered to this component.

set_default_app_command_permissions(permissions) #

Set the default member permissions needed for this component's commands.

Warning

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

PARAMETER DESCRIPTION
permissions

The default member permissions needed for this component's application commands.

If this is left as None then this config will be inherited from the parent client.

This may be overridden by tanjun.abc.AppCommand.default_member_permissions and if this is left as None then this config will be inherited from the parent client.

TYPE: typing.Union[int, hikari.Permissions, None]

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_dms_enabled_for_app_cmds(state) #

Set whether this component's commands should be enabled in DMs.

PARAMETER DESCRIPTION
state

Whether to enable this component's commands in DMs.

This may be overridden by tanjun.abc.AppCommand.is_dm_enabled and if this is left as None then this config will be inherited from the parent client.

TYPE: typing.Optional[bool]

RETURNS DESCRIPTION
Self

This client to enable method chaining.

set_ephemeral_default(state) #

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

PARAMETER DESCRIPTION
state

Whether slash command contexts executed in this component should should default to ephemeral. This will be overridden by any response calls which specify flags.

Setting this to None will let the default set on the parent client propagate and decide the ephemeral default behaviour.

TYPE: typing.Optional[bool]

RETURNS DESCRIPTION
Self

This component to enable method chaining.

set_hooks(hooks) #

Set hooks to be called during the execution of all of this component's commands.

PARAMETER DESCRIPTION
hooks

The command hooks to set.

TYPE: typing.Optional[tanjun.AnyHooks]

RETURNS DESCRIPTION
Self

This component to enable method chaining.

set_menu_hooks(hooks) #

Set hooks to be called during the execution of this component's menu commands.

PARAMETER DESCRIPTION
hooks

The menu command hooks to set.

TYPE: typing.Optional[tanjun.MenuHooks]

RETURNS DESCRIPTION
Self

This component to enable method chaining.

set_message_hooks(hooks) #

Set hooks to be called during the execution of this component's message commands.

PARAMETER DESCRIPTION
hooks

The message command hooks to set.

TYPE: typing.Optional[tanjun.MessageHooks]

RETURNS DESCRIPTION
Self

This component to enable method chaining.

set_slash_hooks(hooks) #

Set hooks to be called during the execution of this component's slash commands.

PARAMETER DESCRIPTION
hooks

The slash command hooks to set.

TYPE: typing.Optional[tanjun.SlashHooks]

RETURNS DESCRIPTION
Self

This component to enable method chaining.

slash_hooks() property #

The slash command hooks set for this component, if any.

with_check(check) #

Add a general command check to this component through a decorator call.

PARAMETER DESCRIPTION
check

The check to add.

TYPE: tanjun.abc.CheckSig

RETURNS DESCRIPTION
tanjun.abc.CheckSig

The added check.

with_client_callback(name) #

Add a client callback through a decorator call.

Examples:

client = tanjun.Client.from_rest_bot(bot)

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

The name this callback is being registered to.

This is case-insensitive.

TYPE: typing.Union[str, tanjun.ClientCallbackNames]

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MetaEventSig], tanjun.abc.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_command(command=None, /, *, copy=False, follow_wrapped=False) #

Add a command to this component through a decorator call.

Examples:

This may be used inconjunction with tanjun.as_slash_command and tanjun.as_message_command.

@component.with_command
@tanjun.with_slash_str_option("option_name", "option description")
@tanjun.as_slash_command("command_name", "command description")
async def slash_command(ctx: tanjun.abc.Context, arg: str) -> None:
    await ctx.respond(f"Hi {arg}")
@component.with_command
@tanjun.with_argument("argument_name")
@tanjun.as_message_command("command_name")
async def message_command(ctx: tanjun.abc.Context, arg: str) -> None:
    await ctx.respond(f"Hi {arg}")
PARAMETER DESCRIPTION
command

The command to add to this component.

TYPE: typing.Optional[_CommandT] DEFAULT: None

copy

Whether to copy the command before adding it to this component.

TYPE: bool DEFAULT: False

follow_wrapped

Whether to also add any commands command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommand

The added command.

with_on_close(callback) #

Add a close callback to this component through a decorator call.

Note

Unlike the closing and closed client callbacks, this is only called for the current component's lifetime and is guaranteed to be called regardless of when the component was added to a client.

PARAMETER DESCRIPTION
callback

The close callback to add to this component.

This should take no positional arguments, return None and may take use injected dependencies.

TYPE: OnCallbackSig

RETURNS DESCRIPTION
OnCallbackSig

The added close callback.

with_on_open(callback) #

Add a open callback to this component through a decorator call.

Note

Unlike the starting and started client callbacks, this is only called for the current component's lifetime and is guaranteed to be called regardless of when the component was added to a client.

PARAMETER DESCRIPTION
callback

The open callback to add to this component.

This should take no positional arguments, return None and may take use injected dependencies.

TYPE: OnCallbackSig

RETURNS DESCRIPTION
OnCallbackSig

The added open callback.

with_schedule(schedule) #

Add a schedule to the component through a decorator call.

Example#

This may be used in conjunction with tanjun.as_interval.

@component.with_schedule
@tanjun.as_interval(60)
async def my_schedule():
    print("I'm running every minute!")
PARAMETER DESCRIPTION
schedule

The schedule to add.

TYPE: tanjun.schedules.AbstractSchedule

RETURNS DESCRIPTION
tanjun.schedules.AbstractSchedule

The added schedule.

ConversionError #

Bases: ParserError

Error raised by a parser parameter when it failed to converter a value.

parameter: str class-attribute #

Name of the parameter this error was raised for.

__init__(message, parameter, /, errors=()) #

Initialise a conversion error.

PARAMETER DESCRIPTION
parameter

The parameter this was raised by.

TYPE: str

errors

An iterable of the source value errors which were raised during conversion.

TYPE: collections.Iterable[ValueError] DEFAULT: ()

FailedCheck #

Bases: TanjunError, RuntimeError

Error raised as an alternative to returning False in a check.

FailedModuleImport #

Bases: FailedModuleLoad

Error raised when a module failed to import.

This is a specialisation of tanjun.errors.FailedModuleLoad.

FailedModuleLoad #

Bases: TanjunError

Error raised when a module fails to load.

This may be raised by the module failing to import or by one of its loaders erroring.

This source error can be accessed at FailedModuleLoad.cause.

__cause__: Exception class-attribute #

The root error.

path() property #

The path of the module which caused the error.

FailedModuleUnload #

Bases: TanjunError

Error raised when a module fails to unload.

This may be raised by the module failing to import or by one of its unloaders erroring.

The source error can be accessed at FailedModuleUnload.cause.

__cause__: Exception class-attribute #

The root error.

path() property #

The path of the module which caused the error.

HaltExecution #

Bases: TanjunError

Error raised while looking for a command in-order to end-execution early.

For the most part, this will be raised during checks in-order to prevent other commands from being tried.

Hooks #

Bases: tanjun.Hooks[_ContextT_contra]

Standard implementation of tanjun.abc.Hooks used for command execution.

This will take either tanjun.abc.Context, tanjun.abc.MessageContext or tanjun.abc.SlashContext dependent on what its bound by (generic wise).

Note

This implementation adds a concept of parser errors which won't be dispatched to general "error" hooks and do not share the error suppression semantics as they favour to always suppress the error if a registered handler is found.

__init__() #

Initialise a command hook object.

add_to_command(command) #

Add this hook object to a command.

Note

This will likely override any previously added hooks.

Examples:

This method may be used as a command decorator:

@standard_hooks.add_to_command
@as_message_command("command")
async def command_command(ctx: tanjun.abc.Context) -> None:
    await ctx.respond("You've called a command!")
PARAMETER DESCRIPTION
command

The command to add the hooks to.

TYPE: tanjun.abc.ExecutableCommand

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommand

The command with the hooks added.

copy() #

Copy this hook object.

set_on_error(callback) #

Set the error callback for this hook object.

Note

This will not be called for tanjun.ParserErrors as these are generally speaking expected. To handle those see Hooks.set_on_parser_error.

PARAMETER DESCRIPTION
callback

The callback to set for this hook. This will remove any previously set callbacks.

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

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

TYPE: typing.Optional[tanjun.ErrorHookSig]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

set_on_parser_error(callback) #

Set the parser error callback for this hook object.

PARAMETER DESCRIPTION
callback

The callback to set for this hook. This will remove any previously set callbacks.

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

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

TYPE: typing.Optional[tanjun.HookSig]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

set_on_success(callback) #

Set the success callback for this hook object.

PARAMETER DESCRIPTION
callback

The callback to set for this hook. This will remove any previously set callbacks.

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

TYPE: typing.Optional[tanjun.HookSig]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

set_post_execution(callback) #

Set the post-execution callback for this hook object.

PARAMETER DESCRIPTION
callback

The callback to set for this hook. This will remove any previously set callbacks.

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

TYPE: typing.Optional[tanjun.HookSig]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

set_pre_execution(callback) #

Set the pre-execution callback for this hook object.

PARAMETER DESCRIPTION
callback

The callback to set for this hook. This will remove any previously set callbacks.

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

TYPE: typing.Optional[tanjun.HookSig]

RETURNS DESCRIPTION
Self

The hook object to enable method chaining.

HotReloader #

Manages hot reloading modules for a Tanjun client..

Warning

An instance of this can only be linked to 1 client.

Examples:

client = tanjun.Client.from_gateway_bot(bot)
(
    tanjun.dependencies.HotReloader()
    .add_modules("python.module.path", pathlib.Path("./module.py"))
    .add_directory("./modules/")
    .add_to_client(client)
)

__init__(*, commands_guild=None, interval=datetime.timedelta(microseconds=500000), redeclare_cmds_after=datetime.timedelta(seconds=10), unload_on_delete=True) #

Initialise a hot reloader.

Warning

redeclare_cmds_after is not aware of commands declared outside of the reloader and will lead to commands being redeclared on startup when mixed with tanjun.clients.Client.init's declare_global_commands argument when it is not None.

PARAMETER DESCRIPTION
commands_guild

Object or ID of the guild to declare commands in if redeclare_cmds_after is not None.

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

interval

How often this should scan files and directories for changes in seconds.

TYPE: typing.Union[int, float, datetime.timedelta] DEFAULT: datetime.timedelta(microseconds=500000)

redeclare_cmds_after

How often to redeclare application commands after a change to the commands is detected.

If None is passed here then this will not redeclare the application's commands.

TYPE: typing.Union[int, float, datetime.timedelta, None] DEFAULT: datetime.timedelta(seconds=10)

unload_on_delete

Whether this should unload modules when their relevant file is deleted.

TYPE: bool DEFAULT: True

add_directory(directory, /, *, namespace=None) #

Add a directory for this hot reloader to track.

Note

This will only reload modules directly in the target directory and will not scan sub-directories.

PARAMETER DESCRIPTION
directory

Path of the directory to hot reload.

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

namespace

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

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

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

TYPE: typing.Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Self

The hot reloader to enable chained calls.

RAISES DESCRIPTION
FileNotFoundError

If the directory cannot be found

add_directory_async(directory, /, *, namespace=None) async #

Asynchronous variant of tanjun.dependencies.reloaders.HotReloader.add_directory.

Unlike tanjun.dependencies.reloaders.HotReloader.add_directory, this method will run blocking code in a background thread.

For more information on the behaviour of this method see the documentation for tanjun.dependencies.reloaders.HotReloader.add_directory.

add_modules(*paths) #

Add modules for this hot reloader to track.

PARAMETER DESCRIPTION
*paths

Module paths for this hot reloader to track.

This has the same behaviour as [tanjun.abc.Client.load_modules][ for how [pathlib.Path][] and str are treated.

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

RAISES DESCRIPTION
FileNotFoundError

If the module's file doesn't exist anymore.

ModuleNotFoundError

If the str module path cannot be imported.

add_modules_async(*paths) async #

Asynchronous variant of tanjun.dependencies.reloaders.HotReloader.add_modules.

Unlike tanjun.dependencies.reloaders.HotReloader.add_modules, this method will run blocking code in a background thread.

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

add_to_client(client) #

Add this to a tanjun.abc.Client instance.

This registers start and closing callbacks which handle the lifetime of this and adds this as a type dependency.

PARAMETER DESCRIPTION
client

The client to link this hot reloader to.

TYPE: tanjun.Client

RETURNS DESCRIPTION
Self

The hot reloader to enable chained calls.

scan(client) async #

Manually scan this hot reloader's tracked modules for changes.

PARAMETER DESCRIPTION
client

The client to reload and unload modules in.

TYPE: tanjun.Client

start(client) #

Start the hot reloader.

RAISES DESCRIPTION
RuntimeError

If the hot reloader is already running.

stop() #

Stop the hot reloader.

RAISES DESCRIPTION
RuntimeError

If the hot reloader isn't running.

InMemoryConcurrencyLimiter #

Bases: AbstractConcurrencyLimiter

In-memory standard implementation of AbstractConcurrencyLimiter.

Examples:

InMemoryConcurrencyLimiter.set_bucket may be used to set the concurrency limits for a specific bucket:

(
    InMemoryConcurrencyLimiter()
    # Set the default bucket template to 10 concurrent uses of the command per-user.
    .set_bucket("default", tanjun.BucketResource.USER, 10)
    # Set the "moderation" bucket with a limit of 5 concurrent uses per-guild.
    .set_bucket("moderation", tanjun.BucketResource.GUILD, 5)
    .set_bucket()
    # add_to_client will setup the concurrency manager (setting it as an
    # injected dependency and registering callbacks to manage it).
    .add_to_client(client)
)

add_to_client(client) #

Add this concurrency manager to a tanjun client.

Note

This registers the manager as a type dependency and manages opening and closing the manager based on the client's life cycle.

PARAMETER DESCRIPTION
client

The client to add this concurrency manager to.

TYPE: tanjun.Client

close() #

Stop the concurrency manager.

RAISES DESCRIPTION
RuntimeError

If the concurrency manager is not running.

disable_bucket(bucket_id) #

Disable a concurrency limit bucket.

This will stop the bucket from ever hitting a concurrency limit and also prevents the bucket from defaulting.

Note

"default" is a special bucket_id which is used as a template for unknown bucket IDs.

PARAMETER DESCRIPTION
bucket_id

The bucket to disable.

TYPE: str

RETURNS DESCRIPTION
Self

This concurrency manager to allow for chaining.

open(*, _loop=None) #

Start the concurrency manager.

RAISES DESCRIPTION
RuntimeError

If the concurrency manager is already running. If called in a thread with no running event loop.

set_bucket(bucket_id, resource, limit) #

Set the concurrency limit for a specific bucket.

Note

"default" is a special bucket_id which is used as a template for unknown bucket IDs.

PARAMETER DESCRIPTION
bucket_id

The ID of the bucket to set the concurrency limit for.

TYPE: str

resource

The type of resource to target for the concurrency limit.

TYPE: BucketResource

limit

The maximum number of concurrent uses to allow.

TYPE: int

RETURNS DESCRIPTION
Self

The concurrency manager to allow call chaining.

RAISES DESCRIPTION
ValueError

If an invalid resource type is given. if limit is less 0 or negative.

InMemoryCooldownManager #

Bases: AbstractCooldownManager

In-memory standard implementation of AbstractCooldownManager.

Examples:

InMemoryCooldownManager.set_bucket may be used to set the cooldown for a specific bucket:

(
    InMemoryCooldownManager()
    # Set the default bucket template to a per-user 10 uses per-60 seconds cooldown.
    .set_bucket("default", tanjun.BucketResource.USER, 10, 60)
    # Set the "moderation" bucket to a per-guild 100 uses per-5 minutes cooldown.
    .set_bucket("moderation", tanjun.BucketResource.GUILD, 100, datetime.timedelta(minutes=5))
    .set_bucket()
    # add_to_client will setup the cooldown manager (setting it as an
    # injected dependency and registering callbacks to manage it).
    .add_to_client(client)
)

add_to_client(client) #

Add this cooldown manager to a tanjun client.

Note

This registers the manager as a type dependency and manages opening and closing the manager based on the client's life cycle.

PARAMETER DESCRIPTION
client

The client to add this cooldown manager to.

TYPE: tanjun.Client

close() #

Stop the cooldown manager.

RAISES DESCRIPTION
RuntimeError

If the cooldown manager is not running.

disable_bucket(bucket_id) #

Disable a cooldown bucket.

This will stop the bucket from ever hitting a cooldown and also prevents the bucket from defaulting.

Note

"default" is a special bucket_id which is used as a template for unknown bucket IDs.

PARAMETER DESCRIPTION
bucket_id

The bucket to disable.

TYPE: str

RETURNS DESCRIPTION
Self

This cooldown manager to allow for chaining.

open(*, _loop=None) #

Start the cooldown manager.

RAISES DESCRIPTION
RuntimeError

If the cooldown manager is already running. If called in a thread with no running event loop.

set_bucket(bucket_id, resource, limit, reset_after) #

Set the cooldown for a specific bucket.

Note

"default" is a special bucket_id which is used as a template for unknown bucket IDs.

PARAMETER DESCRIPTION
bucket_id

The ID of the bucket to set the cooldown for.

TYPE: str

resource

The type of resource to target for the cooldown.

TYPE: BucketResource

limit

The number of uses per cooldown period.

TYPE: int

reset_after

The cooldown period.

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

RETURNS DESCRIPTION
Self

The cooldown manager to allow call chaining.

RAISES DESCRIPTION
ValueError

If an invalid resource type is given. If reset_after or limit are negative, 0 or invalid. if limit is less 0 or negative.

InteractionAcceptsEnum #

Bases: enum.IntFlag

The possible configurations for which interaction this client should execute.

ALL = AUTOCOMPLETE | COMMANDS class-attribute #

Execute all the interaction types Tanjun supports.

AUTOCOMPLETE = enum.auto() class-attribute #

Execute autocomplete interactions.

COMMANDS = enum.auto() class-attribute #

Execute command interactions.

This includes slash command and context menu calls.

NONE = 0 class-attribute #

Set the client to execute no interactions.

LazyConstant #

Bases: typing.Generic[_T]

Injected type used to hold and generate lazy constants.

Note

To easily resolve this type use inject_lc.

__init__(callback) #

Initiate a new lazy constant.

PARAMETER DESCRIPTION
callback

Callback used to resolve this to a constant value.

This supports dependency injection and may either be sync or asynchronous.

TYPE: alluka.abc.CallbackSig[_T]

acquire() #

Acquire this lazy constant as an asynchronous lock.

This is used to ensure that the value is only generated once and should be kept acquired until LazyConstant.set_value has been called.

RETURNS DESCRIPTION
contextlib.AbstractAsyncContextManager[typing.Any]

Context manager that can be used to acquire the lock.

callback() property #

Descriptor of the callback used to get this constant's initial value.

get_value() #

Get the value of this constant if set, else None.

reset() #

Clear the internally stored value.

set_value(value) #

Set the constant value.

PARAMETER DESCRIPTION
value

The value to set.

TYPE: _T

RAISES DESCRIPTION
RuntimeError

If the constant has already been set.

MenuCommand #

Bases: base.PartialCommand[tanjun.MenuContext], tanjun.MenuCommand[_MenuCommandCallbackSigT, _MenuTypeT]

Base class used for the standard menu command implementations.

__init__(callback, type_, name, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True, _wrapped_command=None) #

Initialise a user or message menu command.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commands][] or when declare_global_commands is True

Note

If you want your first response to be ephemeral while using always_defer, you must set default_to_ephemeral to True.

PARAMETER DESCRIPTION
callback

Callback to execute when the command is invoked.

This should be an asynchronous callback which takes one positional argument of type tanjun.abc.MenuContext, returns None and may use dependency injection to access other services.

TYPE: collections.abc.Callable[[tanjun.abc.MenuContext, ...], collections.abc.Coroutine[Any, ANy, None]]

type_ : hikari.commands.CommandType The type of menu command this is.

Only [hikari.commands.CommandType.USER][] and [hikari.commands.CommandType.MESSAGE][]
are valid here.

name The command's name.

This must be between 1 and 32 characters in length.

always_defer Whether the contexts this command is executed with should always be deferred before being passed to the command's callback. default_member_permissions Member permissions necessary to utilize this command by default.

If this is [None][] then the configuration for the parent component or client
will be used.

default_to_ephemeral Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as [None][] then the default set on the parent command(s),
component or client will be in effect.

dm_enabled Whether this command is enabled in DMs with the bot.

If this is [None][] then the configuration for the parent component or client
will be used.

is_global Whether this command is a global command.

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MenuCommandCallbackSig], MenuCommand]

The decorator callback used to make a tanjun.MenuCommand.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name isn't in the length range of 1 to 32.
  • If the command name has uppercase characters.

set_ephemeral_default(state) #

Set whether this command's responses should default to ephemeral.

PARAMETER DESCRIPTION
state

Whether this command's responses should default to ephemeral. This will be overridden by any response calls which specify flags.

Setting this to None will let the default set on the parent command(s), component or client propagate and decide the ephemeral default for contexts used by this command.

TYPE: typing.Optional[bool]

RETURNS DESCRIPTION
Self

This command to allow for chaining.

wrapped_command() property #

The command object this wraps, if any.

MessageAcceptsEnum #

Bases: str, enum.Enum

The possible configurations for which events tanjun.Client should execute commands based on.

ALL = 'ALL' class-attribute #

Set the client to execute commands based on both DM and guild message create events.

DM_ONLY = 'DM_ONLY' class-attribute #

Set the client to execute commands based only DM message create events.

GUILD_ONLY = 'GUILD_ONLY' class-attribute #

Set the client to execute commands based only guild message create events.

NONE = 'NONE' class-attribute #

Set the client to not execute commands based on message create events.

get_event_type() #

Get the base event type this mode listens to.

RETURNS DESCRIPTION
type[hikari.events.MessageCreateEvent] | None

The type object of the MessageCreateEvent class this mode will register a listener for.

This will be None if this mode disables listening to message create events.

MessageCommand #

Bases: base.PartialCommand[tanjun.MessageContext], tanjun.MessageCommand[_CommandCallbackSigT]

Standard implementation of a message command.

__init__(callback, name, /, *names, validate_arg_keys=True, _wrapped_command=None) #

Initialise a message command.

PARAMETER DESCRIPTION
callback

Callback to execute when the command is invoked.

This should be an asynchronous callback which takes one positional argument of type tanjun.abc.MessageContext, returns None and may use dependency injection to access other services.

TYPE: collections.abc.Callable[[tanjun.abc.MessageContext, ...], collections.abc.Coroutine[None]]

name

The command name.

TYPE: str

*names

Variable positional arguments of other names for the command.

TYPE: str DEFAULT: ()

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

wrapped_command() property #

The command object this wraps, if any.

MessageCommandGroup #

Bases: MessageCommand[_CommandCallbackSigT], tanjun.MessageCommandGroup[_CommandCallbackSigT]

Standard implementation of a message command group.

__init__(callback, name, /, *names, strict=False, validate_arg_keys=True, _wrapped_command=None) #

Initialise a message command group.

PARAMETER DESCRIPTION
callback

Callback to execute when the command is invoked.

This should be an asynchronous callback which takes one positional argument of type tanjun.abc.MessageContext, returns None and may use dependency injection to access other services.

TYPE: collections.abc.Callable[[tanjun.abc.MessageContext, ...], collections.abc.Coroutine[None]]

name

The command name.

TYPE: str

*names

Variable positional arguments of other names for the command.

TYPE: str DEFAULT: ()

strict

Whether this command group should only allow commands without spaces in their names.

This allows for a more optimised command search pattern to be used and enforces that command names are unique to a single command within the group.

TYPE: bool DEFAULT: False

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

add_command(command) #

Add a command to this group.

PARAMETER DESCRIPTION
command

The command to add.

TYPE: tanjun.MessageCommand[typing.Any]

RETURNS DESCRIPTION
Self

The group instance to enable chained calls.

RAISES DESCRIPTION
ValueError

If one of the command's names is already registered in a strict command group.

as_sub_command(name, /, *names, validate_arg_keys=True) #

Build a message command in this group from a decorated callback.

PARAMETER DESCRIPTION
name

The command name.

TYPE: str

*names

Variable positional arguments of other names for the command.

TYPE: str DEFAULT: ()

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.CommandCallbackSig], MessageCommand]

The decorator callback used to make a sub-command.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand).

as_sub_group(name, /, *names, strict=False, validate_arg_keys=True) #

Build a message command group in this group from a decorated callback.

PARAMETER DESCRIPTION
name

The command name.

TYPE: str

*names

Variable positional arguments of other names for the command.

TYPE: str DEFAULT: ()

strict

Whether this command group should only allow commands without spaces in their names.

This allows for a more optimised command search pattern to be used and enforces that command names are unique to a single command within the group.

TYPE: bool DEFAULT: False

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.CommandCallbackSig], MessageCommand]

The decorator callback used to make a sub-command group.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand).

ModuleMissingLoaders #

Bases: RuntimeError, TanjunError

Error raised when a module is missing loaders.

message() property #

The error message.

path() property #

The path of the module which is missing loaders.

ModuleMissingUnloaders #

Bases: RuntimeError, TanjunError

Error raised when a module is missing unloaders.

message() property #

The error message.

path() property #

The path of the module which is missing unloaders.

ModuleStateConflict #

Bases: ValueError, TanjunError

Error raised when a module cannot be (un)loaded due to a state conflict.

message() property #

The error message.

path() property #

The path of the module which caused the error.

NotEnoughArgumentsError #

Bases: ParserError

Error raised by the parser when not enough arguments are found for a parameter.

parameter: str class-attribute #

Name of the parameter this error was raised for.

__init__(message, parameter) #

Initialise a not enough arguments error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

parameter

The parameter this error was raised for.

TYPE: str

ParserError #

Bases: TanjunError, ValueError

Base error raised by a parser or parameter during parsing.

Note

Expected errors raised by the parser will subclass this error.

__init__(message, parameter) #

Initialise a parser error.

PARAMETER DESCRIPTION
message

String message for this error.

TYPE: str

parameter

Name of the parameter which caused this error, should be None if not applicable.

TYPE: typing.Optional[str]

ShlexParser #

Bases: AbstractOptionParser

A shlex based AbstractOptionParser implementation.

__init__() #

Initialise a shlex parser.

SlashCommand #

Bases: BaseSlashCommand, tanjun.SlashCommand[_CommandCallbackSigT]

Standard implementation of a slash command.

__init__(callback, name, description, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True, sort_options=True, validate_arg_keys=True, _wrapped_command=None) #

Initialise a slash command.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commands][] or when declare_global_commands is True

Warning

default_member_permissions, "dm_enabled" and is_global are ignored for commands within slash command groups.

Note

If you want your first response to be ephemeral while using always_defer, you must set default_to_ephemeral to True.

PARAMETER DESCRIPTION
callback

Callback to execute when the command is invoked.

This should be an asynchronous callback which takes one positional argument of type tanjun.abc.SlashContext, returns None and may use dependency injection to access other services.

TYPE: collections.abc.Callable[[tanjun.abc.SlashContext, ...], collections.abc.Coroutine[Any, Any, None]]

name

The command's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The command's description. This should be inclusively between 1-100 characters in length.

TYPE: str

always_defer

Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.

TYPE: bool DEFAULT: False

default_member_permissions

Member permissions necessary to utilize this command by default.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Union[hikari.Permissions, int, None] DEFAULT: None

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

dm_enabled

Whether this command is enabled in DMs with the bot.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Optional[bool] DEFAULT: None

is_global

Whether this command is a global command.

TYPE: bool DEFAULT: True

sort_options

Whether this command should sort its set options based on whether they're required.

If this is True then the options are re-sorted to meet the requirement from Discord that required command options be listed before optional ones.

TYPE: bool DEFAULT: True

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the command name has uppercase characters.
  • If the description is over 100 characters long.

add_attachment_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add an attachment option to the slash command.

Note

This will result in options of type hikari.messages.Attachment.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

PARAMETER DESCRIPTION
default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str]

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used and the coverters field will be ignored.

TYPE: bool

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_bool_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a boolean option to a slash command.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_channel_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, types=None, pass_as_kwarg=True) #

Add a channel option to a slash command.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

types

A collection of the channel classes and types this option should accept.

If left as None or empty then the option will allow all channel types.

TYPE: typing.Optional[collections.Collection[typing.Union[type[hikari.PartialChannel], int]]] DEFAULT: None

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the command already has 25 options.
  • If an invalid type is passed in types.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_float_option(name, description, /, *, always_float=True, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True, _stack_level=0) #

Add a float option to a slash command.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

always_float

If this is set to True then the value will always be converted to a float (this will happen before it's passed to converters).

This masks behaviour from Discord where we will either be provided a float or int dependent on what the user provided.

TYPE: bool DEFAULT: True

autocomplete

The autocomplete callback for the option.

More information on this callback's signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type float.

TYPE: typing.Optional[tanjun.AutocompleteCallbackSig] DEFAULT: None

choices

The option's choices.

This is a mapping of [option_name, option_value] where option_name should be a string of up to 100 characters and option_value should be a float.

TYPE: typing.Optional[collections.Mapping[str, float]] DEFAULT: None

converters

The option's converters.

This may be either one or multiple converter callbacks used to convert the option's value to the final form. If no converters are provided then the raw value will be passed.

Only the first converter to pass will be used.

TYPE: typing.Union[collections.Collection[ConverterSig], ConverterSig] DEFAULT: ()

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

min_value

The option's (inclusive) minimum value.

TYPE: typing.Optional[float] DEFAULT: None

max_value

The option's (inclusive) maximum value.

TYPE: typing.Optional[float] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used and the fields coverters, and always_float will be ignored.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the option has more than 25 choices.
  • If the command already has 25 options.
  • If min_value is greater than max_value.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_int_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True, _stack_level=0) #

Add an integer option to the slash command.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

autocomplete

The autocomplete callback for the option.

More information on this callback's signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type int.

TYPE: typing.Optional[tanjun.AutocompleteCallbackSig] DEFAULT: None

choices

The option's choices.

This is a mapping of [option_name, option_value] where option_name should be a string of up to 100 characters and option_value should be an integer.

TYPE: typing.Optional[collections.Mapping[str, int]] DEFAULT: None

converters

The option's converters.

This may be either one or multiple converter callbacks used to convert the option's value to the final form. If no converters are provided then the raw value will be passed.

Only the first converter to pass will be used.

TYPE: typing.Union[collections.Collection[ConverterSig], ConverterSig] DEFAULT: ()

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

min_value

The option's (inclusive) minimum value.

TYPE: typing.Optional[int] DEFAULT: None

max_value

The option's (inclusive) maximum value.

TYPE: typing.Optional[int] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used and the coverters field will be ignored.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the option has more than 25 choices.
  • If the command already has 25 options.
  • If min_value is greater than max_value.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_member_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None) #

Add a member option to a slash command.

Warning

Unlike the other options, this is an artificial option which adds a restraint to the USER option type and therefore cannot have pass_as_kwarg set to False as this artificial constraint isn't present when its not being passed as a keyword argument.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_mentionable_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a mentionable option to a slash command.

Note

This may target roles, guild members or users and results in hikari.User | hikari.InteractionMember | hikari.Role.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_role_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a role option to a slash command.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_str_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True, _stack_level=0) #

Add a string option to the slash command.

Note

As a shorthand, choices also supports passing a list of strings rather than a dict of names to values (each string will used as both the choice's name and value with the names being capitalised).

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

autocomplete

The autocomplete callback for the option.

More information on this callback's signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type str.

TYPE: typing.Optional[tanjun.AutocompleteCallbackSig] DEFAULT: None

choices

The option's choices.

This either a mapping of [option_name, option_value] where both option_name and option_value should be strings of up to 100 characters or a sequence of strings where the string will be used for both the choice's name and value.

TYPE: typing.Union[collections.Mapping[str, str], collections.Sequence[str], None] DEFAULT: None

converters

The option's converters.

This may be either one or multiple converter callbacks used to convert the option's value to the final form. If no converters are provided then the raw value will be passed.

Only the first converter to pass will be used.

TYPE: typing.Union[collections.Sequence[ConverterSig], ConverterSig] DEFAULT: ()

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used and the coverters field will be ignored.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the option has more than 25 choices.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

add_user_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a user option to a slash command.

Note

This may result in hikari.interactions.base_interactions.InteractionMember or hikari.users.User if the user isn't in the current guild or if this command was executed in a DM channel.

PARAMETER DESCRIPTION
name

The option's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The option's description.

This should be inclusively between 1-100 characters in length.

TYPE: str

default

The option's default value.

If this is left as undefined then this option will be required.

TYPE: typing.Any DEFAULT: UNDEFINED_DEFAULT

key

Name of the argument this option's value should be passed to.

This defaults to the first name provided in name and is no-op if pass_as_kwarg is False.

TYPE: typing.Optional[str] DEFAULT: None

pass_as_kwarg

Whether or not to pass this option as a keyword argument to the command callback.

If False is passed here then default will only decide whether the option is required without the actual value being used.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the option name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the option name has uppercase characters.
  • If the option description is over 100 characters in length.
  • If the option has more than 25 choices.
  • If the command already has 25 options.
  • If name isn't valid for this command's callback when validate_arg_keys is True.

set_float_autocomplete(name, callback) #

Set the autocomplete callback for a float option.

PARAMETER DESCRIPTION
name

The option's name.

TYPE: str

callback

The autocomplete callback for the option.

More information on this callback's signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type float.

Passing None here will remove the autocomplete callback for the option.

TYPE: typing.Optional[tanjun.AutocompleteCallbackSig]

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
KeyError

Raises a key error if the option doesn't exist.

TypeError

Raises a type error if the option isn't of type float.

set_int_autocomplete(name, callback) #

Set the autocomplete callback for a string option.

PARAMETER DESCRIPTION
name

The option's name.

TYPE: str

callback

The autocomplete callback for the option.

More information on this callback's signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type str.

Passing None here will remove the autocomplete callback for the option.

TYPE: tanjun.AutocompleteCallbackSig

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
KeyError

Raises a key error if the option doesn't exist.

TypeError

Raises a type error if the option isn't of type str.

set_str_autocomplete(name, callback) #

Set the autocomplete callback for a str option.

PARAMETER DESCRIPTION
name

The option's name.

TYPE: str

callback

The autocomplete callback for the option.

More information on this callback's signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type str.

Passing None here will remove the autocomplete callback for the option.

TYPE: tanjun.AutocompleteCallbackSig

RETURNS DESCRIPTION
Self

The command object for chaining.

RAISES DESCRIPTION
KeyError

Raises a key error if the option doesn't exist.

TypeError

Raises a type error if the option isn't of type str.

with_float_autocomplete(name) #

Set the autocomplete callback for a float option through a decorator call.

PARAMETER DESCRIPTION
name

The option's name.

TYPE: str

RETURNS DESCRIPTION
Collections.abc.Callable[[tanjun.abc.AutocompleteCallbackSig], tanjun.abc.AutocompleteCallbackSig]

Decorator callback used to capture the autocomplete callback.

More information on the autocomplete signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type float.

RAISES DESCRIPTION
KeyError

Raises a key error if the option doesn't exist.

TypeError

Raises a type error if the option isn't of type float.

with_int_autocomplete(name) #

Set the autocomplete callback for a integer option through a decorator call.

PARAMETER DESCRIPTION
name

The option's name.

TYPE: str

RETURNS DESCRIPTION
Collections.abc.Callable[[tanjun.abc.AutocompleteCallbackSig], tanjun.abc.AutocompleteCallbackSig]

Decorator callback used to capture the autocomplete callback.

More information on the autocomplete signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type int.

RAISES DESCRIPTION
KeyError

Raises a key error if the option doesn't exist.

TypeError

Raises a type error if the option isn't of type int.

with_str_autocomplete(name) #

Set the autocomplete callback for a string option through a decorator call.

PARAMETER DESCRIPTION
name

The option's name.

TYPE: str

RETURNS DESCRIPTION
Collections.abc.Callable[[tanjun.abc.AutocompleteCallbackSig], tanjun.abc.AutocompleteCallbackSig]

Decorator callback used to capture the autocomplete callback.

More information on the autocomplete signature can be found at tanjun.abc.AutocompleteCallbackSig and the 2nd positional argument should be of type str.

RAISES DESCRIPTION
KeyError

Raises a key error if the option doesn't exist.

TypeError

Raises a type error if the option isn't of type str.

wrapped_command() property #

The command object this wraps, if any.

SlashCommandGroup #

Bases: BaseSlashCommand, tanjun.SlashCommandGroup

Standard implementation of a slash command group.

Note

Unlike message command groups, slash command groups cannot be callable functions themselves.

__init__(name, description, /, *, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True) #

Initialise a slash command group.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commands][] or when declare_global_commands is True

Warning

default_member_permissions, "dm_enabled" and is_global are ignored for commands groups within another slash command groups.

PARAMETER DESCRIPTION
name

The name of the command group.

This must match the regex ^[\w-]{1,32}$ in Unicode mode and be lowercase.

TYPE: str

description

The description of the command group.

TYPE: str

default_member_permissions

Member permissions necessary to utilize this command by default.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Union[hikari.Permissions, int, None] DEFAULT: None

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

dm_enabled

Whether this command is enabled in DMs with the bot.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Optional[bool] DEFAULT: None

is_global

Whether this command is a global command.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the command name has uppercase characters.
  • If the description is over 100 characters long.

add_command(command) #

Add a slash command to this group.

Warning

Command groups are only supported within top-level groups.

PARAMETER DESCRIPTION
command

Command to add to this group.

TYPE: tanjun.BaseSlashCommand

RETURNS DESCRIPTION
Self

Object of this group to enable chained calls.

as_sub_command(name, description, /, *, always_defer=False, default_to_ephemeral=None, sort_options=True, validate_arg_keys=True) #

Build a tanjun.SlashCommand in this command group by decorating a function.

Note

If you want your first response to be ephemeral while using always_defer, you must set default_to_ephemeral to True.

PARAMETER DESCRIPTION
name

The command's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The command's description. This should be inclusively between 1-100 characters in length.

TYPE: str

always_defer

Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.

TYPE: bool DEFAULT: False

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

sort_options

Whether this command should sort its set options based on whether they're required.

If this is True then the options are re-sorted to meet the requirement from Discord that required command options be listed before optional ones.

TYPE: bool DEFAULT: True

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.CommandCallbackSig], SlashCommand]

The decorator callback used to make a sub-command.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand tanjun.SlashCommand).

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the command name has uppercase characters.
  • If the description is over 100 characters long.

make_sub_group(name, description, /, *, default_to_ephemeral=None) #

Create a sub-command group in this group.

Note

Unlike message command groups, slash command groups cannot be callable functions themselves.

PARAMETER DESCRIPTION
name

The name of the command group.

This must match the regex ^[\w-]{1,32}$ in Unicode mode and be lowercase.

TYPE: str

description

The description of the command group.

TYPE: str

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
SlashCommandGroup

The created sub-command group.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the command name has uppercase characters.
  • If the description is over 100 characters long.

remove_command(command) #

Remove a command from this group.

PARAMETER DESCRIPTION
command

Command to remove from this group.

TYPE: tanjun.BaseSlashCommand

RETURNS DESCRIPTION
Self

Object of this group to enable chained calls.

with_command(command) #

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

PARAMETER DESCRIPTION
command

Command to add to this group.

TYPE: tanjun.abc.BaseSlashCommand

RETURNS DESCRIPTION
tanjun.abc.BaseSlashCommand

Command which was added to this group.

TanjunError #

Bases: Exception

The base class for all errors raised by Tanjun.

TooManyArgumentsError #

Bases: ParserError

Error raised by the parser when too many arguments are found for a parameter.

parameter: str class-attribute #

Name of the parameter this error was raised for.

__init__(message, parameter) #

Initialise a too many arguments error.

PARAMETER DESCRIPTION
message

The error message.

TYPE: str

parameter

The parameter this error was raised for.

TYPE: str

as_interval(interval, /, *, fatal_exceptions=(), ignored_exceptions=(), max_runs=None) #

Decorator to create an schedule.

PARAMETER DESCRIPTION
interval

The interval between calls. Passed as a timedelta, or a number of seconds.

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

fatal_exceptions

A sequence of exceptions that will cause the schedule to stop if raised by the callback, start callback or stop callback.

TYPE: collections.Sequence[type[Exception]] DEFAULT: ()

ignored_exceptions

A sequence of exceptions that should be ignored if raised by the callback, start callback or stop callback.

TYPE: collections.Sequence[type[Exception]] DEFAULT: ()

max_runs

The maximum amount of times the schedule runs.

TYPE: typing.Optional[int] DEFAULT: None

RETURNS DESCRIPTION
collections.Callable[[_CallbackSigT], tanjun.scheduling.IntervalSchedule[_CallbackSigT]]

The decorator used to create the schedule.

This should be decorating an asynchronous function which takes no positional arguments, returns None and may use dependency injection.

as_loader(callback=None, /, *, standard_impl=True) #

Mark a callback as being used to load Tanjun components from a module.

Note

This is only necessary if you wish to use [tanjun.Client.load_modules][].

PARAMETER DESCRIPTION
callback

The callback used to load Tanjun components from a module.

This should take one argument of type tanjun.Client (or tanjun.abc.Client if standard_impl is False), return nothing and will be expected to initiate and add utilities such as components to the provided client.

TYPE: typing.Union[collections.Callable[[tanjun.Client], None], collections.Callable[[Client], None], None] DEFAULT: None

standard_impl

Whether this loader should only allow instances of tanjun.Client as opposed to tanjun.abc.Client.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.Client], None]]

The decorated load callback.

as_message_command(name, /, *names, validate_arg_keys=True) #

Build a message command from a decorated callback.

PARAMETER DESCRIPTION
name

The command name.

TYPE: str

*names

Variable positional arguments of other names for the command.

TYPE: str DEFAULT: ()

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.CommandCallbackSig], MessageCommand]

The decorator callback used to make a tanjun.MessageCommand.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope.

as_message_command_group(name, /, *names, strict=False, validate_arg_keys=True) #

Build a message command group from a decorated callback.

PARAMETER DESCRIPTION
name

The command name.

TYPE: str

*names

Variable positional arguments of other names for the command.

TYPE: str DEFAULT: ()

strict

Whether this command group should only allow commands without spaces in their names.

This allows for a more optimised command search pattern to be used and enforces that command names are unique to a single command within the group.

TYPE: bool DEFAULT: False

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.CommandCallbackSig], MessageCommand]

The decorator callback used to make a tanjun.MessageCommandGroup.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope.

as_message_menu(name, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True) #

Build a message tanjun.MenuCommand by decorating a function.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commands][] or when declare_global_commands is True

Note

If you want your first response to be ephemeral while using always_defer, you must set default_to_ephemeral to True.

Examples:

@as_message_menu("message")
async def message_command(self, ctx: tanjun.abc.MenuContext, message: hikari.Message) -> None:
    await ctx.respond(
        embed=hikari.Embed(title="Message content", description=message.content or "N/A")
    )
PARAMETER DESCRIPTION
name

The command's name.

This must be between 1 and 32 characters in length.

TYPE: str

always_defer

Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.

TYPE: bool DEFAULT: False

default_member_permissions

Member permissions necessary to utilize this command by default.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Union[hikari.Permissions, int, None] DEFAULT: None

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

dm_enabled

Whether this command is enabled in DMs with the bot.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Optional[bool] DEFAULT: None

is_global

Whether this command is a global command.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MenuCommandCallbackSig], MenuCommand]

The decorator callback used to make a tanjun.MenuCommand.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name isn't in the length range of 1 to 32.
  • If the command name has uppercase characters.

as_self_injecting(client) #

Make a callback self-inecting by linking it to a client through a decorator call.

Examples:

def make_callback(client: tanjun.Client) -> collections.abc.Callable[[], int]:
    @tanjun.as_self_injected(client)
    async def get_int_value(
        redis: redis.Client = tanjun.inject(type=redis.Client)
    ) -> int:
        return int(await redis.get('key'))

    return get_int_value
PARAMETER DESCRIPTION
client

The client to use to resolve dependencies.

TYPE: tanjun.abc.Client

RETURNS DESCRIPTION
collections.abc.Callable[[alluka.abc.CallbackSig], alluka.AsyncSelfInjecting]

Decorator callback that returns a self-injecting callback.

as_slash_command(name, description, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True, sort_options=True, validate_arg_keys=True) #

Build a tanjun.SlashCommand by decorating a function.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commands][] or when declare_global_commands is True

Warning

default_member_permissions, "dm_enabled" and is_global are ignored for commands within slash command groups.

Note

If you want your first response to be ephemeral while using always_defer, you must set default_to_ephemeral to True.

Examples:

@as_slash_command("ping", "Get the bot's latency")
async def ping_command(self, ctx: tanjun.abc.SlashContext) -> None:
    start_time = time.perf_counter()
    await ctx.rest.fetch_my_user()
    time_taken = (time.perf_counter() - start_time) * 1_000
    await ctx.respond(f"PONG\n - REST: {time_taken:.0f}mss")
PARAMETER DESCRIPTION
name

The command's name.

This must match the regex ^[\w-]{1,32} in Unicode mode and be lowercase.

TYPE: str

description

The command's description. This should be inclusively between 1-100 characters in length.

TYPE: str

always_defer

Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.

TYPE: bool DEFAULT: False

default_member_permissions

Member permissions necessary to utilize this command by default.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Union[hikari.Permissions, int, None] DEFAULT: None

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

dm_enabled

Whether this command is enabled in DMs with the bot.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Optional[bool] DEFAULT: None

is_global

Whether this command is a global command.

TYPE: bool DEFAULT: True

sort_options

Whether this command should sort its set options based on whether they're required.

If this is True then the options are re-sorted to meet the requirement from Discord that required command options be listed before optional ones.

TYPE: bool DEFAULT: True

validate_arg_keys

Whether to validate that option keys match the command callback's signature.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.CommandCallbackSig], SlashCommand]

The decorator callback used to make a tanjun.SlashCommand.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the command name has uppercase characters.
  • If the description is over 100 characters long.

as_time_schedule(*, months=(), weekly=False, days=(), hours=(), minutes=(), seconds=0, fatal_exceptions=(), ignored_exceptions=(), timezone=None) #

Create a time schedule through a decorator call.

PARAMETER DESCRIPTION
months

Either one or multiple months the schedule should run on.

If this is not specified or an empty sequence then the schedule will run on all months.

TYPE: typing.Union[int, collections.Sequence[int]] DEFAULT: ()

weekly

Whether the schedule should run on a weekly basis.

TYPE: bool DEFAULT: False

days

Either one or multiple days the schedule should run on.

When weekly is True, days will refer to the days of the week (range(7)).

Otherwise this will refer to the days of the month (range(32)). For months where less than 31 days exist, numbers which are too large will be ignored.

If this is not specified or an empty sequence, then the schedule will on all days.

TYPE: typing.Union[int, collections.Sequence[int]] DEFAULT: ()

hours

Either one or multiple hours the schedule should run on.

If this is not specified or an empty sequence then the schedule will run on all hours.

TYPE: typing.Union[int, collections.Sequence[int]] DEFAULT: ()

minutes

Either one or multiple minutes the schedule should run on.

If this is not specified or an empty sequence then the schedule will run on all minutes.

TYPE: typing.Union[int, collections.Sequence[int]] DEFAULT: ()

seconds

Either one or multiple seconds the schedule should run on.

Defaults to the start of the minute if not specified or an empty sequence.

TYPE: typing.Union[int, collections.Sequence[int]] DEFAULT: 0

fatal_exceptions

A sequence of exceptions that will cause the schedule to stop if raised by the callback, start callback or stop callback.

TYPE: collections.Sequence[type[Exception]] DEFAULT: ()

ignored_exceptions

A sequence of exceptions that should be ignored if raised by the callback, start callback or stop callback.

TYPE: collections.Sequence[type[Exception]] DEFAULT: ()

timezone

The timezone to use for the schedule.

If this is not specified then the system's local timezone will be used.

TYPE: typing.Optional[datetime.timezone] DEFAULT: None

RETURNS DESCRIPTION
collections.Callable[[_CallbackSigT], tanjun.scheduling.TimeSchedule[_CallbackSigT]]

The decorator used to create the schedule.

This should be decorating an asynchronous function which takes no positional arguments, returns None and may use dependency injection.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If months has any values outside the range of range(1, 13).
  • If days has any values outside the range of range(1, 32) when weekly is False or outside the range of range(1, 7) when weekly is True.
  • If hours has any values outside the range of range(0, 24).
  • If minutes has any values outside the range of range(0, 60).
  • If seconds has any values outside the range of range(0, 60).

as_unloader(callback=None, /, *, standard_impl=True) #

Mark a callback as being used to unload a module's utilities from a client.

Note

This is the inverse of tanjun.as_loader and is only necessary if you wish to use the [tanjun.Client.unload_modules][] or [tanjun.Client.reload_modules][].

PARAMETER DESCRIPTION
callback

The callback used to unload Tanjun components from a module.

This should take one argument of type tanjun.Client (or tanjun.abc.Client if standard_impl is False), return nothing and will be expected to remove utilities such as components from the provided client.

TYPE: typing.Union[collections.Callable[[Client], None], collections.Callable[[tanjun.Client], None], None] DEFAULT: None

standard_impl

Whether this unloader should only allow instances of tanjun.Client as opposed to tanjun.abc.Client.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.Client], None]]

The decorated unload callback.

as_user_menu(name, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True) #

Build a user tanjun.MenuCommand by decorating a function.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commands][] or when declare_global_commands is True

Note

If you want your first response to be ephemeral while using always_defer, you must set default_to_ephemeral to True.

Examples:

@as_user_menu("user")
async def user_command(
    self,
    ctx: tanjun.abc.MenuContext,
    user: hikari.User | hikari.InteractionMember,
) -> None:
    await ctx.respond(f"Hello {user}")
PARAMETER DESCRIPTION
name

The command's name.

This must be between 1 and 32 characters in length.

TYPE: str

always_defer

Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.

TYPE: bool DEFAULT: False

default_member_permissions

Member permissions necessary to utilize this command by default.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Union[hikari.Permissions, int, None] DEFAULT: None

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

dm_enabled

Whether this command is enabled in DMs with the bot.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Optional[bool] DEFAULT: None

is_global

Whether this command is a global command.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MenuCommandCallbackSig], MenuCommand]

The decorator callback used to make a tanjun.MenuCommand.

This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name isn't in the length range of 1 to 32.
  • If the command name has uppercase characters.

cached_inject(callback, /, *, expire_after=None) #

Inject a callback with caching.

This acts like alluka.inject and the result of it should also be assigned to a parameter's default to be used.

Example#

async def resolve_database(
    client: tanjun.abc.Client = tanjun.inject(type=tanjun.abc.Client)
) -> Database:
    raise NotImplementedError

@tanjun.as_message_command("command name")
async def command(
    ctx: tanjun.abc.Context, db: Database = tanjun.cached_inject(resolve_database)
) -> None:
    raise NotImplementedError
PARAMETER DESCRIPTION
callback

The callback to inject.

TYPE: alluka.abc.CallbackSig[_T]

expire_after

The amount of time to cache the result for in seconds.

Leave this as None to cache for the runtime of the application.

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

RETURNS DESCRIPTION
alluka.InjectedDescriptor[_T]

Injector used to resolve the cached callback.

RAISES DESCRIPTION
ValueError

If expire_after is not a valid value. If expire_after is not less than or equal to 0 seconds.

inject_lc(type_) #

Make a LazyConstant injector.

This acts like alluka.inject and the result of it should also be assigned to a parameter's default to be used.

Note

For this to work, a LazyConstant must've been set as a type dependency for the passed type_.

PARAMETER DESCRIPTION
type_

The type of the constant to resolve.

TYPE: type[_T]

RETURNS DESCRIPTION
alluka.InjectedDescriptor[_T]

Injector used to resolve the LazyConstant.

Example#

@component.with_command
@tanjun.as_message_command
async def command(
    ctx: tanjun.abc.MessageCommand,
    application: hikari.Application = tanjun.inject_lc(hikari.Application)
) -> None:
    raise NotImplementedError

...

async def resolve_app(
    client: tanjun.abc.Client = tanjun.inject(type=tanjun.abc.Client)
) -> hikari.Application:
    raise NotImplementedError

tanjun.Client.from_gateway_bot(...).set_type_dependency(
    tanjun.LazyConstant[hikari.Application] = tanjun.LazyConstant(resolve_app)
)

slash_command_group(name, description, /, *, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True) #

Create a slash command group.

Note

Unlike message command groups, slash command groups cannot be callable functions themselves.

Warning

default_member_permissions, "dm_enabled" and is_global are ignored for command groups within other slash command groups.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by [tanjun.Client.declare_global_commandsadd_command or when declare_global_commands is True

Examples:

Sub-commands can be added to the created slash command object through the following decorator based approach:

help_group = tanjun.slash_command_group("help", "get help")

@help_group.with_command
@tanjun.with_str_slash_option("command_name", "command name")
@tanjun.as_slash_command("command", "Get help with a command")
async def help_command_command(ctx: tanjun.abc.SlashContext, command_name: str) -> None:
    ...

@help_group.with_command
@tanjun.as_slash_command("me", "help me")
async def help_me_command(ctx: tanjun.abc.SlashContext) -> None:
    ...

component = tanjun.Component().add_slash_command(help_group)
PARAMETER DESCRIPTION
name

The name of the command group.

This must match the regex ^[\w-]{1,32}$ in Unicode mode and be lowercase.

TYPE: str

description

The description of the command group.

TYPE: str

default_member_permissions

Member permissions necessary to utilize this command by default.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Union[hikari.Permissions, int, None] DEFAULT: None

default_to_ephemeral

Whether this command's responses should default to ephemeral unless flags are set to override this.

If this is left as None then the default set on the parent command(s), component or client will be in effect.

TYPE: typing.Optional[bool] DEFAULT: None

dm_enabled

Whether this command is enabled in DMs with the bot.

If this is None then the configuration for the parent component or client will be used.

TYPE: typing.Optional[bool] DEFAULT: None

is_global

Whether this command is a global command.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
SlashCommandGroup

The command group.

RAISES DESCRIPTION
ValueError

Raises a value error for any of the following reasons:

  • If the command name doesn't match the regex ^[\w-]{1,32}$ (Unicode mode).
  • If the command name has uppercase characters.
  • If the description is over 100 characters long.

to_bool(value) #

Convert user string input into a boolean value.

PARAMETER DESCRIPTION
value

The value to convert.

TYPE: str

RETURNS DESCRIPTION
bool

The converted value.

RAISES DESCRIPTION
ValueError

If the value cannot be converted.

to_color(argument) #

Convert user input to a hikari.colors.Color object.

to_datetime(value) #

Parse a datetime from Discord's datetime format.

More information on this format can be found at https://discord.com/developers/docs/reference#message-formatting-timestamp-styles

PARAMETER DESCRIPTION
value

The value to parse.

TYPE: str

RETURNS DESCRIPTION
datetime.datetime

The parsed datetime.

RAISES DESCRIPTION
ValueError

If the value cannot be parsed.

with_all_checks(check, /, *checks, follow_wrapped=False) #

Add a check which will pass if all the provided checks pass through a decorator call.

This ensures that the callbacks are run in the order they were supplied in rather than concurrently.

PARAMETER DESCRIPTION
check

The first check callback to combine.

TYPE: tanjun.CheckSig

*checks

Additional check callbacks to combine.

TYPE: tanjun.CheckSig DEFAULT: ()

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.Context], collections.abc.Coroutine[typing.Any, typing.Any, bool]]

A check which will pass if all of the provided check callbacks pass.

with_any_checks(check, /, *checks, error=None, error_message, follow_wrapped=False, halt_execution=False, suppress=(errors.CommandError, errors.HaltExecution)) #

Add a check which'll pass if any of the provided checks pass through a decorator call.

This ensures that the callbacks are run in the order they were supplied in rather than concurrently.

PARAMETER DESCRIPTION
check

The first check callback to combine.

TYPE: tanjun.CheckSig

*checks

Additional check callbacks to combine.

TYPE: tanjun.CheckSig DEFAULT: ()

error

Callback used to create a custom error to raise if the check fails.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

TYPE: typing.Optional[str]

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

suppress

Tuple of the exceptions to suppress when a check fails.

TYPE: tuple[type[Exception], ...] DEFAULT: (errors.CommandError, errors.HaltExecution)

RETURNS DESCRIPTION
collections.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]

A decorator which adds the generated check to a command.

with_argument(key, /, converters=(), *, default=UNDEFINED, greedy=False, max_value=None, min_value=None, multi=False) #

Add an argument to a message command through a decorator call.

Warning

Since order matters for positional arguments, you'll want to keep in mind that decorator execution starts at the decorator closest to the command and goes upwards with this deciding where a positional argument is located in a command's signature.

Note

If no parser is explicitly set on the command this is decorating before this decorator call then this will set ShlexParser as the parser.

Examples:

import tanjun

@tanjun.parsing.with_argument("command", converters=int, default=42)
@tanjun.parsing.with_parser
@tanjun.component.as_message_command("command")
async def command(self, ctx: tanjun.abc.Context, /, argument: int):
    ...
PARAMETER DESCRIPTION
key

The string identifier of this argument (may be used to pass the result of this argument to the command's callback during execution).

TYPE: str

converters

The converter(s) this argument should use to handle values passed to it during parsing.

If no converters are provided then the raw string value will be passed.

Only the first converter to pass will be used.

TYPE: _MaybeIterable[ConverterSig[typing.Any]] DEFAULT: ()

default

The default value of this argument, if left as UNDEFINED then this will have no default.

TYPE: _UndefinedOr[typing.Any] DEFAULT: UNDEFINED

greedy

Whether or not this argument should be greedy (meaning that it takes in the remaining argument values).

TYPE: bool DEFAULT: False

max_value

Assert that the parsed value(s) for this argument are less than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

min_value

Assert that the parsed value(s) for this argument are greater than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

multi

Whether this argument can be passed multiple times.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]

Decorator function for the message command this argument is being added to.

RAISES DESCRIPTION
ValueError

If key isn't valid for any of the commands this command's parser is linked to where validate_arg_keys is True.

with_attachment_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add an attachment option to a slash command.

For more information on this function's parameters see tanjun.SlashCommand.add_attachment_option.

Examples:

@with_attachment_slash_option("name", "A name.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, name: hikari.Attachment) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_author_permission_check(permissions, *, error=None, error_message="You don't have the permissions required to use this command", follow_wrapped=False, halt_execution=False) #

Only let a command run if the author has certain permissions in the current channel.

Note

This will only pass for commands in DMs if permissions is valid for a DM context (e.g. can't have any moderation permissions)

PARAMETER DESCRIPTION
permissions

The permission(s) required for this command to run.

TYPE: typing.Union[hikari.Permissions, int]

error

Callback used to create a custom error to raise if the check fails.

This should take 1 positional argument of type hikari.permissions.Permissions which represents the missing permissions required for this command to run.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[hikari.Permissions], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: "You don't have the permissions required to use this command"

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]

A command decorator callback which adds the check.

with_bool_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a boolean option to a slash command.

For information on this function's parameters see tanjun.SlashCommand.add_bool_option.

Examples:

@with_bool_slash_option("flag", "Whether this flag should be enabled.", default=False)
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, flag: bool) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_channel_slash_option(name, description, /, *, types=None, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a channel option to a slash command.

For information on this function's parameters see tanjun.SlashCommand.add_channel_option.

Examples:

@with_channel_slash_option("channel", "channel to target.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, channel: hikari.InteractionChannel) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_check(check, /, *, follow_wrapped=False) #

Add a generic check to a command.

PARAMETER DESCRIPTION
check

The check to add to this command.

TYPE: tanjun.CheckSig

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]

A command decorator callback which adds the check.

with_concurrency_limit(bucket_id, /, *, error=None, error_message='This resource is currently busy; please try again later.', follow_wrapped=False) #

Add the hooks used to manage a command's concurrency limit through a decorator call.

Warning

Concurrency limiters will only work if there's a setup injected AbstractConcurrencyLimiter dependency with InMemoryConcurrencyLimiter being usable as a standard in-memory concurrency manager.

PARAMETER DESCRIPTION
bucket_id

The concurrency limit bucket's ID.

TYPE: str

error

Callback used to create a custom error to raise if the check fails.

This should two one str argument which is the limiting bucket's ID.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[str], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if this fails to acquire the concurrency limit.

TYPE: str DEFAULT: 'This resource is currently busy; please try again later.'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]

A decorator that adds the concurrency limiter hooks to a command.

with_cooldown(bucket_id, /, *, error=None, error_message='This command is currently in cooldown. Try again {cooldown}.', follow_wrapped=False, owners_exempt=True) #

Add a pre-execution hook used to manage a command's cooldown through a decorator call.

Warning

Cooldowns will only work if there's a setup injected AbstractCooldownManager dependency with InMemoryCooldownManager being usable as a standard in-memory cooldown manager.

PARAMETER DESCRIPTION
bucket_id

The cooldown bucket's ID.

TYPE: str

error

Callback used to create a custom error to raise if the check fails.

This should two arguments one of type str and datetime.datetime where the first is the limiting bucket's ID and the second is when said bucket can be used again.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[str, datetime.datetime], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

TYPE: str DEFAULT: 'This command is currently in cooldown. Try again {cooldown}.'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

owners_exempt

Whether owners should be exempt from the cooldown.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]

A decorator that adds a CooldownPreExecution hook to the command.

with_dm_check(command=None, /, *, error=None, error_message='Command can only be used in DMs', follow_wrapped=False, halt_execution=False) #

Only let a command run in a DM channel.

PARAMETER DESCRIPTION
command

The command to add this check to.

TYPE: tanjun.abc.ExecutableCommand | None DEFAULT: None

error

Callback used to create a custom error to raise if the check fails.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: 'Command can only be used in DMs'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommand

The command this check was added to.

with_float_slash_option(name, description, /, *, always_float=True, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True) #

Add a float option to a slash command.

For information on this function's parameters see tanjun.SlashCommand.add_float_option.

Examples:

@with_float_slash_option("float_value", "Float value.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, float_value: float) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_greedy_argument(key, /, converters=(), *, default=UNDEFINED, max_value=None, min_value=None) #

Add a greedy argument to a message command through a decorator call.

A greedy argument will consume the remaining positional arguments and pass them through to the converters as one joined string while also requiring that at least one more positional argument is remaining unless a default is set.

Warning

Since order matters for positional arguments, you'll want to keep in mind that decorator execution starts at the decorator closest to the command and goes upwards with this deciding where a positional argument is located in a command's signature.

Note

If no parser is explicitly set on the command this is decorating before this decorator call then this will set ShlexParser as the parser.

Examples:

import tanjun

@tanjun.parsing.with_greedy_argument("command", converters=StringView)
@tanjun.parsing.with_parser
@tanjun.component.as_message_command("command")
async def command(self, ctx: tanjun.abc.Context, /, argument: StringView):
    ...
PARAMETER DESCRIPTION
key

The string identifier of this argument (may be used to pass the result of this argument to the command's callback during execution).

TYPE: str

converters

The converter(s) this argument should use to handle values passed to it during parsing.

If no converters are provided then the raw string value will be passed.

Only the first converter to pass will be used.

TYPE: _MaybeIterable[ConverterSig[typing.Any]] DEFAULT: ()

default

The default value of this argument, if left as UNDEFINED then this will have no default.

TYPE: _UndefinedOr[typing.Any] DEFAULT: UNDEFINED

max_value

Assert that the parsed value(s) for this argument are less than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

min_value

Assert that the parsed value(s) for this argument are greater than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]

Decorator function for the message command this argument is being added to.

RAISES DESCRIPTION
ValueError

If key isn't valid for any of the commands this command's parser is linked to where validate_arg_keys is True.

with_guild_check(command=None, /, *, error=None, error_message='Command can only be used in guild channels', follow_wrapped=False, halt_execution=False) #

Only let a command run in a guild channel.

PARAMETER DESCRIPTION
command

The command to add this check to.

TYPE: tanjun.abc.ExecutableCommand | None DEFAULT: None

error

Callback used to create a custom error to raise if the check fails.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: 'Command can only be used in guild channels'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommanmd

The command this check was added to.

with_int_slash_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True) #

Add an integer option to a slash command.

For information on this function's parameters see tanjun.SlashCommand.add_int_option.

Examples:

@with_int_slash_option("int_value", "Int value.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, int_value: int) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_member_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None) #

Add a member option to a slash command.

For information on this function's arguments see tanjun.SlashCommand.add_member_option.

Examples:

@with_member_slash_option("member", "member to target.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, member: hikari.InteractionMember) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_mentionable_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a mentionable option to a slash command.

For information on this function's arguments see tanjun.SlashCommand.add_mentionable_option.

Note

This may target roles, guild members or users and results in hikari.User | hikari.InteractionMember | hikari.Role.

Examples:

@with_mentionable_slash_option("mentionable", "Mentionable entity to target.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, mentionable: [Role, InteractionMember, User]) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_multi_argument(key, /, converters=(), *, default=UNDEFINED, max_value=None, min_value=None) #

Add a multi-argument to a message command through a decorator call.

A multi argument will consume the remaining positional arguments and pass them to the converters through multiple calls while also requiring that at least one more positional argument is remaining unless a default is set and passing through the results to the command's callback as a sequence.

Warning

Since order matters for positional arguments, you'll want to keep in mind that decorator execution starts at the decorator closest to the command and goes upwards with this deciding where a positional argument is located in a command's signature.

Note

If no parser is explicitly set on the command this is decorating before this decorator call then this will set ShlexParser as the parser.

Examples:

import tanjun

@tanjun.parsing.with_multi_argument("command", converters=int)
@tanjun.parsing.with_parser
@tanjun.component.as_message_command("command")
async def command(self, ctx: tanjun.abc.Context, /, argument: collections.abc.Sequence[int]):
    ...
PARAMETER DESCRIPTION
key

The string identifier of this argument (may be used to pass the result of this argument to the command's callback during execution).

TYPE: str

converters

The converter(s) this argument should use to handle values passed to it during parsing.

If no converters are provided then the raw string value will be passed.

Only the first converter to pass will be used.

TYPE: _MaybeIterable[ConverterSig[typing.Any]] DEFAULT: ()

default

The default value of this argument, if left as UNDEFINED then this will have no default.

TYPE: _UndefinedOr[typing.Any] DEFAULT: UNDEFINED

max_value

Assert that the parsed value(s) for this argument are less than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

min_value

Assert that the parsed value(s) for this argument are greater than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]

Decorator function for the message command this argument is being added to.

RAISES DESCRIPTION
ValueError

If key isn't valid for any of the commands this command's parser is linked to where validate_arg_keys is True.

with_multi_option(key, name, /, *names, converters=(), default, empty_value=UNDEFINED, max_value=None, min_value=None) #

Add an multi-option to a command's parser through a decorator call.

A multi option will consume all the values provided for an option and pass them through to the converters as an array of strings while also requiring that at least one value is provided for the option unless a default is set.

Note

If no parser is explicitly set on the command this is decorating before this decorator call then this will set ShlexParser as the parser.

Examples:

import tanjun

@tanjun.parsing.with_multi_option("command", converters=int, default=())
@tanjun.parsing.with_parser
@tanjun.component.as_message_command("command")
async def command(self, ctx: tanjun.abc.Context, /, argument: collections.abc.Sequence[int]):
    ...
PARAMETER DESCRIPTION
key

The string identifier of this option which will be used to pass the result of this argument to the command's callback during execution as a keyword argument.

TYPE: str

name

The name of this option used for identifying it in the parsed content.

TYPE: str

*names

Other names of this option used for identifying it in the parsed content.

TYPE: str DEFAULT: ()

default

The default value of this argument, unlike arguments this is required for options.

TYPE: typing.Any

converters

The converter(s) this argument should use to handle values passed to it during parsing.

If no converters are provided then the raw string value will be passed.

Only the first converter to pass will be used.

TYPE: _MaybeIterable[ConverterSig[typing.Any]] DEFAULT: ()

empty_value

The value to use if this option is provided without a value. If left as UNDEFINED then this option will error if it's provided without a value.

TYPE: _UndefinedOr[typing.Any] DEFAULT: UNDEFINED

max_value

Assert that the parsed value(s) for this option are less than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

min_value

Assert that the parsed value(s) for this option are greater than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]

Decorator function for the message command this option is being added to.

RAISES DESCRIPTION
ValueError

If key isn't valid for any of the commands this command's parser is linked to where validate_arg_keys is True.

with_nsfw_check(command=None, /, *, error=None, error_message='Command can only be used in NSFW channels', follow_wrapped=False, halt_execution=False) #

Only let a command run in a channel that's marked as nsfw.

PARAMETER DESCRIPTION
command

The command to add this check to.

TYPE: tanjun.abc.ExecutableCommand | None DEFAULT: None

error

Callback used to create a custom error to raise if the check fails.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: 'Command can only be used in NSFW channels'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommand

The command this check was added to.

with_option(key, name, /, *names, converters=(), default, empty_value=UNDEFINED, max_value=None, min_value=None, multi=False) #

Add an option to a message command through a decorator call.

Note

If no parser is explicitly set on the command this is decorating before this decorator call then this will set ShlexParser as the parser.

Examples:

import tanjun

@tanjun.parsing.with_option("command", converters=int, default=42)
@tanjun.parsing.with_parser
@tanjun.component.as_message_command("command")
async def command(self, ctx: tanjun.abc.Context, /, argument: int):
    ...
PARAMETER DESCRIPTION
key

The string identifier of this option which will be used to pass the result of this argument to the command's callback during execution as a keyword argument.

TYPE: str

name

The name of this option used for identifying it in the parsed content.

TYPE: str

*names

Other names of this option used for identifying it in the parsed content.

TYPE: str DEFAULT: ()

default

The default value of this argument, unlike arguments this is required for options.

TYPE: typing.Any

converters

The converter(s) this argument should use to handle values passed to it during parsing.

If no converters are provided then the raw string value will be passed.

Only the first converter to pass will be used.

TYPE: _MaybeIterable[ConverterSig[typing.Any]] DEFAULT: ()

empty_value

The value to use if this option is provided without a value. If left as UNDEFINED then this option will error if it's provided without a value.

TYPE: _UndefinedOr[typing.Any] DEFAULT: UNDEFINED

max_value

Assert that the parsed value(s) for this option are less than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

min_value

Assert that the parsed value(s) for this option are greater than or equal to this.

If any converters are provided then this should be compatible with the result of them.

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

multi

If this option can be provided multiple times.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]

Decorator function for the message command this option is being added to.

RAISES DESCRIPTION
ValueError

If key isn't valid for any of the commands this command's parser is linked to where validate_arg_keys is True.

with_own_permission_check(permissions, *, error=None, error_message="Bot doesn't have the permissions required to run this command", follow_wrapped=False, halt_execution=False) #

Only let a command run if we have certain permissions in the current channel.

Note

This will only pass for commands in DMs if permissions is valid for a DM context (e.g. can't have any moderation permissions)

PARAMETER DESCRIPTION
permissions

The permission(s) required for this command to run.

TYPE: typing.Union[hikari.Permissions, int]

error

Callback used to create a custom error to raise if the check fails.

This should take 1 positional argument of type hikari.permissions.Permissions which represents the missing permissions required for this command to run.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[hikari.Permissions], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: "Bot doesn't have the permissions required to run this command"

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]

A command decorator callback which adds the check.

with_owner_check(command=None, /, *, error=None, error_message='Only bot owners can use this command', follow_wrapped=False, halt_execution=False) #

Only let a command run if it's being triggered by one of the bot's owners.

PARAMETER DESCRIPTION
command

The command to add this check to.

TYPE: tanjun.abc.ExecutableCommand | None DEFAULT: None

error

Callback used to create a custom error to raise if the check fails.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: 'Only bot owners can use this command'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommand

The command this check was added to.

with_parser(command) #

Add a shlex parser command parser to a supported command.

Example#

@tanjun.with_argument("arg", converters=int)
@tanjun.with_parser
@tanjun.as_message_command("hi")
async def hi(ctx: tanjun.MessageContext, arg: int) -> None:
    ...
PARAMETER DESCRIPTION
command

The message command to set the parser on.

TYPE: _CommandT

RETURNS DESCRIPTION
tanjun.abc.MessageCommand

The command with the parser set.

RAISES DESCRIPTION
ValueError

If the command already has a parser set.

with_role_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a role option to a slash command.

For information on this function's parameters see tanjun.SlashCommand.add_role_option.

Examples:

@with_role_slash_option("role", "Role to target.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, role: hikari.Role) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_sfw_check(command=None, /, *, error=None, error_message='Command can only be used in SFW channels', follow_wrapped=False, halt_execution=False) #

Only let a command run in a channel that's marked as sfw.

PARAMETER DESCRIPTION
command

The command to add this check to.

TYPE: tanjun.abc.ExecutableCommand | None DEFAULT: None

error

Callback used to create a custom error to raise if the check fails.

This takes priority over error_message.

TYPE: typing.Optional[collections.Callable[[], Exception]] DEFAULT: None

error_message

The error message to send in response as a command error if the check fails.

Setting this to None will disable the error message allowing the command search to continue.

TYPE: typing.Optional[str] DEFAULT: 'Command can only be used in SFW channels'

follow_wrapped

Whether to also add this check to any other command objects this command wraps in a decorator call chain.

TYPE: bool DEFAULT: False

halt_execution

Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False.

This takes priority over error_message.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tanjun.abc.ExecutableCommand

The command this check was added to.

with_str_slash_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a string option to a slash command.

For more information on this function's parameters see tanjun.commands.SlashCommand.add_str_option.

Examples:

@with_str_slash_option("name", "A name.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, name: str) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.

with_user_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True) #

Add a user option to a slash command.

For information on this function's parameters see tanjun.SlashCommand.add_user_option.

Note

This may result in hikari.interactions.base_interactions.InteractionMember or hikari.users.User if the user isn't in the current guild or if this command was executed in a DM channel.

Examples:

@with_user_slash_option("user", "user to target.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, user: Union[InteractionMember, User]) -> None:
    ...
RETURNS DESCRIPTION
collections.abc.Callable[[_SlashCommandT], _SlashCommandT]

Decorator callback which adds the option to the command.