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 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).
#
# `bot_managed=True` has to be explicitly passed here to indicate that the client
# should automatically start when the linked REST bot starts.
client = tanjun.Client.from_rest_bot(bot, bot_managed=True, 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")

# Thanks to `bot_managed=True`, this will also start the client.
bot.run()

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

AnyHooks = Hooks[Context]

Hooks that can be used with any context.

Note

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

MenuHooks module-attribute #

MenuHooks = Hooks[MenuContext]

Hooks that can be used with a menu context.

Note

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

MessageHooks module-attribute #

MessageHooks = Hooks[MessageContext]

Hooks that can be used with a message context.

Note

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

MissingDependencyError module-attribute #

MissingDependencyError = MissingDependencyError

SlashHooks module-attribute #

SlashHooks = Hooks[SlashContext]

Hooks that can be used with a slash context.

Note

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

to_channel module-attribute #

to_channel = ToChannel()

Convert user input to a hikari.PartialChannel object.

to_colour module-attribute #

to_colour = to_color

Convert user input to a hikari.Color object.

to_emoji module-attribute #

to_emoji = ToEmoji()

Convert user input to a cached hikari.KnownCustomEmoji object.

Note

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

to_guild module-attribute #

to_guild = ToGuild()

Convert user input to a hikari.Guild object.

to_invite module-attribute #

to_invite = ToInvite()

Convert user input to a cached hikari.InviteWithMetadata object.

to_invite_with_metadata module-attribute #

to_invite_with_metadata = ToInviteWithMetadata()

Convert user input to a hikari.Invite object.

to_member module-attribute #

to_member = ToMember()

Convert user input to a hikari.Member object.

to_message module-attribute #

to_message = ToMessage()

Convert user input to a hikari.Message object.

to_presence module-attribute #

to_presence = ToPresence()

Convert user input to a cached hikari.MemberPresence.

to_role module-attribute #

to_role = ToRole()

Convert user input to a hikari.Role object.

to_snowflake module-attribute #

to_snowflake = parse_snowflake

Convert user input to a hikari.Snowflake.

Note

This also range validates the input.

to_user module-attribute #

to_user = ToUser()

Convert user input to a hikari.User object.

to_voice_state module-attribute #

to_voice_state = ToVoiceState()

Convert user input to a cached hikari.VoiceState.

BucketResource #

Bases: int, Enum

Resource target types used within command cooldowns and concurrency limiters.

CHANNEL class-attribute instance-attribute #

CHANNEL = 2

A per-channel resource bucket.

GLOBAL class-attribute instance-attribute #

GLOBAL = 7

A global resource bucket.

GUILD class-attribute instance-attribute #

GUILD = 6

A per-guild resource bucket.

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

MEMBER class-attribute instance-attribute #

MEMBER = 1

A per-guild member resource bucket.

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

PARENT_CHANNEL class-attribute instance-attribute #

PARENT_CHANNEL = 3

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 class-attribute instance-attribute #

TOP_ROLE = 5

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 class-attribute instance-attribute #

USER = 0

A per-user resource bucket.

Client #

Bases: 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.

When manually managing the lifetime of the client the linked rest app or bot must always be started before the Tanjun client.

Note

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

checks property #

checks

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

Note

These may be taking advantage of the standard dependency injection.

hooks property #

hooks

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

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

interaction_accepts property #

interaction_accepts

The types of interactions this client is executing.

is_human_only property #

is_human_only

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

menu_hooks property #

menu_hooks

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

These are only called during menu command execution.

message_accepts property #

message_accepts

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

message_hooks property #

message_hooks

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

These are only called during message command execution.

prefix_getter property #

prefix_getter

Prefix getter method set for this client.

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

prefixes property #

prefixes

Collection of the standard prefixes set for this client.

slash_hooks property #

slash_hooks

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

These are only called during slash command execution.

__init__ #

__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 Client.from_gateway_bot and Client.from_rest_bot.

Parameters:

  • rest (RESTClient) –

    The Hikari REST client this will use.

  • cache (Optional[Cache], default: None ) –

    The Hikari cache client this will use if applicable.

  • events (Optional[EventManager], default: None ) –

    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.

  • server (Optional[InteractionServer], default: None ) –

    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.

  • shards (Optional[ShardAware], default: None ) –

    The Hikari shard aware client this will use if applicable.

  • voice (Optional[VoiceComponent], default: None ) –

    The Hikari voice component this will use if applicable.

  • event_managed (bool, default: False ) –

    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.

  • injector (Optional[Client], default: None ) –

    The alluka client this should use for dependency injection.

    If not provided then either the "local" Alluka client will be used or the client will initialise its own DI client.

  • mention_prefix (bool, default: False ) –

    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.

  • declare_global_commands (Union[SnowflakeishSequence[PartialGuild], SnowflakeishOr[PartialGuild], bool], default: False ) –

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

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

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

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

    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.

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

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

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

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

Raises:

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

add_check(*checks)

Add a generic check to this client.

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

Parameters:

  • *checks (AnyCheckSig, default: () ) –

    The checks to add. These 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.

Returns:

  • Self

    The client instance to enable chained calls.

add_component #

add_component(component)

Add a component to this client.

Parameters:

  • component (Component) –

    The component to move to this client.

Returns:

  • Self

    The client instance to allow chained calls.

Raises:

  • ValueError

    If the component's name is already registered.

add_prefix #

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.

Parameters:

  • prefixes (Union[Iterable[str], str]) –

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

Returns:

  • Self

    The client instance to enable chained calls.

close async #

close(*, deregister_listeners=True)

Close the client.

Raises:

fetch_rest_application_id async #

fetch_rest_application_id()

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

Returns:

  • Snowflake

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

from_gateway_bot classmethod #

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)

Build a Client from a gateway bot.

Note

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

Parameters:

  • bot (ShardAware & RESTAware & EventManagerAware) –

    The bot client to build from.

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

  • event_managed (bool, default: True ) –

    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.

  • injector (Optional[Client], default: None ) –

    The alluka client this should use for dependency injection.

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

  • mention_prefix (bool, default: False ) –

    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.

  • declare_global_commands (Union[SnowflakeishSequence[PartialGuild], SnowflakeishOr[PartialGuild], bool], default: False ) –

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

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

    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.

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

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

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

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

from_rest_bot classmethod #

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

Build a Client from a hikari.RESTBotAware instance.

Note

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

Parameters:

  • bot (RESTBotAware) –

    The bot client to build from.

  • declare_global_commands (Union[SnowflakeishSequence[PartialGuild], SnowflakeishOr[PartialGuild], bool], default: False ) –

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

  • bot_managed (bool, default: False ) –

    Whether the client should be managed by the REST bot.

    A REST bot managed client will be automatically started and closed based on the REST bot's startup and shutdown callbacks.

  • injector (Optional[Client], default: None ) –

    The alluka client this should use for dependency injection.

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

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

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

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

    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.

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

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

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

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

on_autocomplete_interaction_request async #

on_autocomplete_interaction_request(interaction)

Execute a command autocomplete based on received REST requests.

Parameters:

Returns:

on_command_interaction_request async #

on_command_interaction_request(interaction)

Execute an app command based on received REST requests.

Parameters:

Returns:

on_gateway_autocomplete_create async #

on_gateway_autocomplete_create(interaction)

Execute command autocomplete based on a received gateway interaction create.

Parameters:

on_gateway_command_create async #

on_gateway_command_create(interaction)

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

Parameters:

on_interaction_create_event async #

on_interaction_create_event(event)

Handle a gateway interaction create event.

This will execute both application command and autocomplete interactions.

Parameters:

on_message_create_event async #

on_message_create_event(event)

Execute a message command based on a gateway event.

Parameters:

open async #

open(*, register_listeners=True)

Start the client.

If mention_prefix was passed to Client.__init__ or 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:

remove_check #

remove_check(check)

Remove a check from the client.

Parameters:

Raises:

  • ValueError

    If the check was not previously added.

remove_prefix #

remove_prefix(prefix)

Remove a message content prefix from the client.

Parameters:

  • prefix (str) –

    The prefix to remove.

Raises:

  • ValueError

    If the prefix is not registered with the client.

Returns:

  • Self

    The client instance to enable chained calls.

set_auto_defer_after #

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.

Parameters:

  • time (Optional[float]) –

    The time in seconds to defer interaction command responses after.

set_autocomplete_ctx_maker #

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.AutocompleteContext rather than just any implementation of the AutocompleteContext abc due to this client relying on implementation detail of tanjun.AutocompleteContext.

Parameters:

Returns:

  • Self

    This client to enable method chaining.

set_case_sensitive #

set_case_sensitive(state)

Set whether this client defaults to being case sensitive for message commands.

Parameters:

  • state (bool) –

    Whether this client's message commands should be matched case-sensitively.

    This may be overridden by component specific configuration.

set_default_app_command_permissions #

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.

Parameters:

Returns:

  • Self

    This client to enable method chaining.

set_dms_enabled_for_app_cmds #

set_dms_enabled_for_app_cmds(state)

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

Parameters:

Returns:

  • Self

    This client to enable method chaining.

set_ephemeral_default #

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.

Parameters:

  • state (bool) –

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

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

Returns:

  • Self

    This client to enable method chaining.

set_global_commands async #

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

Alias of Client.declare_global_commands.

deprecated

Since v2.1.1a1; use Client.declare_global_commands instead.

set_hikari_trait_injectors #

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 Client.set_type_dependency for all the hikari trait types bot is valid for with bot.

Parameters:

  • bot (RESTAware) –

    The hikari client to set dependency injectors for.

set_hooks #

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.

Parameters:

  • hooks (Optional[AnyHooks]) –

    The general command execution hooks to set for this client.

    Passing None will remove all hooks.

Returns:

  • Self

    The client instance to enable chained calls.

set_human_only #

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

Parameters:

  • value (bool, default: True ) –

    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.

set_interaction_accepts #

set_interaction_accepts(accepts)

Set the kind of interactions this client should execute.

Parameters:

Raises:

set_interaction_not_found #

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.

Parameters:

  • message (Optional[str]) –

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

set_menu_ctx_maker #

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.MenuContext rather than just any implementation of the MenuContext abc due to this client relying on implementation detail of tanjun.MenuContext.

Parameters:

Returns:

  • Self

    This client to enable method chaining.

set_menu_hooks #

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.

Parameters:

  • hooks (Optional[MenuHooks]) –

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

    Passing None will remove the hooks.

Returns:

  • Self

    The client instance to enable chained calls.

set_menu_not_found #

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.

Parameters:

  • message (Optional[str]) –

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

set_message_accepts #

set_message_accepts(accepts)

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

Parameters:

  • accepts (MessageAcceptsEnum) –

    The type of messages commands should be executed based on.

Raises:

set_message_ctx_maker #

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.MessageContext rather than just any implementation of the MessageContext abc due to this client relying on implementation detail of tanjun.MessageContext.

Parameters:

Returns:

  • Self

    This client to enable method chaining.

set_message_hooks #

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.

Parameters:

  • hooks (Optional[MessageHooks]) –

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

    Passing None will remove all hooks.

Returns:

  • Self

    The client instance to enable chained calls.

set_prefix_getter #

set_prefix_getter(getter)

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

Parameters:

  • getter (Optional[PrefixGetterSig]) –

    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.

Returns:

  • Self

    The client instance to enable chained calls.

set_slash_ctx_maker #

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.SlashContext rather than just any implementation of the SlashContext abc due to this client relying on implementation detail of tanjun.SlashContext.

Parameters:

Returns:

  • Self

    This client to enable method chaining.

set_slash_hooks #

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.

Parameters:

  • hooks (Optional[SlashHooks]) –

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

    Passing None will remove the hooks.

Returns:

  • Self

    The client instance to enable chained calls.

set_slash_not_found #

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.

Parameters:

  • message (Optional[str]) –

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

with_check #

with_check(check)

Add a check to this client through a decorator call.

Parameters:

  • check (CheckSig) –

    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.

Returns:

  • CheckSig

    The added check.

with_prefix_getter #

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

Parameters:

  • getter (PrefixGetterSig) –

    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.

Returns:

ClientCallbackNames #

Bases: str, Enum

Enum of the standard client callback names.

These should be dispatched by all Client implementations.

CLOSED class-attribute instance-attribute #

CLOSED = 'closed'

Called when the client has finished closing.

No positional arguments are provided for this event.

CLOSING class-attribute instance-attribute #

CLOSING = 'closing'

Called when the client is initially instructed to close.

No positional arguments are provided for this event.

COMPONENT_ADDED class-attribute instance-attribute #

COMPONENT_ADDED = 'component_added'

Called when a component is added to an active client.

Warning

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

The first positional argument is the Component being added.

COMPONENT_REMOVED class-attribute instance-attribute #

COMPONENT_REMOVED = 'component_removed'

Called when a component is added to an active client.

Warning

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

The first positional argument is the Component being removed.

MENU_COMMAND_NOT_FOUND class-attribute instance-attribute #

MENU_COMMAND_NOT_FOUND = 'menu_command_not_found'

Called when a menu command is not found.

MenuContext is provided as the first positional argument.

MESSAGE_COMMAND_NOT_FOUND class-attribute instance-attribute #

MESSAGE_COMMAND_NOT_FOUND = 'message_command_not_found'

Called when a message command is not found.

MessageContext is provided as the first positional argument.

SLASH_COMMAND_NOT_FOUND class-attribute instance-attribute #

SLASH_COMMAND_NOT_FOUND = 'slash_command_not_found'

Called when a slash command is not found.

SlashContext is provided as the first positional argument.

STARTED class-attribute instance-attribute #

STARTED = 'started'

Called when the client has finished starting.

No positional arguments are provided for this event.

STARTING class-attribute instance-attribute #

STARTING = 'starting'

Called when the client is initially instructed to start.

No positional arguments are provided for this event.

CommandError #

Bases: TanjunError

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

attachments instance-attribute #

attachments = [attachment] if attachment else attachments

Sequence of the attachments to be sent as a response to the command, if set.

components instance-attribute #

components = [component] if component else components

Sequence of the components to be sent as a response to the command, if set.

content instance-attribute #

content = content

The response error message's content.

delete_after instance-attribute #

delete_after = delete_after

The seconds after which the response message should be deleted, if set.

embeds instance-attribute #

embeds = [embed] if embed else embeds

Sequence of the embeds to be sent as a response to the command, if set.

mentions_everyone instance-attribute #

mentions_everyone = mentions_everyone

Whether or not the response should be allowed to mention @everyone/@here.

role_mentions instance-attribute #

role_mentions = role_mentions

Configuration for the response's allowed role mentions.

If this is a sequence then the response will only be allowed to mention roles in the sequence.

If this is a bool then the response will only be allowed to mention roles if the value is True.

user_mentions instance-attribute #

user_mentions = user_mentions

Configuration for the response's allowed user mentions.

If this is a sequence then the response will only be allowed to mention users in the sequence.

If this is a bool then the response will only be allowed to mention users if the value is True.

__init__ #

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

Parameters:

Raises:

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

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

Send this error as a command response.

Parameters:

  • ctx (Context) –

    The command call context to respond to.

  • ensure_result (bool, default: False ) –

    Ensure that this call will always return a message object.

    If True then this will always return hikari.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.

Raises:

  • ValueError

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

  • BadRequestError

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

  • UnauthorizedError

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

  • ForbiddenError

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

  • NotFoundError

    If the channel is not found.

  • RateLimitTooLongError

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

  • InternalServerError

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

Component #

Bases: 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.

checks property #

checks

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

hooks property #

hooks

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

menu_hooks property #

menu_hooks

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

message_hooks property #

message_hooks

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

schedules property #

schedules

Collection of the schedules registered to this component.

slash_hooks property #

slash_hooks

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

__init__ #

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

Initialise a new component.

Parameters:

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

    The component's identifier.

    If not provided then this will be a random string.

  • strict (bool, default: False ) –

    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.

add_check #

add_check(*checks)

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

Parameters:

  • *checks (AnyCheckSig, default: () ) –

    The checks to add.

Returns:

  • Self

    This component to enable method chaining.

add_client_callback #

add_client_callback(name, /, *callbacks)

Add a client callback.

Parameters:

  • name (Union[str, ClientCallbackNames]) –

    The name this callback is being registered to.

    This is case-insensitive.

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

    The callbacks to register.

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

Returns:

  • Self

    The client instance to enable chained calls.

add_command #

add_command(command)

Add a command to this component.

Parameters:

Returns:

  • Self

    The current component to allow for chaining.

add_message_command #

add_message_command(command)

Add a message command to the component.

Parameters:

Returns:

  • Self

    The component to allow method chaining.

Raises:

  • ValueError

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

add_on_close #

add_on_close(*callbacks)

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.

Parameters:

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

    The close callbacks to add to this component.

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

Returns:

  • Self

    The component object to enable call chaining.

add_on_open #

add_on_open(*callbacks)

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.

Parameters:

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

    The open callbacks to add to this component.

    These should take no positional arguments, return None and may request injected dependencies.

Returns:

  • Self

    The component object to enable call chaining.

add_schedule #

add_schedule(schedule)

Add a schedule to the component.

Parameters:

Returns:

  • Self

    The component itself for chaining.

get_client_callbacks #

get_client_callbacks(name)

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

Parameters:

Returns:

  • Collection[MetaEventSig]

    Collection of the callbacks for the provided name.

load_from_scope #

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

Parameters:

  • include_globals (bool, default: False ) –

    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.

  • scope (Optional[Mapping[str, Any]], default: None ) –

    The scope to detect entries which implement AbstractComponentLoader from.

    This overrides the default usage of stackframe introspection.

Returns:

  • Self

    The current component to allow for chaining.

Raises:

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

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 Client.load_modules, Client.unload_modules and Client.reload_modules.

Parameters:

  • copy (bool, default: True ) –

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

Returns:

  • ClientLoader

    The loader for this component.

remove_check #

remove_check(check)

Remove a command check from this component.

Parameters:

Returns:

  • Self

    This component to enable method chaining.

Raises:

  • ValueError

    If the check is not registered with this component.

remove_client_callback #

remove_client_callback(name, callback)

Remove a client callback.

Parameters:

  • name (str) –

    The name this callback is being registered to.

    This is case-insensitive.

  • callback (MetaEventSig) –

    The callback to remove from the client's callbacks.

Raises:

  • KeyError

    If the provided name isn't found.

  • ValueError

    If the provided callback isn't found.

Returns:

  • Self

    The client instance to enable chained calls.

remove_command #

remove_command(command)

Remove a command from this component.

Parameters:

Returns:

  • Self

    This component to enable method chaining.

remove_schedule #

remove_schedule(schedule)

Remove a schedule from the component.

Parameters:

Returns:

  • Self

    The component itself for chaining.

Raises:

  • ValueError

    If the schedule isn't registered.

set_case_sensitive #

set_case_sensitive(state)

Set whether this component defaults to being case sensitive for component.

Parameters:

  • state (Optional[bool]) –

    Whether this component's message commands should be matched case-sensitively.

    If this is left as None then the client's case-sensitive setting will be used.

set_default_app_command_permissions #

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.

Parameters:

  • permissions (Union[int, Permissions, None]) –

    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 AppCommand.default_member_permissions and if this is left as None then this config will be inherited from the parent client.

Returns:

  • Self

    This client to enable method chaining.

set_dms_enabled_for_app_cmds #

set_dms_enabled_for_app_cmds(state)

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

Parameters:

  • state (Optional[bool]) –

    Whether to enable this component's commands in DMs.

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

Returns:

  • Self

    This client to enable method chaining.

set_ephemeral_default #

set_ephemeral_default(state)

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

Parameters:

  • state (Optional[bool]) –

    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.

Returns:

  • Self

    This component to enable method chaining.

set_hooks #

set_hooks(hooks)

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

Parameters:

Returns:

  • Self

    This component to enable method chaining.

set_menu_hooks #

set_menu_hooks(hooks)

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

Parameters:

Returns:

  • Self

    This component to enable method chaining.

set_message_hooks #

set_message_hooks(hooks)

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

Parameters:

Returns:

  • Self

    This component to enable method chaining.

set_slash_hooks #

set_slash_hooks(hooks)

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

Parameters:

Returns:

  • Self

    This component to enable method chaining.

with_check #

with_check(check)

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

Parameters:

  • check (CheckSig) –

    The check to add.

Returns:

  • CheckSig

    The added check.

with_client_callback #

with_client_callback(name)

Add a client callback through a decorator call.

Examples:

client = tanjun.Client.from_rest_bot(bot)

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

Parameters:

Returns:

  • Callable[[MetaEventSig], MetaEventSig]

    Decorator callback used to register the client callback.

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

with_command #

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}")

Parameters:

  • command (Optional[_CommandT], default: None ) –

    The command to add to this component.

  • copy (bool, default: False ) –

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

  • follow_wrapped (bool, default: False ) –

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

Returns:

  • ExecutableCommand

    The added command.

with_on_close #

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.

Parameters:

  • callback (OnCallbackSig) –

    The close callback to add to this component.

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

Returns:

with_on_open #

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.

Parameters:

  • callback (OnCallbackSig) –

    The open callback to add to this component.

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

Returns:

with_schedule #

with_schedule(schedule)

Add a schedule to the component through a decorator call.

Example

This may be used in conjunction with tanjun.as_interval or tanjun.as_time_schedule.

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

Parameters:

  • schedule (AbstractSchedule) –

    The schedule to add.

Returns:

  • AbstractSchedule

    The added schedule.

ConversionError #

Bases: ParserError

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

errors instance-attribute #

errors = tuple(errors)

Sequence of the errors that were caught during conversion for this parameter.

message instance-attribute #

message = message

String message for this error.

Note

This may be used as a command response message.

parameter instance-attribute #

parameter

Name of the parameter this error was raised for.

__init__ #

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

Initialise a conversion error.

Parameters:

  • parameter (str) –

    The parameter this was raised by.

  • errors (Iterable[ValueError], default: () ) –

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

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

__cause__ instance-attribute #

__cause__

The root error.

path property #

path

The path of the module which caused the error.

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__ instance-attribute #

__cause__

The root error.

path property #

path

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__ instance-attribute #

__cause__

The root error.

path property #

path

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

__init__()

Initialise a command hook object.

add_to_command #

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!")

Parameters:

  • command (ExecutableCommand) –

    The command to add the hooks to.

Returns:

  • ExecutableCommand

    The command with the hooks added.

copy #

copy()

Copy this hook object.

set_on_error #

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.

Parameters:

  • callback (Optional[ErrorHookSig[_ContextT_contra]]) –

    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.

Returns:

  • Self

    The hook object to enable method chaining.

set_on_parser_error #

set_on_parser_error(callback)

Set the parser error callback for this hook object.

Parameters:

  • callback (Optional[ParserHookSig[_ContextT_contra]]) –

    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.

Returns:

  • Self

    The hook object to enable method chaining.

set_on_success #

set_on_success(callback)

Set the success callback for this hook object.

Parameters:

  • callback (Optional[HookSig[_ContextT_contra]]) –

    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.

Returns:

  • Self

    The hook object to enable method chaining.

set_post_execution #

set_post_execution(callback)

Set the post-execution callback for this hook object.

Parameters:

  • callback (Optional[HookSig[_ContextT_contra]]) –

    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.

Returns:

  • Self

    The hook object to enable method chaining.

set_pre_execution #

set_pre_execution(callback)

Set the pre-execution callback for this hook object.

Parameters:

  • callback (Optional[HookSig[_ContextT_contra]]) –

    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.

Returns:

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

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

Parameters:

  • commands_guild (Optional[SnowflakeishOr[PartialGuild]], default: None ) –

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

  • interval (Union[int, float, timedelta], default: timedelta(microseconds=500000) ) –

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

  • redeclare_cmds_after (Union[int, float, timedelta, None], default: timedelta(seconds=10) ) –

    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.

  • unload_on_delete (bool, default: True ) –

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

add_directory #

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.

Parameters:

  • directory (Union[str, Path]) –

    Path of the directory to hot reload.

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

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

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

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

Returns:

  • Self

    The hot reloader to enable chained calls.

Raises:

add_directory_async async #

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

Asynchronous variant of HotReloader.add_directory.

Unlike 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 HotReloader.add_directory.

add_modules #

add_modules(*paths)

Add modules for this hot reloader to track.

Parameters:

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

    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.

Raises:

add_modules_async async #

add_modules_async(*paths)

Asynchronous variant of HotReloader.add_modules.

Unlike 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 HotReloader.add_modules.

add_to_client #

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.

Parameters:

  • client (Client) –

    The client to link this hot reloader to.

scan async #

scan(client)

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

Parameters:

  • client (Client) –

    The client to reload and unload modules in.

start #

start(client)

Start the hot reloader.

Raises:

stop #

stop()

Stop the hot reloader.

Raises:

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)
    # add_to_client will setup the concurrency manager (setting it as an
    # injected dependency and registering callbacks to manage it).
    .add_to_client(client)
)

acquire #

acquire(bucket_id, ctx, /, *, error=lambda: errors.CommandError('This resource is currently busy; please try again later.'))

Acquire an concurrency lock on a bucket through an async context manager.

Parameters:

  • bucket_id (str) –

    The concurrency bucket to acquire.

  • ctx (Context) –

    The context to acquire this resource lock with.

  • error (Callable[[], Exception], default: lambda: CommandError('This resource is currently busy; please try again later.') ) –

    Callback which returns the error that's raised when the lock couldn't be acquired due to being at it's limit.

    This will be raised on entering the returned context manager and defaults to an English command error.

Returns:

Raises:

  • CommandError

    The default error that's raised while entering the returned async context manager if it couldn't acquire the lock.

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

Parameters:

  • client (Client) –

    The client to add this concurrency manager to.

close #

close()

Stop the concurrency manager.

Raises:

  • RuntimeError

    If the concurrency manager is not running.

disable_bucket #

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.

Parameters:

  • bucket_id (str) –

    The bucket to disable.

Returns:

  • Self

    This concurrency manager to allow for chaining.

open #

open(*, _loop=None)

Start the concurrency manager.

Raises:

  • RuntimeError

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

set_bucket #

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.

Parameters:

  • bucket_id (str) –

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

  • resource (BucketResource) –

    The type of resource to target for the concurrency limit.

  • limit (int) –

    The maximum number of concurrent uses to allow.

Returns:

  • Self

    The concurrency manager to allow call chaining.

Raises:

  • ValueError

    If any of the following cases are met:

    • If an invalid resource is passed.
    • If limit is less 0 or negative.

set_custom_bucket #

set_custom_bucket(resource, /, *bucket_ids)

Set a custom concurrency limit resource.

Parameters:

  • resource (AbstractConcurrencyBucket) –

    Object which handles the concurrency limits for these buckets.

  • bucket_ids (str, default: () ) –

    IDs of buckets to set this custom resource for.

Returns:

  • Self

    The concurrency manager to allow call chaining.

Examples:

class CustomBucket(tanjun.dependencies.AbstractConcurrencyBucket):
    __slots__ = ()

    async def try_acquire(
        self, bucket_id: str, ctx: tanjun.abc.Context, /
    ) -> bool:
        # ResourceDepleted should be raised if this couldn't be acquired.
        raise tanjun.dependencies.ResourceDepleted

    async def release(
        self, bucket_id: str, ctx: tanjun.abc.Context, /
    ) -> None:
        ...

(
    tanjun.dependencies.InMemoryConcurrencyLimiter()
    .set_custom_bucket(CustomBucket(), "BUCKET_ID", "OTHER_BUCKET_ID")
)

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))
    # add_to_client will setup the cooldown manager (setting it as an
    # injected dependency and registering callbacks to manage it).
    .add_to_client(client)
)

acquire #

acquire(bucket_id, ctx, /, error=lambda cooldown: errors.CommandError('This command is currently in cooldown.' + f' Try again {conversion.from_datetime(cooldown, style='R')}.' if cooldown else ''))

Acquire a cooldown lock on a bucket through an async context manager.

Parameters:

  • bucket_id (str) –

    The cooldown bucket to acquire.

  • ctx (Context) –

    The context to acquire this resource lock with.

  • error (Callable[[Optional[datetime]], Exception], default: lambda cooldown: CommandError('This command is currently in cooldown.' + f' Try again {from_datetime(cooldown, style='R')}.' if cooldown else '') ) –

    Callback which returns the error that's raised when the lock couldn't be acquired due to it being on cooldown.

    This will be raised on entering the returned context manager and defaults to an English command error.

Returns:

Raises:

  • CommandError

    The default error that's raised while entering the returned async context manager if it couldn't acquire the lock.

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

Parameters:

  • client (Client) –

    The client to add this cooldown manager to.

close #

close()

Stop the cooldown manager.

Raises:

disable_bucket #

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.

Parameters:

  • bucket_id (str) –

    The bucket to disable.

Returns:

  • Self

    This cooldown manager to allow for chaining.

increment_cooldown async #

increment_cooldown(bucket_id, ctx)

Deprecated function for incrementing a cooldown.

Use AbstractCooldownManager.acquire and AbstractCooldownManager.release.

open #

open(*, _loop=None)

Start the cooldown manager.

Raises:

  • RuntimeError

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

set_bucket #

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.

Parameters:

  • bucket_id (str) –

    The ID of the bucket to set the cooldown for.

  • resource (BucketResource) –

    The type of resource to target for the cooldown.

  • limit (int) –

    The number of uses per cooldown period.

  • reset_after (Union[int, float, timedelta]) –

    The cooldown period.

Returns:

  • Self

    The cooldown manager to allow call chaining.

Raises:

  • ValueError

    If any of the following cases are met:

    • If an invalid resource is passed.
    • If reset_after or limit are negative, 0 or invalid.
    • If limit is less 0 or negative.

set_custom_bucket #

set_custom_bucket(resource, /, *bucket_ids)

Set a custom cooldown limit resource.

Parameters:

  • resource (AbstractCooldownBucket) –

    Object which handles the cooldowns for these buckets.

  • bucket_ids (str, default: () ) –

    IDs of buckets to set this custom resource for.

Returns:

  • Self

    The cooldown manager to allow call chaining.

Examples:

class CustomBucket(tanjun.dependencies.AbstractCooldownBucket):
    __slots__ = ()

    async def try_acquire(
        self, bucket_id: str, ctx: tanjun.abc.Context, /
    ) -> None:
        # CooldownDepleted should be raised if this couldn't be acquired.
        raise tanjun.dependencies.CooldownDepleted(None)

    async def release(
        self, bucket_id: str, ctx: tanjun.abc.Context, /
    ) -> None:
        ...

(
    tanjun.dependencies.InMemoryCooldownManager()
    .set_custom_bucket(CustomBucket(), "BUCKET_ID", "OTHER_BUCKET_ID")
)

InteractionAcceptsEnum #

Bases: IntFlag

The possible configurations for which interaction this client should execute.

ALL class-attribute instance-attribute #

ALL = AUTOCOMPLETE | COMMANDS

Execute all the interaction types Tanjun supports.

AUTOCOMPLETE class-attribute instance-attribute #

AUTOCOMPLETE = auto()

Execute autocomplete interactions.

COMMANDS class-attribute instance-attribute #

COMMANDS = auto()

Execute command interactions.

This includes slash command and context menu calls.

NONE class-attribute instance-attribute #

NONE = 0

Set the client to execute no interactions.

LazyConstant #

Bases: Generic[_T]

Injected type used to hold and generate lazy constants.

Note

To easily resolve this type use inject_lc.

callback property #

callback

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

__init__ #

__init__(callback)

Initiate a new lazy constant.

Parameters:

  • callback (CallbackSig[_T]) –

    Callback used to resolve this to a constant value.

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

acquire #

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:

get_value #

get_value()

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

reset #

reset()

Clear the internally stored value.

set_value #

set_value(value)

Set the constant value.

Parameters:

  • value (_T) –

    The value to set.

Raises:

MenuCommand #

Bases: PartialCommand[MenuContext], MenuCommand[_AnyMenuCallbackSigT, _MenuTypeT]

Base class used for the standard menu command implementations.

wrapped_command property #

wrapped_command

The command object this wraps, if any.

__init__ #

__init__(callback, type_, name, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True, nsfw=False, _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 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.

Parameters:

  • callback (MenuCallbackSig) –

    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_ (CommandType) –

    The type of menu command this is.

    Only CommandType.USER and CommandType.MESSAGE are valid here.

  • name (Union[str, Mapping[str, str]]) –

    The command's name (supports localisation).

    This must be between 1 and 32 characters in length.

  • always_defer (bool, default: False ) –

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

Returns:

Raises:

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

set_ephemeral_default(state)

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

Parameters:

  • state (Optional[bool]) –

    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.

Returns:

  • Self

    This command to allow for chaining.

MessageAcceptsEnum #

Bases: str, Enum

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

ALL class-attribute instance-attribute #

ALL = 'ALL'

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

DM_ONLY class-attribute instance-attribute #

DM_ONLY = 'DM_ONLY'

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

GUILD_ONLY class-attribute instance-attribute #

GUILD_ONLY = 'GUILD_ONLY'

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

NONE class-attribute instance-attribute #

NONE = 'NONE'

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

get_event_type #

get_event_type()

Get the base event type this mode listens to.

Returns:

  • type[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: PartialCommand[MessageContext], MessageCommand[_MessageCallbackSigT]

Standard implementation of a message command.

wrapped_command property #

wrapped_command

The command object this wraps, if any.

__init__ #

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

Initialise a message command.

Parameters:

  • callback (MessageCallbackSig) –

    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.

  • name (str) –

    The command name.

  • *names (str, default: () ) –

    Other names for the command.

  • validate_arg_keys (bool, default: True ) –

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

MessageCommandGroup #

Bases: MessageCommand[_MessageCallbackSigT], MessageCommandGroup[_MessageCallbackSigT]

Standard implementation of a message command group.

wrapped_command property #

wrapped_command

The command object this wraps, if any.

__init__ #

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

Initialise a message command group.

Parameters:

  • callback (MessageCallbackSig) –

    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.

  • name (str) –

    The command name.

  • *names (str, default: () ) –

    Other names for the command.

  • strict (bool, default: False ) –

    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.

  • validate_arg_keys (bool, default: True ) –

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

add_command #

add_command(command)

Add a command to this group.

Parameters:

Returns:

  • Self

    The group instance to enable chained calls.

Raises:

  • ValueError

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

as_sub_command #

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

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

Parameters:

  • name (str) –

    The command name.

  • *names (str, default: () ) –

    Other names for the command.

  • validate_arg_keys (bool, default: True ) –

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

Returns:

as_sub_group #

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

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

Parameters:

  • name (str) –

    The command name.

  • *names (str, default: () ) –

    Other names for the command.

  • strict (bool, default: False ) –

    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.

  • validate_arg_keys (bool, default: True ) –

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

Returns:

ModuleMissingLoaders #

Bases: RuntimeError, TanjunError

Error raised when a module is missing loaders.

message property #

message

The error message.

path property #

path

The path of the module which is missing loaders.

ModuleMissingUnloaders #

Bases: RuntimeError, TanjunError

Error raised when a module is missing unloaders.

message property #

message

The error message.

path property #

path

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 #

message

The error message.

path property #

path

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.

message instance-attribute #

message = message

String message for this error.

Note

This may be used as a command response message.

parameter instance-attribute #

parameter

Name of the parameter this error was raised for.

__init__ #

__init__(message, parameter)

Initialise a not enough arguments error.

Parameters:

  • message (str) –

    The error message.

  • parameter (str) –

    The parameter this error was raised for.

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.

message instance-attribute #

message = message

String message for this error.

Note

This may be used as a command response message.

parameter instance-attribute #

parameter = parameter

Name of the this was raised for.

Note

This will be None if it was raised while parsing the provided message content.

__init__ #

__init__(message, parameter)

Initialise a parser error.

Parameters:

  • message (str) –

    String message for this error.

  • parameter (Optional[str]) –

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

ShlexParser #

Bases: AbstractOptionParser

A shlex based AbstractOptionParser implementation.

__init__ #

__init__()

Initialise a shlex parser.

SlashCommand #

Bases: BaseSlashCommand, SlashCommand[_SlashCallbackSigT]

Standard implementation of a slash command.

wrapped_command property #

wrapped_command

The command object this wraps, if any.

__init__ #

__init__(callback, name, description, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True, nsfw=False, 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 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.

Parameters:

  • callback (SlashCallbackSig) –

    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.

  • name (Union[str, Mapping[str, str]]) –

    The command's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The command's description (supports localisation).

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

  • always_defer (bool, default: False ) –

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

  • sort_options (bool, default: True ) –

    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.

  • validate_arg_keys (bool, default: True ) –

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

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the command name doesn't fit Discord's requirements.
    • If the command name has uppercase characters.
    • If the description is over 100 characters long.

add_attachment_option #

add_attachment_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add an attachment option to the slash command.

Note

This will result in options of type hikari.Attachment.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • pass_as_kwarg (bool, default: True ) –

    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 converters field will be ignored.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

add_bool_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a boolean option to a slash command.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • pass_as_kwarg (bool, default: True ) –

    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.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

add_channel_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, types=None, pass_as_kwarg=True)

Add a channel option to a slash command.

Note

This will always result in hikari.InteractionChannel.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

  • types (Optional[Collection[Union[type[PartialChannel], int]]], default: None ) –

    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.

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

    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.

  • pass_as_kwarg (bool, default: True ) –

    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.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

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

Add a float option to a slash command.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • always_float (bool, default: True ) –

    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.

  • autocomplete (Optional[AutocompleteSig[float]], default: None ) –

    The autocomplete callback for the option.

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

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

    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.

  • converters (Union[Sequence[ConverterSig[float]], ConverterSig[float]], default: () ) –

    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.

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • min_value (Optional[float], default: None ) –

    The option's (inclusive) minimum value.

  • max_value (Optional[float], default: None ) –

    The option's (inclusive) maximum value.

  • pass_as_kwarg (bool, default: True ) –

    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 converters, and always_float will be ignored.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

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

Add an integer option to the slash command.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • autocomplete (Optional[AutocompleteSig[int]], default: None ) –

    The autocomplete callback for the option.

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

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

    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.

  • converters (Union[Sequence[ConverterSig[int]], ConverterSig[int]], default: () ) –

    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.

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

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

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • min_value (Optional[int], default: None ) –

    The option's (inclusive) minimum value.

  • max_value (Optional[int], default: None ) –

    The option's (inclusive) maximum value.

  • pass_as_kwarg (bool, default: True ) –

    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 converters field will be ignored.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

add_member_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None)

Add a member option to a slash command.

Note

This will always result in hikari.InteractionMember.

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.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

add_mentionable_option(name, description, /, *, default=tanjun.NO_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.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • pass_as_kwarg (bool, default: True ) –

    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.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

add_role_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a role option to a slash command.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • pass_as_kwarg (bool, default: True ) –

    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.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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 #

add_str_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=tanjun.NO_DEFAULT, key=None, min_length=None, max_length=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).

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

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

    The autocomplete callback for the option.

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

  • choices ((Mapping[str, str], Sequence[str] | None), default: None ) –

    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.

    Passing a sequence of tuples here is deprecated.

  • converters (Union[Sequence[ConverterSig[str]], ConverterSig[str]], default: () ) –

    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.

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • min_length (Optional[int], default: None ) –

    The minimum length of this string.

    This must be greater than or equal to 0, and less than or equal to max_length and 6000.

  • max_length (Optional[int], default: None ) –

    The maximum length of this string.

    This must be greater then or equal to min_length and 1, and less than or equal to 6000.

  • pass_as_kwarg (bool, default: True ) –

    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 converters field will be ignored.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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.
    • If min_length is greater than max_length.
    • If min_length is less than 0 or greater than 6000.
    • If max_length is less than 1 or greater than 6000.

add_user_option #

add_user_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a user option to a slash command.

Note

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

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The option's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The option's description (supports localisation).

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

  • default (Any, default: NO_DEFAULT ) –

    The option's default value.

    If this is left as no default then this option will be required.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

    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.

  • pass_as_kwarg (bool, default: True ) –

    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.

Returns:

  • Self

    The command object for chaining.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the option name doesn't fit Discord's requirements.
    • 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_ephemeral_default #

set_ephemeral_default(state)

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

Parameters:

  • state (Optional[bool]) –

    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.

Returns:

  • Self

    This command to allow for chaining.

set_float_autocomplete #

set_float_autocomplete(name, callback)

Set the autocomplete callback for a float option.

Parameters:

  • name (str) –

    The option's name.

    If localised names were provided for the option then this should be the default name.

  • callback (Optional[AutocompleteSig[float]]) –

    The autocomplete callback for the option.

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

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

Returns:

  • Self

    The command object for chaining.

Raises:

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

set_int_autocomplete(name, callback)

Set the autocomplete callback for a string option.

Parameters:

  • name (str) –

    The option's name.

    If localised names were provided for the option then this should be the default name.

  • callback (AutocompleteSig[int]) –

    The autocomplete callback for the option.

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

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

Returns:

  • Self

    The command object for chaining.

Raises:

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

set_str_autocomplete(name, callback)

Set the autocomplete callback for a str option.

Parameters:

  • name (str) –

    The option's name.

    If localised names were provided for the option then this should be the default name.

  • callback (AutocompleteSig[str]) –

    The autocomplete callback for the option.

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

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

Returns:

  • Self

    The command object for chaining.

Raises:

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

with_float_autocomplete(name)

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

Parameters:

  • name (str) –

    The option's name.

    If localised names were provided for the option then this should be the default name.

Returns:

  • Callable[[AutocompleteSig[float]], AutocompleteSig[float]]

    Decorator callback used to capture the autocomplete callback.

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

Raises:

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

with_int_autocomplete(name)

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

Parameters:

  • name (str) –

    The option's name.

    If localised names were provided for the option then this should be the default name.

Returns:

  • Callable[[AutocompleteSig[int]], AutocompleteSig[int]]

    Decorator callback used to capture the autocomplete callback.

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

Raises:

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

with_str_autocomplete(name)

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

Parameters:

  • name (str) –

    The option's name.

    If localised names were provided for the option then this should be the default name.

Returns:

  • Callable[[AutocompleteSig[str]], AutocompleteSig[str]]

    Decorator callback used to capture the autocomplete callback.

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

Raises:

  • KeyError

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

  • TypeError

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

SlashCommandGroup #

Bases: BaseSlashCommand, SlashCommandGroup

Standard implementation of a slash command group.

Note

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

__init__ #

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

Initialise a slash command group.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by 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.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The name of the command group (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The description of the command group (supports localisation).

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the command name doesn't fit Discord's requirements.
    • If the command name has uppercase characters.
    • If the description is over 100 characters long.

add_command #

add_command(command)

Add a slash command to this group.

Warning

Command groups are only supported within top-level groups.

Parameters:

Returns:

  • Self

    Object of this group to enable chained calls.

as_sub_command #

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

Build a 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.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The command's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

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

  • always_defer (bool, default: False ) –

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

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

    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.

  • sort_options (bool, default: True ) –

    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.

  • validate_arg_keys (bool, default: True ) –

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

Returns:

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the command name doesn't fit Discord's requirements.
    • If the command name has uppercase characters.
    • If the description is over 100 characters long.

make_sub_group #

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.

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The name of the command group (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The description of the command group.

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

    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.

Returns:

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the command name doesn't fit Discord's requirements.
    • If the command name has uppercase characters.
    • If the description is over 100 characters long.

remove_command #

remove_command(command)

Remove a command from this group.

Parameters:

Returns:

  • Self

    Object of this group to enable chained calls.

set_ephemeral_default #

set_ephemeral_default(state)

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

Parameters:

  • state (Optional[bool]) –

    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.

Returns:

  • Self

    This command to allow for chaining.

with_command #

with_command(command)

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

Parameters:

  • command (BaseSlashCommand) –

    Command to add to this group.

Returns:

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

message instance-attribute #

message = message

String message for this error.

Note

This may be used as a command response message.

parameter instance-attribute #

parameter

Name of the parameter this error was raised for.

__init__ #

__init__(message, parameter)

Initialise a too many arguments error.

Parameters:

  • message (str) –

    The error message.

  • parameter (str) –

    The parameter this error was raised for.

as_interval #

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

Decorator to create an schedule.

Examples:

@component.with_schedule
@tanjun.as_interval(datetime.timedelta(minutes=5))  # This will run every 5 minutes
async def interval(client: alluka.Injected[tanjun.abc.Client]) -> None:
    ...

This should be loaded into a component using either Component.with_schedule or Component.load_from_scope, and will be started and stopped with the linked tanjun client.

Parameters:

  • interval (Union[int, float, timedelta]) –

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

  • fatal_exceptions (Sequence[type[Exception]], default: () ) –

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

  • ignored_exceptions (Sequence[type[Exception]], default: () ) –

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

  • max_runs (Optional[int], default: None ) –

    The maximum amount of times the schedule runs.

Returns:

  • Callable[[_CallbackSigT], 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 #

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

Parameters:

  • callback (Union[Callable[[Client], None], Callable[[Client], None], None], default: None ) –

    The callback used to load Tanjun components from a module.

    This should take one argument of type 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.

  • standard_impl (bool, default: True ) –

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

Returns:

  • collections.abc.Callable[[tanjun.abc.Client], None]]

    The decorated load callback.

as_message_command #

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

Build a message command from a decorated callback.

Parameters:

  • name (str) –

    The command name.

  • *names (str, default: () ) –

    Other names for the command.

  • validate_arg_keys (bool, default: True ) –

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

Returns:

as_message_command_group #

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

Build a message command group from a decorated callback.

Parameters:

  • name (str) –

    The command name.

  • *names (str, default: () ) –

    Other names for the command.

  • strict (bool, default: False ) –

    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.

  • validate_arg_keys (bool, default: True ) –

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

Returns:

as_message_menu #

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

Build a message MenuCommand by decorating a function.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by 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")
    )

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The command's name (supports localisation).

    This must be between 1 and 32 characters in length.

  • always_defer (bool, default: False ) –

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

Returns:

Raises:

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

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

Parameters:

  • client (Client) –

    The client to use to resolve dependencies.

Returns:

as_slash_command #

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

Build a SlashCommand by decorating a function.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by 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")

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The command's name (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The command's description (supports localisation).

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

  • always_defer (bool, default: False ) –

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

  • sort_options (bool, default: True ) –

    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.

  • validate_arg_keys (bool, default: True ) –

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

Returns:

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the command name doesn't fit Discord's requirements.
    • If the command name has uppercase characters.
    • If the description is over 100 characters long.

as_time_schedule #

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.

Examples:

@component.with_schedule
@tanjun.as_time_schedule(  # This will run every week day at 8:00 and 16:00 UTC.
    minutes=0, hours=[8, 16], days=range(0, 5), weekly=True, timezone=datetime.timezone.utc
)
async def interval(client: alluka.Injected[tanjun.abc.Client]) -> None:
    ...

This should be loaded into a component using either Component.with_schedule or Component.load_from_scope, and will be started and stopped with the linked tanjun client.

Parameters:

  • months (Union[int, Sequence[int]], default: () ) –

    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.

  • weekly (bool, default: False ) –

    Whether the schedule should run on a weekly basis.

  • days (Union[int, Sequence[int]], default: () ) –

    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 run on all days.

  • hours (Union[int, Sequence[int]], default: () ) –

    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.

  • minutes (Union[int, Sequence[int]], default: () ) –

    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.

  • seconds (Union[int, Sequence[int]], default: 0 ) –

    Either one or multiple seconds the schedule should run on.

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

  • fatal_exceptions (Sequence[type[Exception]], default: () ) –

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

  • ignored_exceptions (Sequence[type[Exception]], default: () ) –

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

  • timezone (Optional[timezone], default: None ) –

    The timezone to use for the schedule.

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

Returns:

  • Callable[[_CallbackSigT], 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:

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

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 as_loader and is only necessary if you wish to use the Client.unload_modules or Client.reload_modules.

Parameters:

  • callback (Union[Callable[[Client], None], Callable[[Client], None], None], default: None ) –

    The callback used to unload Tanjun components from a module.

    This should take one argument of type 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.

  • standard_impl (bool, default: True ) –

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

Returns:

  • collections.abc.Callable[[tanjun.abc.Client], None]]

    The decorated unload callback.

as_user_menu #

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

Build a user MenuCommand by decorating a function.

Note

Under the standard implementation, is_global is used to determine whether the command should be bulk set by 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}")

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The command's name (supports localisation).

    This must be between 1 and 32 characters in length.

  • always_defer (bool, default: False ) –

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

Returns:

Raises:

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

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

Parameters:

  • callback (CallbackSig[_T]) –

    The callback to inject.

  • expire_after (Union[float, int, timedelta, None], default: None ) –

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

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

Returns:

Raises:

  • ValueError

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

inject_lc #

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

Parameters:

  • type_ (type[_T]) –

    The type of the constant to resolve.

Returns:

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 #

slash_command_group(name, description, /, *, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, nsfw=False, 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 Client.declare_global_commands 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")

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

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

component = tanjun.Component().add_slash_command(help_group)

Parameters:

  • name (Union[str, Mapping[str, str]]) –

    The name of the command group (supports localisation).

    This must fit discord's requirements.

  • description (Union[str, Mapping[str, str]]) –

    The description of the command group (supports localisation).

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

  • default_member_permissions (Union[Permissions, int, None], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (Optional[bool], default: None ) –

    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 (bool, default: True ) –

    Whether this command is a global command.

  • nsfw (bool, default: False ) –

    Whether this command should only be accessible in channels marked as nsfw.

Returns:

Raises:

  • ValueError

    Raises a value error for any of the following reasons:

    • If the command name doesn't fit Discord's requirements.
    • If the command name has uppercase characters.
    • If the description is over 100 characters long.

to_bool #

to_bool(value)

Convert user string input into a boolean value.

Parameters:

  • value (str) –

    The value to convert.

Returns:

  • bool

    The converted value.

Raises:

  • ValueError

    If the value cannot be converted.

to_color #

to_color(argument)

Convert user input to a hikari.Color object.

to_datetime #

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

Parameters:

  • value (str) –

    The value to parse.

Returns:

Raises:

with_all_checks #

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.

Parameters:

  • check (CheckSig[Any]) –

    The first check callback to combine.

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

    Additional check callbacks to combine.

  • follow_wrapped (bool, default: False ) –

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

Returns:

  • Callable[[Context], Coroutine[Any, Any, bool]]

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

with_any_checks #

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.

Parameters:

  • check (CheckSig[Any]) –

    The first check callback to combine.

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

    Additional check callbacks to combine.

  • error (Optional[Callable[[], Exception]], default: None ) –

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

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None]) –

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

    This supports localisation and uses the check name "tanjun.any_check" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

  • suppress (tuple[type[Exception], ...], default: (CommandError, HaltExecution) ) –

    Tuple of the exceptions to suppress when a check fails.

Returns:

  • Callable[[ExecutableCommand], ExecutableCommand]

    A decorator which adds the generated check to a command.

with_argument #

with_argument(key, /, converters=(), *, default=tanjun.NO_DEFAULT, greedy=False, min_length=None, max_length=None, min_value=None, max_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):
    ...

Parameters:

  • key (str) –

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

  • converters (_MaybeIterable[ConverterSig[Any]], default: () ) –

    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.

  • default (Any, default: NO_DEFAULT ) –

    The default value of this argument, if left as tanjun.abc.NO_DEFAULT then this will have no default.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

  • greedy (bool, default: False ) –

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

  • min_length (Optional[int], default: None ) –

    Assert that a string argument's length is greater than or equal to this.

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

  • max_length (Optional[int], default: None ) –

    Assert that a string argument's length is less than or equal to this.

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

  • min_value (Optional[Any], default: None ) –

    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.

  • max_value (Optional[Any], default: None ) –

    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.

  • multi (bool, default: False ) –

    Whether this argument can be passed multiple times.

Returns:

  • collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]:

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

Raises:

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

with_attachment_slash_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add an attachment option to a slash command.

For more information on this function's parameters see 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:

with_author_permission_check #

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)

Parameters:

  • permissions (Union[Permissions, int]) –

    The permission(s) required for this command to run.

  • error (Optional[Callable[[Permissions], Exception]], default: None ) –

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

    This should take 1 positional argument of type hikari.Permissions which represents the missing permissions required for this command to run.

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: "You don't have the permissions required to use this command" ) –

    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.

    This supports localisation and uses the check name "tanjun.AuthorPermissionCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • Callable[[ExecutableCommand], ExecutableCommand]

    A command decorator callback which adds the check.

with_bool_slash_option #

with_bool_slash_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a boolean option to a slash command.

For information on this function's parameters see 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:

with_channel_slash_option #

with_channel_slash_option(name, description, /, *, types=None, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a channel option to a slash command.

For information on this function's parameters see SlashCommand.add_channel_option.

Note

This will always result in hikari.InteractionChannel.

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:

with_check #

with_check(check, /, *, follow_wrapped=False)

Add a generic check to a command.

Parameters:

  • check (CheckSig[Any]) –

    The check to add to this command.

  • follow_wrapped (bool, default: False ) –

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

Returns:

  • Callable[[ExecutableCommand], ExecutableCommand]

    A command decorator callback which adds the check.

with_concurrency_limit #

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.

Parameters:

  • bucket_id (str) –

    The concurrency limit bucket's ID.

  • error (Optional[Callable[[str], Exception]], default: None ) –

    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.

  • error_message (Union[str, Mapping[str, str]], default: 'This resource is currently busy; please try again later.' ) –

    The error message to send in response as a command error if this fails to acquire the concurrency limit.

    This supports localisation and uses the check name "tanjun.concurrency" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

Returns:

  • Callable[[ExecutableCommand], ExecutableCommand]

    A decorator which adds the concurrency limiter hooks to a command.

with_cooldown #

with_cooldown(bucket_id, /, *, error=None, error_message='This command is currently in cooldown. Try again {cooldown}.', unknown_message=None, 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.

Parameters:

  • bucket_id (str) –

    The cooldown bucket's ID.

  • error (Optional[Callable[[str, Optional[datetime]], Exception]], default: None ) –

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

    This should two arguments one of type str and datetime.datetime | None where the first is the limiting bucket's ID and the second is when said bucket can be used again if known.

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str]], default: 'This command is currently in cooldown. Try again {cooldown}.' ) –

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

    This supports localisation and uses the check name "tanjun.cooldown" for global overrides.

  • unknown_message (Union[str, Mapping[str, str], None], default: None ) –

    Response error message for when cooldown is unknown.

    This supports localisation and uses the check name "tanjun.cooldown_unknown" for global overrides.

    This defaults to error_message but takes no format args.

  • follow_wrapped (bool, default: False ) –

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

  • owners_exempt (bool, default: True ) –

    Whether owners should be exempt from the cooldown.

Returns:

  • Callable[[ExecutableCommand], ExecutableCommand]

    A decorator which adds the relevant cooldown hooks.

with_dm_check #

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.

Parameters:

  • command (ExecutableCommand | None, default: None ) –

    The command to add this check to.

  • error (Optional[Callable[[], Exception]], default: None ) –

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

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: 'Command can only be used in DMs' ) –

    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.

    This supports localisation and uses the check name "tanjun.DmCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • ExecutableCommand

    The command this check was added to.

with_float_slash_option #

with_float_slash_option(name, description, /, *, always_float=True, autocomplete=None, choices=None, converters=(), default=tanjun.NO_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 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:

with_greedy_argument #

with_greedy_argument(key, /, converters=(), *, default=tanjun.NO_DEFAULT, min_length=None, max_length=None, min_value=None, max_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):
    ...

Parameters:

  • key (str) –

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

  • converters (_MaybeIterable[ConverterSig[Any]], default: () ) –

    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.

  • default (Any, default: NO_DEFAULT ) –

    The default value of this argument, if left as tanjun.abc.NO_DEFAULT then this will have no default.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

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

  • min_length (Optional[int], default: None ) –

    Assert that a string argument's length is greater than or equal to this.

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

  • max_length (Optional[int], default: None ) –

    Assert that a string argument's length is less than or equal to this.

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

  • min_value (Optional[Any], default: None ) –

    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.

  • max_value (Optional[Any], default: None ) –

    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.

Returns:

  • collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]:

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

Raises:

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

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.

Parameters:

  • command (ExecutableCommand | None, default: None ) –

    The command to add this check to.

  • error (Optional[Callable[[], Exception]], default: None ) –

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

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: 'Command can only be used in guild channels' ) –

    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.

    This supports localisation and uses the check name "tanjun.GuildCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • ExecutableCommand

    The command this check was added to.

with_int_slash_option #

with_int_slash_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=tanjun.NO_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 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:

with_member_slash_option #

with_member_slash_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None)

Add a member option to a slash command.

For information on this function's arguments see SlashCommand.add_member_option.

Note

This will always result in hikari.InteractionMember.

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:

with_mentionable_slash_option #

with_mentionable_slash_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a mentionable option to a slash command.

For information on this function's arguments see 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:

with_multi_argument #

with_multi_argument(key, /, converters=(), *, default=tanjun.NO_DEFAULT, min_length=None, max_length=None, min_value=None, max_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]):
    ...

Parameters:

  • key (str) –

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

  • converters (_MaybeIterable[ConverterSig[Any]], default: () ) –

    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.

  • default (Any, default: NO_DEFAULT ) –

    The default value of this argument, if left as tanjun.abc.NO_DEFAULT then this will have no default.

    If this is tanjun.abc.NO_PASS then the key parameter won't be passed when no value was provided.

  • min_length (Optional[int], default: None ) –

    Assert that a string argument's length is greater than or equal to this.

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

  • max_length (Optional[int], default: None ) –

    Assert that a string argument's length is less than or equal to this.

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

  • min_value (Optional[Any], default: None ) –

    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.

  • max_value (Optional[Any], default: None ) –

    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.

Returns:

  • collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]:

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

Raises:

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

with_multi_option(key, name, /, *names, converters=(), default, empty_value=tanjun.NO_DEFAULT, min_length=None, max_length=None, min_value=None, max_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]):
    ...

Parameters:

  • key (str) –

    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.

  • name (str) –

    The name of this option used for identifying it in the parsed content.

  • *names (str, default: () ) –

    Other names of this option used for identifying it in the parsed content.

  • default (Any) –

    The default value of this argument, unlike arguments this is required for options.

  • converters (_MaybeIterable[ConverterSig[Any]], default: () ) –

    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.

  • empty_value (Any, default: NO_DEFAULT ) –

    The value to use if this option is provided without a value.

    If left as tanjun.abc.NO_DEFAULT then this option will error if it's provided without a value.

    tanjun.abc.NO_PASS is not supported for this.

  • min_length (Optional[int], default: None ) –

    Assert that a string argument's length is greater than or equal to this.

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

  • max_length (Optional[int], default: None ) –

    Assert that a string argument's length is less than or equal to this.

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

  • min_value (Optional[Any], default: None ) –

    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.

  • max_value (Optional[Any], default: None ) –

    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.

Returns:

  • collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]:

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

Raises:

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

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.

Parameters:

  • command (ExecutableCommand | None, default: None ) –

    The command to add this check to.

  • error (Optional[Callable[[], Exception]], default: None ) –

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

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: 'Command can only be used in NSFW channels' ) –

    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.

    This supports localisation and uses the check name "tanjun.NsfwCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • ExecutableCommand

    The command this check was added to.

with_option #

with_option(key, name, /, *names, converters=(), default, empty_value=tanjun.NO_DEFAULT, min_length=None, max_length=None, min_value=None, max_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):
    ...

Parameters:

  • key (str) –

    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.

  • name (str) –

    The name of this option used for identifying it in the parsed content.

  • *names (str, default: () ) –

    Other names of this option used for identifying it in the parsed content.

  • default (Any) –

    The default value of this argument, unlike arguments this is required for options.

  • converters (_MaybeIterable[ConverterSig[Any]], default: () ) –

    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.

  • empty_value (Any, default: NO_DEFAULT ) –

    The value to use if this option is provided without a value.

    If left as tanjun.abc.NO_DEFAULT then this option will error if it's provided without a value.

    tanjun.abc.NO_PASS is not supported for this.

  • min_length (Optional[int], default: None ) –

    Assert that a string argument's length is greater than or equal to this.

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

  • max_length (Optional[int], default: None ) –

    Assert that a string argument's length is less than or equal to this.

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

  • min_value (Optional[Any], default: None ) –

    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.

  • max_value (Optional[Any], default: None ) –

    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.

  • multi (bool, default: False ) –

    If this option can be provided multiple times.

Returns:

  • collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]:

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

Raises:

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

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)

Parameters:

  • permissions (Union[Permissions, int]) –

    The permission(s) required for this command to run.

  • error (Optional[Callable[[Permissions], Exception]], default: None ) –

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

    This should take 1 positional argument of type hikari.Permissions which represents the missing permissions required for this command to run.

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: "Bot doesn't have the permissions required to run this command" ) –

    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.

    This supports localisation and uses the check name "tanjun.OwnPermissionCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • Callable[[ExecutableCommand], ExecutableCommand]

    A command decorator callback which adds the check.

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

Parameters:

  • command (ExecutableCommand | None, default: None ) –

    The command to add this check to.

  • error (Optional[Callable[[], Exception]], default: None ) –

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

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: 'Only bot owners can use this command' ) –

    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.

    This supports localisation and uses the check name "tanjun.OwnerCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • ExecutableCommand

    The command this check was added to.

with_parser #

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

Parameters:

  • command (_CommandT) –

    The message command to set the parser on.

Returns:

  • MessageCommand

    The command with the parser set.

Raises:

  • ValueError

    If the command already has a parser set.

with_role_slash_option #

with_role_slash_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a role option to a slash command.

For information on this function's parameters see 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:

with_sfw_check #

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.

Parameters:

  • command (ExecutableCommand | None, default: None ) –

    The command to add this check to.

  • error (Optional[Callable[[], Exception]], default: None ) –

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

    This takes priority over error_message.

  • error_message (Union[str, Mapping[str, str], None], default: 'Command can only be used in SFW channels' ) –

    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.

    This supports localisation and uses the check name "tanjun.SfwCheck" for global overrides.

  • follow_wrapped (bool, default: False ) –

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

  • halt_execution (bool, default: False ) –

    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.

Returns:

  • ExecutableCommand

    The command this check was added to.

with_str_slash_option #

with_str_slash_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=tanjun.NO_DEFAULT, key=None, min_length=None, max_length=None, pass_as_kwarg=True)

Add a string option to a slash command.

For more information on this function's parameters see 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:

with_user_slash_option #

with_user_slash_option(name, description, /, *, default=tanjun.NO_DEFAULT, key=None, pass_as_kwarg=True)

Add a user option to a slash command.

For information on this function's parameters see SlashCommand.add_user_option.

Note

This may result in hikari.InteractionMember or hikari.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: