tanjun#
A flexible command framework designed to extend Hikari.
Examples:
A Tanjun client can be quickly initialised from a Hikari gateway bot through tanjun.Client.from_gateway_bot, this enables both slash (interaction) and message command execution:
bot = hikari.GatewayBot("BOT_TOKEN")
# As a note, unless event_managed=False is passed here then this client
# will be managed based on gateway startup and stopping events.
# mention_prefix=True instructs the client to also set mention prefixes on the
# first startup.
client = tanjun.Client.from_gateway_bot(bot, declare_global_commands=True, mention_prefix=True)
component = tanjun.Component()
client.add_component(component)
# Declare a message command with some basic parser logic.
@component.with_command
@tanjun.with_greedy_argument("name", default="World")
@tanjun.as_message_command("test")
async def test_command(ctx: tanjun.abc.Context, name: str) -> None:
await ctx.respond(f"Hello, {name}!")
# Declare a ping slash command
@component.with_command
@tanjun.with_user_slash_option("user", "The user facing command option's description", default=None)
@tanjun.as_slash_command("hello", "The command's user facing description")
async def hello(ctx: tanjun.abc.Context, user: hikari.User | None) -> None:
user = user or ctx.author
await ctx.respond(f"Hello, {user}!")
Alternatively, the client can also be built from a RESTBot but this will only enable slash (interaction) command execution:
bot = hikari.RESTBot("BOT_TOKEN", "Bot")
# declare_global_commands=True instructs the client to set the global commands
# for the relevant bot on first startup (this will replace any previously
# declared commands).
#
# `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[tanjun.Context]
Hooks that can be used with any context.
Note
This is shorthand for Hooks[tanjun.abc.Context]
.
MenuHooks
module-attribute
#
MenuHooks = Hooks[tanjun.MenuContext]
Hooks that can be used with a menu context.
Note
This is shorthand for Hooks[tanjun.abc.MenuContext]
.
MessageHooks
module-attribute
#
MessageHooks = Hooks[tanjun.MessageContext]
Hooks that can be used with a message context.
Note
This is shorthand for Hooks[tanjun.abc.MessageContext]
.
MissingDependencyError
module-attribute
#
MissingDependencyError = alluka.MissingDependencyError
Type alias of alluka.MissingDependencyError.
SlashHooks
module-attribute
#
SlashHooks = Hooks[tanjun.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: typing.Final[ToChannel] = ToChannel()
Convert user input to a hikari.channels.PartialChannel object.
to_colour
module-attribute
#
to_colour: typing.Final[collections.Callable[[_SnowflakeIsh], hikari.Color]] = to_color
Convert user input to a hikari.colors.Color object.
to_emoji
module-attribute
#
to_emoji: typing.Final[ToEmoji] = ToEmoji()
Convert user input to a cached hikari.emojis.KnownCustomEmoji object.
Note
If you just want to convert input to a hikari.emojis.Emoji, hikari.emojis.CustomEmoji or hikari.emojis.UnicodeEmoji without making any cache or REST calls then you can just use the relevant hikari.emojis.Emoji.parse, hikari.emojis.CustomEmoji.parse or hikari.emojis.UnicodeEmoji.parse methods.
to_guild
module-attribute
#
to_guild: typing.Final[ToGuild] = ToGuild()
Convert user input to a hikari.guilds.Guild object.
to_invite
module-attribute
#
to_invite: typing.Final[ToInvite] = ToInvite()
Convert user input to a cached hikari.invites.InviteWithMetadata object.
to_invite_with_metadata
module-attribute
#
to_invite_with_metadata: typing.Final[ToInviteWithMetadata] = ToInviteWithMetadata()
Convert user input to a hikari.invites.Invite object.
to_member
module-attribute
#
to_member: typing.Final[ToMember] = ToMember()
Convert user input to a hikari.guilds.Member object.
to_message
module-attribute
#
to_message: typing.Final[ToMessage] = ToMessage()
Convert user input to a hikari.messages.Message object.
to_presence
module-attribute
#
to_presence: typing.Final[ToPresence] = ToPresence()
Convert user input to a cached hikari.presences.MemberPresence.
to_role
module-attribute
#
to_role: typing.Final[ToRole] = ToRole()
Convert user input to a hikari.guilds.Role object.
to_snowflake
module-attribute
#
to_snowflake: typing.Final[collections.Callable[[_SnowflakeIsh], hikari.Snowflake]] = parse_snowflake
Convert user input to a hikari.snowflakes.Snowflake.
Note
This also range validates the input.
to_user
module-attribute
#
to_user: typing.Final[ToUser] = ToUser()
Convert user input to a hikari.users.User object.
to_voice_state
module-attribute
#
to_voice_state: typing.Final[ToVoiceState] = ToVoiceState()
Convert user input to a cached hikari.voices.VoiceState.
BucketResource #
Resource target types used within command calldowns and concurrency limiters.
GUILD
class-attribute
#
GUILD = 6
A per-guild resource bucket.
When executed in a DM this will be per-DM.
MEMBER
class-attribute
#
MEMBER = 1
A per-guild member resource bucket.
When executed in a DM this will be per-DM.
PARENT_CHANNEL
class-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
#
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.
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 tanjun.Client.set_hooks.
checks
property
#
checks: collections.Collection[tanjun.AnyCheckSig]
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: typing.Optional[tanjun.AnyHooks]
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: InteractionAcceptsEnum
The types of interactions this client is executing.
is_human_only
property
#
is_human_only: bool
Whether this client is only executing for non-bot/webhook users messages.
menu_hooks
property
#
menu_hooks: typing.Optional[tanjun.MenuHooks]
Top level tanjun.abc.MenuHooks set for this client.
These are only called during menu command execution.
message_accepts
property
#
message_accepts: MessageAcceptsEnum
Type of message create events this command client accepts for execution.
message_hooks
property
#
message_hooks: typing.Optional[tanjun.MessageHooks]
Top level tanjun.abc.MessageHooks set for this client.
These are only called during message command execution.
prefix_getter
property
#
prefix_getter: typing.Optional[PrefixGetterSig]
Prefix getter method set for this client.
For more information on this callback's signature see tanjun.clients.PrefixGetterSig.
prefixes
property
#
prefixes: collections.Collection[str]
Collection of the standard prefixes set for this client.
slash_hooks
property
#
slash_hooks: typing.Optional[tanjun.SlashHooks]
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 tanjun.Client.from_gateway_bot and tanjun.Client.from_rest_bot.
PARAMETER | DESCRIPTION |
---|---|
rest |
The Hikari REST client this will use.
TYPE:
|
cache |
The Hikari cache client this will use if applicable. |
events |
The Hikari event manager client this will use if applicable. This is necessary for message command dispatch and will also
be necessary for interaction command dispatch if
TYPE:
|
server |
The Hikari interaction server client this will use if applicable. This is used for interaction command dispatch if interaction events aren't being received from the event manager.
TYPE:
|
shards |
The Hikari shard aware client this will use if applicable.
TYPE:
|
voice |
The Hikari voice component this will use if applicable.
TYPE:
|
event_managed |
Whether or not this client is managed by the event manager. An event managed client will be automatically started and closed based on Hikari's lifetime events. This can only be passed as True if
TYPE:
|
injector |
The alluka client this should use for dependency injection. If not provided then the client will initialise its own DI client. |
mention_prefix |
Whether or not mention prefixes should be automatically set when this client is first started. It should be noted that this only applies to message commands.
TYPE:
|
declare_global_commands |
Whether or not to automatically set global slash commands when this client is first started. If one or more guild objects/IDs are passed here then the registered global commands will be set on the specified guild(s) at startup rather than globally. The endpoint this uses has a strict ratelimit which, as of writing, only allows for 2 requests per minute (with that ratelimit either being per-guild if targeting a specific guild otherwise globally).
TYPE:
|
set_global_commands |
Deprecated as of v2.1.1a1 alias of
TYPE:
|
command_ids |
If provided, a mapping of top level command names to IDs of the existing commands to update. This will be used for all application commands but in cases where
commands have overlapping names, This field is complementary to This currently isn't supported when multiple guild IDs are passed for
TYPE:
|
message_ids |
If provided, a mapping of message context menu command names to the IDs of existing commands to update.
TYPE:
|
user_ids |
If provided, a mapping of user context menu command names to the IDs of existing commands to update.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises for the following reasons:
|
add_check #
add_check(*checks)
Add a generic check to this client.
This will be applied to both message and slash command execution.
PARAMETER | DESCRIPTION |
---|---|
*checks |
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The client instance to enable chained calls. |
add_component #
add_component(component)
Add a component to this client.
PARAMETER | DESCRIPTION |
---|---|
component |
The component to move to this client. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The client instance to allow chained calls. |
RAISES | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
prefixes |
Either a single string or an iterable of strings to be used as prefixes. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The client instance to enable chained calls. |
close
async
#
close(*, deregister_listeners=True)
Close the client.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the client isn't running. |
fetch_rest_application_id
async
#
fetch_rest_application_id()
Fetch the ID of the application this client is linked to.
RETURNS | DESCRIPTION |
---|---|
hikari.Snowflake
|
The application ID of the application this client is linked to. |
from_gateway_bot
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 tanjun.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
.
PARAMETER | DESCRIPTION |
---|---|
bot |
The bot client to build from. This will be used to infer the relevant Hikari clients to use.
TYPE:
|
event_managed |
Whether or not this client is managed by the event manager. An event managed client will be automatically started and closed based on Hikari's lifetime events.
TYPE:
|
injector |
The alluka client this should use for dependency injection. If not provided then the client will initialise its own DI client. |
mention_prefix |
Whether or not mention prefixes should be automatically set when this client is first started. It should be noted that this only applies to message commands.
TYPE:
|
declare_global_commands |
Whether or not to automatically set global slash commands when this client is first started. If one or more guild objects/IDs are passed here then the registered global commands will be set on the specified guild(s) at startup rather than globally. The endpoint this uses has a strict ratelimit which, as of writing, only allows for 2 requests per minute (with that ratelimit either being per-guild if targeting a specific guild otherwise globally).
TYPE:
|
set_global_commands |
Deprecated as of v2.1.1a1 alias of
TYPE:
|
command_ids |
If provided, a mapping of top level command names to IDs of the commands to update. This field is complementary to This currently isn't supported when multiple guild IDs are passed for
TYPE:
|
message_ids |
If provided, a mapping of message context menu command names to the IDs of existing commands to update.
TYPE:
|
user_ids |
If provided, a mapping of user context menu command names to the IDs of existing commands to update.
TYPE:
|
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 tanjun.Client from a hikari.traits.RESTBotAware instance.
Note
This sets type dependency injectors for the hikari traits present in
bot
(including hikari.traits.RESTBotAware).
PARAMETER | DESCRIPTION |
---|---|
bot |
The bot client to build from.
TYPE:
|
declare_global_commands |
Whether or not to automatically set global slash commands when this client is first started. If one or more guild objects/IDs are passed here then the registered global commands will be set on the specified guild(s) at startup rather than globally. The endpoint this uses has a strict ratelimit which, as of writing, only allows for 2 requests per minute (with that ratelimit either being per-guild if targeting a specific guild otherwise globally).
TYPE:
|
bot_managed |
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.
TYPE:
|
injector |
The alluka client this should use for dependency injection. If not provided then the client will initialise its own DI client. |
set_global_commands |
Deprecated as of v2.1.1a1 alias of
TYPE:
|
command_ids |
If provided, a mapping of top level command names to IDs of the existing commands to update. This will be used for all application commands but in cases where
commands have overlapping names, This field is complementary to This currently isn't supported when multiple guild IDs are passed for
TYPE:
|
message_ids |
If provided, a mapping of message context menu command names to the IDs of existing commands to update.
TYPE:
|
user_ids |
If provided, a mapping of user context menu command names to the IDs of existing commands to update.
TYPE:
|
on_autocomplete_interaction_request
async
#
on_autocomplete_interaction_request(interaction)
on_command_interaction_request
async
#
on_command_interaction_request(interaction)
Execute an app command based on received REST requests.
PARAMETER | DESCRIPTION |
---|---|
interaction |
The interaction to execute a command based on.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
hikari.api.InteractionMessageBuilder | hikari.api.InteractionDeferredBuilder | hikari.api.InteractionModalBuilder
|
The initial response to send back to Discord. |
on_gateway_autocomplete_create
async
#
on_gateway_autocomplete_create(interaction)
Execute command autocomplete based on a received gateway interaction create.
PARAMETER | DESCRIPTION |
---|---|
interaction |
The interaction to execute a command based on.
TYPE:
|
on_gateway_command_create
async
#
on_gateway_command_create(interaction)
Execute an app command based on a received gateway interaction create.
PARAMETER | DESCRIPTION |
---|---|
interaction |
The interaction to execute a command based on.
TYPE:
|
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.
PARAMETER | DESCRIPTION |
---|---|
event |
The event to execute commands based on.
TYPE:
|
on_message_create_event
async
#
on_message_create_event(event)
Execute a message command based on a gateway event.
PARAMETER | DESCRIPTION |
---|---|
event |
The event to handle.
TYPE:
|
open
async
#
open(*, register_listeners=True)
Start the client.
If mention_prefix
was passed to tanjun.Client.__init__
or tanjun.Client.from_gateway_bot then this function may make a fetch request
to Discord if it cannot get the current user from the cache.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the client is already active. |
remove_check #
remove_check(check)
Remove a check from the client.
PARAMETER | DESCRIPTION |
---|---|
check |
The check to remove.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the check was not previously added. |
remove_prefix #
remove_prefix(prefix)
Remove a message content prefix from the client.
PARAMETER | DESCRIPTION |
---|---|
prefix |
The prefix to remove.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the prefix is not registered with the client. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The client instance to enable chained calls. |
set_auto_defer_after #
set_auto_defer_after(time)
Set when this client should automatically defer execution of commands.
Warning
If time
is set to None then automatic deferrals will be disabled.
This may lead to unexpected behaviour.
PARAMETER | DESCRIPTION |
---|---|
time |
The time in seconds to defer interaction command responses after. |
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.context.AutocompleteContext rather than just any implementation of the AutocompleteContext abc due to this client relying on implementation detail of tanjun.context.AutocompleteContext.
PARAMETER | DESCRIPTION |
---|---|
maker |
The autocomplete context maker to use. This is a callback which should match the signature of tanjun.context.AutocompleteContext.init and return an instance of tanjun.context.AutocompleteContext.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
state |
Whether this client's message commands should be matched case-sensitively. This may be overridden by component specific configuration.
TYPE:
|
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.
PARAMETER | DESCRIPTION |
---|---|
permissions |
The default member permissions needed for this client's application commands. This may be overridden by tanjun.abc.AppCommand.default_member_permissions and tanjun.abc.Component.default_app_cmd_permissions; if this is left as None then this config will be inherited from the parent client. |
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
state |
Whether to enable this client's commands in DMs. This may be overridden by tanjun.abc.AppCommand.is_dm_enabled and tanjun.abc.Component.dms_enabled_for_app_cmds; if this is left as None then this config will be inherited from the parent client.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
state |
Whether slash command contexts executed in this client should should default to ephemeral. This will be overridden by any response calls which specify flags.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This client to enable method chaining. |
set_global_commands
async
#
set_global_commands(*, application=None, guild=hikari.UNDEFINED, force=False)
Alias of [tanjun.Client.declare_global_commands][].
deprecated
Since v2.1.1a1; use [tanjun.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 [tanjun.Client.add_type_dependency][] for all
the hikari trait types bot
is valid for with bot.
PARAMETER | DESCRIPTION |
---|---|
bot |
The hikari client to set dependency injectors for. |
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.
PARAMETER | DESCRIPTION |
---|---|
hooks |
The general command execution hooks to set for this client. Passing None will remove all hooks. |
RETURNS | DESCRIPTION |
---|---|
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).
PARAMETER | DESCRIPTION |
---|---|
value |
Whether or not message commands execution should be limited to "human" users. Passing True here will prevent message commands from being executed based on webhook and bot messages.
TYPE:
|
set_interaction_accepts #
set_interaction_accepts(accepts)
Set the kind of interactions this client should execute.
PARAMETER | DESCRIPTION |
---|---|
accepts |
Bitfield of the interaction types this client should execute.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If called while the client is running. |
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.
PARAMETER | DESCRIPTION |
---|---|
message |
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.context.MenuContext rather than just any implementation of the MenuContext abc due to this client relying on implementation detail of tanjun.context.MenuContext.
PARAMETER | DESCRIPTION |
---|---|
maker |
The autocomplete context maker to use. This is a callback which should match the signature of tanjun.context.MenuContext.init and return an instance of tanjun.context.MenuContext.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
hooks |
The menu context specific command execution hooks to set for this client. Passing None will remove the hooks. |
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
message |
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.
PARAMETER | DESCRIPTION |
---|---|
accepts |
The type of messages commands should be executed based on.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If called while the client is running. |
ValueError
|
If |
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.context.MessageContext rather than just any implementation of the MessageContext abc due to this client relying on implementation detail of tanjun.context.MessageContext.
PARAMETER | DESCRIPTION |
---|---|
maker |
The message context maker to use. This is a callback which should match the signature of tanjun.context.MessageContext.__init__ and return an instance of tanjun.context.MessageContext.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
hooks |
The message context specific command execution hooks to set for this client. Passing None will remove all hooks.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
getter |
The callback which'll be used to retrieve prefixes for the guild a message context is from. If None is passed here then the callback will be unset. This should be an async callback which one argument of type tanjun.abc.MessageContext and returns an iterable of string prefixes. Dependency injection is supported for this callback's keyword arguments.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.context.SlashContext rather than just any implementation of the SlashContext abc due to this client relying on implementation detail of tanjun.context.SlashContext.
PARAMETER | DESCRIPTION |
---|---|
maker |
The slash context maker to use. This is a callback which should match the signature of tanjun.context.SlashContext.__init__ and return an instance of tanjun.context.SlashContext.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
hooks |
The slash context specific command execution hooks to set for this client. Passing None will remove the hooks.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
message |
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.
PARAMETER | DESCRIPTION |
---|---|
check |
The check to add. This may be either synchronous or asynchronous and must take one positional argument of type tanjun.abc.Context with dependency injection being supported for its keyword arguments. |
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.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
PARAMETER | DESCRIPTION |
---|---|
getter |
The callback which'll be to retrieve prefixes for the guild a message event is from. This should be an async callback which one argument of type tanjun.abc.MessageContext and returns an iterable of string prefixes. Dependency injection is supported for this callback's keyword arguments.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
PrefixGetterSig
|
The registered callback. |
ClientCallbackNames #
Enum of the standard client callback names.
These should be dispatched by all tanjun.abc.Client implementations.
CLOSED
class-attribute
#
CLOSED = 'closed'
Called when the client has finished closing.
No positional arguments are provided for this event.
CLOSING
class-attribute
#
CLOSING = 'closing'
Called when the client is initially instructed to close.
No positional arguments are provided for this event.
COMPONENT_ADDED
class-attribute
#
COMPONENT_ADDED = 'component_added'
Called when a component is added to an active client.
Warning
This event isn't dispatched for components which were registered while the client is inactive.
The first positional argument is the tanjun.abc.Component being added.
COMPONENT_REMOVED
class-attribute
#
COMPONENT_REMOVED = 'component_removed'
Called when a component is added to an active client.
Warning
This event isn't dispatched for components which were removed while the client is inactive.
The first positional argument is the tanjun.abc.Component being removed.
MENU_COMMAND_NOT_FOUND
class-attribute
#
MENU_COMMAND_NOT_FOUND = 'menu_command_not_found'
Called when a menu command is not found.
tanjun.abc.MenuContext is provided as the first positional argument.
MESSAGE_COMMAND_NOT_FOUND
class-attribute
#
MESSAGE_COMMAND_NOT_FOUND = 'message_command_not_found'
Called when a message command is not found.
tanjun.abc.MessageContext is provided as the first positional argument.
SLASH_COMMAND_NOT_FOUND
class-attribute
#
SLASH_COMMAND_NOT_FOUND = 'slash_command_not_found'
Called when a slash command is not found.
tanjun.abc.SlashContext is provided as the first positional argument.
STARTED
class-attribute
#
STARTED = 'started'
Called when the client has finished starting.
No positional arguments are provided for this event.
STARTING
class-attribute
#
STARTING = 'starting'
Called when the client is initially instructed to start.
No positional arguments are provided for this event.
CommandError #
Bases: TanjunError
An error which is sent as a response to the command call.
__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.
PARAMETER | DESCRIPTION |
---|---|
content |
The content to respond with. If provided, the message contents. If hikari.undefined.UNDEFINED, then nothing will be sent in the content.
TYPE:
|
delete_after |
If provided, the seconds after which the response message should be deleted. Slash command responses can only be deleted within 15 minutes of the command being received.
TYPE:
|
attachment |
A singular attachment to respond with.
TYPE:
|
attachments |
A sequence of attachments to respond with.
TYPE:
|
component |
If provided, builder object of the component to include in this response.
TYPE:
|
components |
If provided, a sequence of the component builder objects to include in this response.
TYPE:
|
embed |
An embed to respond with.
TYPE:
|
embeds |
A sequence of embeds to respond with.
TYPE:
|
mentions_everyone |
If provided, whether the message should parse @everyone/@here mentions. |
user_mentions |
If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.
TYPE:
|
role_mentions |
If provided, and True, all mentions will be parsed. If provided, and False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.guilds.PartialRole derivatives to enforce mentioning specific roles.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raised for any of the following reasons:
|
send
async
#
send(ctx, /, *, ensure_result=False)
Send this error as a command response.
PARAMETER | DESCRIPTION |
---|---|
ctx |
The command call context to respond to. |
ensure_result |
Ensure that this call will always return a message object. If True then this will always return hikari.messages.Message,
otherwise this will return It's worth noting that, under certain scenarios within the slash command flow, this may lead to an extre request being made.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If |
hikari.BadRequestError
|
This may be raised in several discrete situations, such as messages being empty with no attachments or embeds; messages with more than 2000 characters in them, embeds that exceed one of the many embed limits; too many attachments; attachments that are too large; invalid image URLs in embeds; too many components. |
hikari.UnauthorizedError
|
If you are unauthorized to make the request (invalid/missing token). |
hikari.ForbiddenError
|
If you are missing the |
hikari.NotFoundError
|
If the channel is not found. |
hikari.RateLimitTooLongError
|
Raised in the event that a rate limit occurs that is
longer than |
hikari.RateLimitedError
|
Usually, Hikari will handle and retry on hitting rate-limits automatically. This includes most bucket-specific rate-limits and global rate-limits. In some rare edge cases, however, Discord implements other undocumented rules for rate-limiting, such as limits per attribute. These cannot be detected or handled normally by Hikari due to their undocumented nature, and will trigger this exception if they occur. |
hikari.InternalServerError
|
If an internal error occurs on Discord while handling the request. |
Component #
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: collections.Collection[tanjun.AnyCheckSig]
Collection of the checks being run against every command execution in this component.
hooks
property
#
hooks: typing.Optional[tanjun.AnyHooks]
The general command hooks set for this component, if any.
menu_hooks
property
#
menu_hooks: typing.Optional[tanjun.MenuHooks]
The menu command hooks set for this component, if any.
message_hooks
property
#
message_hooks: typing.Optional[tanjun.MessageHooks]
The message command hooks set for this component, if any.
schedules
property
#
schedules: collections.Collection[schedules_.AbstractSchedule]
Collection of the schedules registered to this component.
slash_hooks
property
#
slash_hooks: typing.Optional[tanjun.SlashHooks]
The slash command hooks set for this component, if any.
__init__ #
__init__(*, name=None, strict=False)
Initialise a new component.
PARAMETER | DESCRIPTION |
---|---|
name |
The component's identifier. If not provided then this will be a random string. |
strict |
Whether this component should use a stricter (more optimal) approach for message command search. When this is True, message command names will not be allowed to contain spaces and will have to be unique to one command within the component.
TYPE:
|
add_check #
add_check(*checks)
Add a command check to this component to be used for all its commands.
PARAMETER | DESCRIPTION |
---|---|
*checks |
The checks to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This component to enable method chaining. |
add_client_callback #
add_client_callback(name, /, *callbacks)
Add a client callback.
PARAMETER | DESCRIPTION |
---|---|
name |
The name this callback is being registered to. This is case-insensitive.
TYPE:
|
*callbacks |
The callbacks to register. These may be sync or async and must return None. The positional and
keyword arguments a callback should expect depend on implementation
detail around the
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The client instance to enable chained calls. |
add_command #
add_command(command)
Add a command to this component.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The current component to allow for chaining. |
add_message_command #
add_message_command(command)
Add a message command to the component.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The component to allow method chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If one of the command's name is already registered in a strict component. |
add_on_close #
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.
PARAMETER | DESCRIPTION |
---|---|
*callbacks |
The close callbacks to add to this component. This should take no positional arguments, return None and may take use injected dependencies.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
*callbacks |
The open callbacks to add to this component. These should take no positional arguments, return None and may request injected dependencies.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The component object to enable call chaining. |
add_schedule #
add_schedule(schedule)
Add a schedule to the component.
PARAMETER | DESCRIPTION |
---|---|
schedule |
The schedule to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The component itself for chaining. |
get_client_callbacks #
get_client_callbacks(name)
Get a collection of the callbacks registered for a specific name.
PARAMETER | DESCRIPTION |
---|---|
name |
The name to get the callbacks registered for. This is case-insensitive.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.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
tanjun.components.AbstractComponentLoader unless scope
is passed
but this isn't possible in a stack-less python implementation; in
stack-less environments the scope will have to be explicitly passed as
scope
.
PARAMETER | DESCRIPTION |
---|---|
include_globals |
Whether to include global variables (along with local) while detecting from the calling scope. This cannot be True when
TYPE:
|
scope |
The scope to detect entries which implement tanjun.components.AbstractComponentLoader from. This overrides the default usage of stackframe introspection.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The current component to allow for chaining. |
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If this is called in a python implementation which doesn't support
stack frame inspection when |
ValueError
|
If |
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 [tanjun.Client.load_modules][], [tanjun.Client.unload_modules][] and [tanjun.Client.reload_modules][].
PARAMETER | DESCRIPTION |
---|---|
copy |
Whether to copy the component before loading it into a client.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.ClientLoader
|
The loader for this component. |
remove_check #
remove_check(check)
Remove a command check from this component.
PARAMETER | DESCRIPTION |
---|---|
check |
The check to remove.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This component to enable method chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the check is not registered with this component. |
remove_client_callback #
remove_client_callback(name, callback)
Remove a client callback.
PARAMETER | DESCRIPTION |
---|---|
name |
The name this callback is being registered to. This is case-insensitive.
TYPE:
|
callback |
The callback to remove from the client's callbacks.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
KeyError
|
If the provided name isn't found. |
ValueError
|
If the provided callback isn't found. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The client instance to enable chained calls. |
remove_command #
remove_command(command)
Remove a command from this component.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to remove.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This component to enable method chaining. |
remove_schedule #
remove_schedule(schedule)
Remove a schedule from the component.
PARAMETER | DESCRIPTION |
---|---|
schedule |
The schedule to remove
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The component itself for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the schedule isn't registered. |
set_case_sensitive #
set_case_sensitive(state)
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.
PARAMETER | DESCRIPTION |
---|---|
permissions |
The default member permissions needed for this component's application commands. If this is left as None then this config will be inherited from the parent client. This may be overridden by tanjun.abc.AppCommand.default_member_permissions and if this is left as None then this config will be inherited from the parent client. |
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
state |
Whether to enable this component's commands in DMs. This may be overridden by tanjun.abc.AppCommand.is_dm_enabled and if this is left as None then this config will be inherited from the parent client. |
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
state |
Whether slash command contexts executed in this component should should default to ephemeral. This will be overridden by any response calls which specify flags. Setting this to None will let the default set on the parent client propagate and decide the ephemeral default behaviour. |
RETURNS | DESCRIPTION |
---|---|
Self
|
This component to enable method chaining. |
set_hooks #
set_hooks(hooks)
set_menu_hooks #
set_menu_hooks(hooks)
set_message_hooks #
set_message_hooks(hooks)
Set hooks to be called during the execution of this component's message commands.
PARAMETER | DESCRIPTION |
---|---|
hooks |
The message command hooks to set.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
hooks |
The slash command hooks to set.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This component to enable method chaining. |
with_check #
with_check(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
PARAMETER | DESCRIPTION |
---|---|
name |
The name this callback is being registered to. This is case-insensitive.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MetaEventSig], tanjun.abc.MetaEventSig]
|
Decorator callback used to register the client callback. This may be sync or async and must return None. The positional and
keyword arguments a callback should expect depend on implementation
detail around the |
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}")
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add to this component. |
copy |
Whether to copy the command before adding it to this component.
TYPE:
|
follow_wrapped |
Whether to also add any commands
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.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.
PARAMETER | DESCRIPTION |
---|---|
callback |
The close callback to add to this component. This should take no positional arguments, return None and may request injected dependencies.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
OnCallbackSig
|
The added close callback. |
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.
PARAMETER | DESCRIPTION |
---|---|
callback |
The open callback to add to this component. This should take no positional arguments, return None and may take use injected dependencies.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
OnCallbackSig
|
The added open callback. |
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.
@component.with_schedule
@tanjun.as_interval(60)
async def my_schedule():
print("I'm running every minute!")
PARAMETER | DESCRIPTION |
---|---|
schedule |
The schedule to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.schedules.AbstractSchedule
|
The added schedule. |
ConversionError #
Bases: ParserError
Error raised by a parser parameter when it failed to converter a value.
__init__ #
__init__(message, parameter, /, *, errors=())
Initialise a conversion error.
PARAMETER | DESCRIPTION |
---|---|
parameter |
The parameter this was raised by.
TYPE:
|
errors |
An iterable of the source value errors which were raised during conversion.
TYPE:
|
FailedCheck #
Bases: TanjunError
, RuntimeError
Error raised as an alternative to returning False
in a check.
FailedModuleImport #
Bases: FailedModuleLoad
Error raised when a module failed to import.
This is a specialisation of tanjun.errors.FailedModuleLoad.
FailedModuleLoad #
Bases: TanjunError
Error raised when a module fails to load.
This may be raised by the module failing to import or by one of its loaders erroring.
This source error can be accessed at FailedModuleLoad.cause.
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.
HaltExecution #
Bases: TanjunError
Error raised while looking for a command in-order to end-execution early.
For the most part, this will be raised during checks in-order to prevent other commands from being tried.
Hooks #
Bases: tanjun.Hooks[_ContextT_contra]
Standard implementation of tanjun.abc.Hooks used for command execution.
This will take either tanjun.abc.Context, tanjun.abc.MessageContext or tanjun.abc.SlashContext dependent on what its bound by (generic wise).
Note
This implementation adds a concept of parser errors which won't be dispatched to general "error" hooks and do not share the error suppression semantics as they favour to always suppress the error if a registered handler is found.
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!")
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add the hooks to.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.ExecutableCommand
|
The command with the hooks added. |
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.
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback to set for this hook. This will remove any previously set callbacks. This callback should take two positional arguments (of type tanjun.abc.Context and Exception) and may be either synchronous or asynchronous. Returning True indicates that the error should be suppressed, False that it should be re-raised and None that no decision has been made. This will be accounted for along with the decisions other error hooks make by majority rule.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback to set for this hook. This will remove any previously set callbacks. This callback should take two positional arguments (of type tanjun.abc.Context and tanjun.ParserError), return None and may be either synchronous or asynchronous. It's worth noting that, unlike general error handlers, this will always suppress the error.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The hook object to enable method chaining. |
set_on_success #
set_on_success(callback)
Set the success callback for this hook object.
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback to set for this hook. This will remove any previously set callbacks. This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The hook object to enable method chaining. |
set_post_execution #
set_post_execution(callback)
Set the post-execution callback for this hook object.
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback to set for this hook. This will remove any previously set callbacks. This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The hook object to enable method chaining. |
set_pre_execution #
set_pre_execution(callback)
Set the pre-execution callback for this hook object.
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback to set for this hook. This will remove any previously set callbacks. This callback should take one positional argument (of type tanjun.abc.Context), return None and may be either synchronous or asynchronous. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The hook object to enable method chaining. |
HotReloader #
Manages hot reloading modules for a Tanjun client..
Warning
An instance of this can only be linked to 1 client.
Examples:
client = tanjun.Client.from_gateway_bot(bot)
(
tanjun.dependencies.HotReloader()
.add_modules("python.module.path", pathlib.Path("./module.py"))
.add_directory("./modules/")
.add_to_client(client)
)
__init__ #
__init__(*, commands_guild=None, interval=datetime.timedelta(microseconds=500000), redeclare_cmds_after=datetime.timedelta(seconds=10), unload_on_delete=True)
Initialise a hot reloader.
Warning
redeclare_cmds_after
is not aware of commands declared outside of
the reloader and will lead to commands being redeclared on startup
when mixed with tanjun.clients.Client.__init__'s
declare_global_commands
argument when it is not None.
PARAMETER | DESCRIPTION |
---|---|
commands_guild |
Object or ID of the guild to declare commands in if
TYPE:
|
interval |
How often this should scan files and directories for changes in seconds.
TYPE:
|
redeclare_cmds_after |
How often to redeclare application commands after a change to the commands is detected. If None is passed here then this will not redeclare the application's commands.
TYPE:
|
unload_on_delete |
Whether this should unload modules when their relevant file is deleted.
TYPE:
|
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.
PARAMETER | DESCRIPTION |
---|---|
directory |
Path of the directory to hot reload. |
namespace |
The python namespace this directory's modules should be imported from, if applicable. This work as If left as None then this will have the same behaviour as when a pathlib.Path is passed to tanjun.abc.Client.load_modules. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The hot reloader to enable chained calls. |
RAISES | DESCRIPTION |
---|---|
FileNotFoundError
|
If the directory cannot be found |
add_directory_async
async
#
add_directory_async(directory, /, *, namespace=None)
Asynchronous variant of tanjun.dependencies.reloaders.HotReloader.add_directory.
Unlike tanjun.dependencies.reloaders.HotReloader.add_directory, this method will run blocking code in a background thread.
For more information on the behaviour of this method see the documentation for tanjun.dependencies.reloaders.HotReloader.add_directory.
add_modules #
add_modules(*paths)
Add modules for this hot reloader to track.
PARAMETER | DESCRIPTION |
---|---|
*paths |
Module paths for this hot reloader to track. This has the same behaviour as [tanjun.abc.Client.load_modules][ for how [pathlib.Path][] and str are treated. |
RAISES | DESCRIPTION |
---|---|
FileNotFoundError
|
If the module's file doesn't exist anymore. |
ModuleNotFoundError
|
If the str module path cannot be imported. |
add_modules_async
async
#
add_modules_async(*paths)
Asynchronous variant of tanjun.dependencies.reloaders.HotReloader.add_modules.
Unlike tanjun.dependencies.reloaders.HotReloader.add_modules, this method will run blocking code in a background thread.
For more information on the behaviour of this method see the documentation for tanjun.abc.Client.load_modules.
add_to_client #
add_to_client(client)
Add this to a tanjun.abc.Client instance.
This registers start and closing callbacks which handle the lifetime of this and adds this as a type dependency.
PARAMETER | DESCRIPTION |
---|---|
client |
The client to link this hot reloader to. |
scan
async
#
scan(client)
start #
start(client)
Start the hot reloader.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the hot reloader is already running. |
stop #
stop()
Stop the hot reloader.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the hot reloader isn't running. |
InMemoryConcurrencyLimiter #
Bases: AbstractConcurrencyLimiter
In-memory standard implementation of AbstractConcurrencyLimiter.
Examples:
InMemoryConcurrencyLimiter.set_bucket may be used to set the concurrency limits for a specific bucket:
(
InMemoryConcurrencyLimiter()
# Set the default bucket template to 10 concurrent uses of the command per-user.
.set_bucket("default", tanjun.BucketResource.USER, 10)
# Set the "moderation" bucket with a limit of 5 concurrent uses per-guild.
.set_bucket("moderation", tanjun.BucketResource.GUILD, 5)
.set_bucket()
# add_to_client will setup the concurrency manager (setting it as an
# injected dependency and registering callbacks to manage it).
.add_to_client(client)
)
add_to_client #
add_to_client(client)
close #
close()
Stop the concurrency manager.
RAISES | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
bucket_id |
The bucket to disable.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This concurrency manager to allow for chaining. |
open #
open(*, _loop=None)
Start the concurrency manager.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the concurrency manager is already running. If called in a thread with no running event loop. |
set_bucket #
set_bucket(bucket_id, resource, limit)
Set the concurrency limit for a specific bucket.
Note
"default" is a special bucket_id
which is used as a template for
unknown bucket IDs.
PARAMETER | DESCRIPTION |
---|---|
bucket_id |
The ID of the bucket to set the concurrency limit for.
TYPE:
|
resource |
The type of resource to target for the concurrency limit.
TYPE:
|
limit |
The maximum number of concurrent uses to allow.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The concurrency manager to allow call chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If an invalid resource type is given. if limit is less 0 or negative. |
InMemoryCooldownManager #
Bases: AbstractCooldownManager
In-memory standard implementation of AbstractCooldownManager.
Examples:
InMemoryCooldownManager.set_bucket may be used to set the cooldown for a specific bucket:
(
InMemoryCooldownManager()
# Set the default bucket template to a per-user 10 uses per-60 seconds cooldown.
.set_bucket("default", tanjun.BucketResource.USER, 10, 60)
# Set the "moderation" bucket to a per-guild 100 uses per-5 minutes cooldown.
.set_bucket("moderation", tanjun.BucketResource.GUILD, 100, datetime.timedelta(minutes=5))
.set_bucket()
# add_to_client will setup the cooldown manager (setting it as an
# injected dependency and registering callbacks to manage it).
.add_to_client(client)
)
add_to_client #
add_to_client(client)
close #
close()
Stop the cooldown manager.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the cooldown manager is not running. |
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.
PARAMETER | DESCRIPTION |
---|---|
bucket_id |
The bucket to disable.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
This cooldown manager to allow for chaining. |
open #
open(*, _loop=None)
Start the cooldown manager.
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the cooldown manager is already running. If called in a thread with no running event loop. |
set_bucket #
set_bucket(bucket_id, resource, limit, reset_after)
Set the cooldown for a specific bucket.
Note
"default" is a special bucket_id
which is used as a template for
unknown bucket IDs.
PARAMETER | DESCRIPTION |
---|---|
bucket_id |
The ID of the bucket to set the cooldown for.
TYPE:
|
resource |
The type of resource to target for the cooldown.
TYPE:
|
limit |
The number of uses per cooldown period.
TYPE:
|
reset_after |
The cooldown period. |
RETURNS | DESCRIPTION |
---|---|
Self
|
The cooldown manager to allow call chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If an invalid resource type is given. If reset_after or limit are negative, 0 or invalid. if limit is less 0 or negative. |
InteractionAcceptsEnum #
The possible configurations for which interaction this client should execute.
LazyConstant #
Injected type used to hold and generate lazy constants.
Note
To easily resolve this type use inject_lc.
callback
property
#
callback: alluka.abc.CallbackSig[_T]
Descriptor of the callback used to get this constant's initial value.
__init__ #
__init__(callback)
Initiate a new lazy constant.
PARAMETER | DESCRIPTION |
---|---|
callback |
Callback used to resolve this to a constant value. This supports dependency injection and may either be sync or asynchronous.
TYPE:
|
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 | DESCRIPTION |
---|---|
contextlib.AbstractAsyncContextManager[typing.Any]
|
Context manager that can be used to acquire the lock. |
set_value #
set_value(value)
Set the constant value.
PARAMETER | DESCRIPTION |
---|---|
value |
The value to set.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
RuntimeError
|
If the constant has already been set. |
MenuCommand #
Bases: base.PartialCommand[tanjun.MenuContext]
, tanjun.MenuCommand[_AnyMenuCallbackSigT, _MenuTypeT]
Base class used for the standard menu command implementations.
wrapped_command
property
#
wrapped_command: typing.Optional[tanjun.ExecutableCommand[typing.Any]]
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, _wrapped_command=None)
Initialise a user or message menu command.
Note
Under the standard implementation, is_global
is used to determine whether
the command should be bulk set by [tanjun.Client.declare_global_commands][]
or when declare_global_commands
is True
Note
If you want your first response to be ephemeral while using
always_defer
, you must set default_to_ephemeral
to True
.
PARAMETER | DESCRIPTION |
---|---|
callback |
Callback to execute when the command is invoked. This should be an asynchronous callback which takes one positional argument of type tanjun.abc.MenuContext, returns None and may use dependency injection to access other services.
TYPE:
|
type_ |
The type of menu command this is. Only hikari.commands.CommandType.USER and hikari.commands.CommandType.MESSAGE are valid here.
TYPE:
|
name |
The command's name (supports localisation). This must be between 1 and 32 characters in length. |
always_defer |
Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.
TYPE:
|
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MenuCallbackSig], MenuCommand]
|
The decorator callback used to make a tanjun.MenuCommand. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
set_ephemeral_default #
set_ephemeral_default(state)
Set whether this command's responses should default to ephemeral.
PARAMETER | DESCRIPTION |
---|---|
state |
Whether this command's responses should default to ephemeral. This will be overridden by any response calls which specify flags. Setting this to None will let the default set on the parent command(s), component or client propagate and decide the ephemeral default for contexts used by this command. |
RETURNS | DESCRIPTION |
---|---|
Self
|
This command to allow for chaining. |
MessageAcceptsEnum #
The possible configurations for which events tanjun.Client should execute commands based on.
ALL
class-attribute
#
ALL = 'ALL'
Set the client to execute commands based on both DM and guild message create events.
DM_ONLY
class-attribute
#
DM_ONLY = 'DM_ONLY'
Set the client to execute commands based only DM message create events.
GUILD_ONLY
class-attribute
#
GUILD_ONLY = 'GUILD_ONLY'
Set the client to execute commands based only guild message create events.
NONE
class-attribute
#
NONE = 'NONE'
Set the client to not execute commands based on message create events.
get_event_type #
get_event_type()
MessageCommand #
Bases: base.PartialCommand[tanjun.MessageContext]
, tanjun.MessageCommand[_MessageCallbackSigT]
Standard implementation of a message command.
wrapped_command
property
#
wrapped_command: typing.Optional[tanjun.ExecutableCommand[typing.Any]]
The command object this wraps, if any.
__init__ #
__init__(callback, name, /, *names, validate_arg_keys=True, _wrapped_command=None)
Initialise a message command.
PARAMETER | DESCRIPTION |
---|---|
callback |
Callback to execute when the command is invoked. This should be an asynchronous callback which takes one positional argument of type tanjun.abc.MessageContext, returns None and may use dependency injection to access other services.
TYPE:
|
name |
The command name.
TYPE:
|
*names |
Other names for the command.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
MessageCommandGroup #
Bases: MessageCommand[_MessageCallbackSigT]
, tanjun.MessageCommandGroup[_MessageCallbackSigT]
Standard implementation of a message command group.
__init__ #
__init__(callback, name, /, *names, strict=False, validate_arg_keys=True, _wrapped_command=None)
Initialise a message command group.
PARAMETER | DESCRIPTION |
---|---|
callback |
Callback to execute when the command is invoked. This should be an asynchronous callback which takes one positional argument of type tanjun.abc.MessageContext, returns None and may use dependency injection to access other services.
TYPE:
|
name |
The command name.
TYPE:
|
*names |
Other names for the command.
TYPE:
|
strict |
Whether this command group should only allow commands without spaces in their names. This allows for a more optimised command search pattern to be used and enforces that command names are unique to a single command within the group.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
add_command #
add_command(command)
Add a command to this group.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The group instance to enable chained calls. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If one of the command's names is already registered in a strict command group. |
as_sub_command #
as_sub_command(name, /, *names, validate_arg_keys=True)
Build a message command in this group from a decorated callback.
PARAMETER | DESCRIPTION |
---|---|
name |
The command name.
TYPE:
|
*names |
Other names for the command.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCallbackSig], MessageCommand]
|
The decorator callback used to make a sub-command. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand). |
as_sub_group #
as_sub_group(name, /, *names, strict=False, validate_arg_keys=True)
Build a message command group in this group from a decorated callback.
PARAMETER | DESCRIPTION |
---|---|
name |
The command name.
TYPE:
|
*names |
Other names for the command.
TYPE:
|
strict |
Whether this command group should only allow commands without spaces in their names. This allows for a more optimised command search pattern to be used and enforces that command names are unique to a single command within the group.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCallbackSig], MessageCommand]
|
The decorator callback used to make a sub-command group. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand). |
ModuleMissingLoaders #
Bases: RuntimeError
, TanjunError
Error raised when a module is missing loaders.
ModuleMissingUnloaders #
Bases: RuntimeError
, TanjunError
Error raised when a module is missing unloaders.
ModuleStateConflict #
Bases: ValueError
, TanjunError
Error raised when a module cannot be (un)loaded due to a state conflict.
NotEnoughArgumentsError #
Bases: ParserError
Error raised by the parser when not enough arguments are found for a parameter.
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.
ShlexParser #
SlashCommand #
Bases: BaseSlashCommand
, tanjun.SlashCommand[_SlashCallbackSigT]
Standard implementation of a slash command.
wrapped_command
property
#
wrapped_command: typing.Optional[tanjun.ExecutableCommand[typing.Any]]
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, sort_options=True, validate_arg_keys=True, _wrapped_command=None)
Initialise a slash command.
Note
Under the standard implementation, is_global
is used to determine whether
the command should be bulk set by [tanjun.Client.declare_global_commands][]
or when declare_global_commands
is True
Warning
default_member_permissions
, dm_enabled
and is_global
are
ignored for commands within slash command groups.
Note
If you want your first response to be ephemeral while using
always_defer
, you must set default_to_ephemeral
to True
.
PARAMETER | DESCRIPTION |
---|---|
callback |
Callback to execute when the command is invoked. This should be an asynchronous callback which takes one positional
argument of type tanjun.abc.SlashContext, returns
TYPE:
|
name |
The command's name (supports localisation). This must fit discord's requirements. |
description |
The command's description (supports localisation). This should be inclusively between 1-100 characters in length. |
always_defer |
Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.
TYPE:
|
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
sort_options |
Whether this command should sort its set options based on whether they're required. If this is True then the options are re-sorted to meet the requirement from Discord that required command options be listed before optional ones.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_attachment_option #
add_attachment_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add an attachment option to the slash command.
Note
This will result in options of type hikari.messages.Attachment.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_bool_option #
add_bool_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a boolean option to a slash command.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_channel_option #
add_channel_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, types=None, pass_as_kwarg=True)
Add a channel option to a slash command.
Note
This will always result in hikari.interactions.command_interactions.InteractionChannel.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
types |
A collection of the channel classes and types this option should accept. If left as None or empty then the option will allow all channel types.
TYPE:
|
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_float_option #
add_float_option(name, description, /, *, always_float=True, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True, _stack_level=0)
Add a float option to a slash command.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
always_float |
If this is set to True then the value will always be converted to a float (this will happen before it's passed to converters). This masks behaviour from Discord where we will either be provided a float or int dependent on what the user provided.
TYPE:
|
autocomplete |
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.
TYPE:
|
choices |
The option's choices. This is a mapping of [option_name, option_value] where option_name should be a string of up to 100 characters and option_value should be a float.
TYPE:
|
converters |
The option's converters. This may be either one or multiple converter callbacks used to convert the option's value to the final form. If no converters are provided then the raw value will be passed. Only the first converter to pass will be used.
TYPE:
|
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
min_value |
The option's (inclusive) minimum value. |
max_value |
The option's (inclusive) maximum value. |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_int_option #
add_int_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True, _stack_level=0)
Add an integer option to the slash command.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
autocomplete |
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.
TYPE:
|
choices |
The option's choices. This is a mapping of [option_name, option_value] where option_name should be a string of up to 100 characters and option_value should be an integer.
TYPE:
|
converters |
The option's converters. This may be either one or multiple converter callbacks used to convert the option's value to the final form. If no converters are provided then the raw value will be passed. Only the first converter to pass will be used.
TYPE:
|
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
min_value |
The option's (inclusive) minimum value. |
max_value |
The option's (inclusive) maximum value. |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_member_option #
add_member_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None)
Add a member option to a slash command.
Note
This will always result in hikari.interactions.base_interactions.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.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_mentionable_option #
add_mentionable_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a mentionable option to a slash command.
Note
This may target roles, guild members or users and results in
hikari.User | hikari.InteractionMember | hikari.Role
.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_role_option #
add_role_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a role option to a slash command.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_str_option #
add_str_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_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).
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
autocomplete |
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.
TYPE:
|
choices |
The option's choices. This either a mapping of [option_name, option_value] where both option_name and option_value should be strings of up to 100 characters or a sequence of strings where the string will be used for both the choice's name and value.
TYPE:
|
converters |
The option's converters. This may be either one or multiple converter callbacks used to convert the option's value to the final form. If no converters are provided then the raw value will be passed. Only the first converter to pass will be used.
TYPE:
|
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
min_length |
The minimum length of this string. This must be greater than or equal to 0, and less than or equal
to |
max_length |
The maximum length of this string. This must be greater then or equal to |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_user_option #
add_user_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a user option to a slash command.
Note
This may result in hikari.interactions.base_interactions.InteractionMember or hikari.users.User if the user isn't in the current guild or if this command was executed in a DM channel.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name (supports localisation). This must fit discord's requirements. |
description |
The option's description (supports localisation). This should be inclusively between 1-100 characters in length. |
default |
The option's default value. If this is left as undefined then this option will be required. |
key |
Name of the argument this option's value should be passed to. This defaults to the first name provided in |
pass_as_kwarg |
Whether or not to pass this option as a keyword argument to the command callback. If False is passed here then
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
set_float_autocomplete #
set_float_autocomplete(name, callback)
Set the autocomplete callback for a float option.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name. If localised names were provided for the option then this should be the default name.
TYPE:
|
callback |
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
KeyError
|
Raises a key error if the option doesn't exist. |
TypeError
|
Raises a type error if the option isn't of type |
set_int_autocomplete #
set_int_autocomplete(name, callback)
Set the autocomplete callback for a string option.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name. If localised names were provided for the option then this should be the default name.
TYPE:
|
callback |
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
KeyError
|
Raises a key error if the option doesn't exist. |
TypeError
|
Raises a type error if the option isn't of type |
set_str_autocomplete #
set_str_autocomplete(name, callback)
Set the autocomplete callback for a str option.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name. If localised names were provided for the option then this should be the default name.
TYPE:
|
callback |
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.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The command object for chaining. |
RAISES | DESCRIPTION |
---|---|
KeyError
|
Raises a key error if the option doesn't exist. |
TypeError
|
Raises a type error if the option isn't of type |
with_float_autocomplete #
with_float_autocomplete(name)
Set the autocomplete callback for a float option through a decorator call.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name. If localised names were provided for the option then this should be the default name.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Collections.abc.Callable[[tanjun.abc.AutocompleteSig[float]], tanjun.abc.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 | DESCRIPTION |
---|---|
KeyError
|
Raises a key error if the option doesn't exist. |
TypeError
|
Raises a type error if the option isn't of type |
with_int_autocomplete #
with_int_autocomplete(name)
Set the autocomplete callback for a integer option through a decorator call.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name. If localised names were provided for the option then this should be the default name.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Collections.abc.Callable[[tanjun.abc.AutocompleteSig[int]], tanjun.abc.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 | DESCRIPTION |
---|---|
KeyError
|
Raises a key error if the option doesn't exist. |
TypeError
|
Raises a type error if the option isn't of type |
with_str_autocomplete #
with_str_autocomplete(name)
Set the autocomplete callback for a string option through a decorator call.
PARAMETER | DESCRIPTION |
---|---|
name |
The option's name. If localised names were provided for the option then this should be the default name.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Collections.abc.Callable[[tanjun.abc.AutocompleteSig[str]], tanjun.abc.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 | DESCRIPTION |
---|---|
KeyError
|
Raises a key error if the option doesn't exist. |
TypeError
|
Raises a type error if the option isn't of type |
SlashCommandGroup #
Bases: BaseSlashCommand
, tanjun.SlashCommandGroup
Standard implementation of a slash command group.
Note
Unlike message command groups, slash command groups cannot be callable functions themselves.
__init__ #
__init__(name, description, /, *, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True)
Initialise a slash command group.
Note
Under the standard implementation, is_global
is used to determine
whether the command should be bulk set by [tanjun.Client.declare_global_commands][]
or when declare_global_commands
is True
Warning
default_member_permissions
, dm_enabled
and is_global
are
ignored for commands groups within another slash command groups.
PARAMETER | DESCRIPTION |
---|---|
name |
The name of the command group (supports localisation). This must fit discord's requirements. |
description |
The description of the command group (supports localisation). This should be inclusively between 1-100 characters in length. |
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
add_command #
add_command(command)
Add a slash command to this group.
Warning
Command groups are only supported within top-level groups.
PARAMETER | DESCRIPTION |
---|---|
command |
Command to add to this group.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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 tanjun.SlashCommand in this command group by decorating a function.
Note
If you want your first response to be ephemeral while using
always_defer
, you must set default_to_ephemeral
to True
.
PARAMETER | DESCRIPTION |
---|---|
name |
The command's name (supports localisation). This must fit discord's requirements. |
description |
The command's description. This should be inclusively between 1-100 characters in length. |
always_defer |
Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
sort_options |
Whether this command should sort its set options based on whether they're required. If this is True then the options are re-sorted to meet the requirement from Discord that required command options be listed before optional ones.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.SlashCallbackSig], SlashCommand]
|
The decorator callback used to make a sub-command. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand tanjun.SlashCommand). |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
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.
PARAMETER | DESCRIPTION |
---|---|
name |
The name of the command group (supports localisation). This must fit discord's requirements. |
description |
The description of the command group. |
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
RETURNS | DESCRIPTION |
---|---|
SlashCommandGroup
|
The created sub-command group. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
remove_command #
remove_command(command)
Remove a command from this group.
PARAMETER | DESCRIPTION |
---|---|
command |
Command to remove from this group.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Self
|
Object of this group to enable chained calls. |
with_command #
with_command(command)
Add a slash command to this group through a decorator call.
PARAMETER | DESCRIPTION |
---|---|
command |
Command to add to this group.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.BaseSlashCommand
|
Command which was added to this group. |
TooManyArgumentsError #
Bases: ParserError
Error raised by the parser when too many arguments are found for a parameter.
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.
PARAMETER | DESCRIPTION |
---|---|
interval |
The interval between calls. Passed as a timedelta, or a number of seconds. |
fatal_exceptions |
A sequence of exceptions that will cause the schedule to stop if raised by the callback, start callback or stop callback.
TYPE:
|
ignored_exceptions |
A sequence of exceptions that should be ignored if raised by the callback, start callback or stop callback.
TYPE:
|
max_runs |
The maximum amount of times the schedule runs. |
RETURNS | DESCRIPTION |
---|---|
collections.Callable[[_CallbackSigT], tanjun.scheduling.IntervalSchedule[_CallbackSigT]]
|
The decorator used to create the schedule. This should be decorating an asynchronous function which takes no positional arguments, returns None and may use dependency injection. |
as_loader #
as_loader(callback=None, /, *, standard_impl=True)
Mark a callback as being used to load Tanjun components from a module.
Note
This is only necessary if you wish to use [tanjun.Client.load_modules][].
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback used to load Tanjun components from a module. This should take one argument of type tanjun.Client (or
tanjun.abc.Client if
TYPE:
|
standard_impl |
Whether this loader should only allow instances of tanjun.Client as opposed to tanjun.abc.Client.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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.
PARAMETER | DESCRIPTION |
---|---|
name |
The command name.
TYPE:
|
*names |
Other names for the command.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCallbackSig], MessageCommand]
|
The decorator callback used to make a tanjun.MessageCommand. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope. |
as_message_command_group #
as_message_command_group(name, /, *names, strict=False, validate_arg_keys=True)
Build a message command group from a decorated callback.
PARAMETER | DESCRIPTION |
---|---|
name |
The command name.
TYPE:
|
*names |
Other names for the command.
TYPE:
|
strict |
Whether this command group should only allow commands without spaces in their names. This allows for a more optimised command search pattern to be used and enforces that command names are unique to a single command within the group.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCallbackSig], MessageCommand]
|
The decorator callback used to make a tanjun.MessageCommandGroup. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope. |
as_message_menu #
as_message_menu(name, /, *, always_defer=False, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True)
Build a message tanjun.MenuCommand by decorating a function.
Note
Under the standard implementation, is_global
is used to determine whether
the command should be bulk set by [tanjun.Client.declare_global_commands][]
or when declare_global_commands
is True
Note
If you want your first response to be ephemeral while using
always_defer
, you must set default_to_ephemeral
to True
.
Examples:
@as_message_menu("message")
async def message_command(self, ctx: tanjun.abc.MenuContext, message: hikari.Message) -> None:
await ctx.respond(
embed=hikari.Embed(title="Message content", description=message.content or "N/A")
)
PARAMETER | DESCRIPTION |
---|---|
name |
The command's name (supports localisation). This must be between 1 and 32 characters in length. |
always_defer |
Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.
TYPE:
|
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MenuCallbackSig], MenuCommand]
|
The decorator callback used to make a tanjun.MenuCommand. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
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
PARAMETER | DESCRIPTION |
---|---|
client |
The client to use to resolve dependencies. |
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[alluka.abc.CallbackSig], alluka.AsyncSelfInjecting]
|
Decorator callback that returns a self-injecting callback. |
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, sort_options=True, validate_arg_keys=True)
Build a tanjun.SlashCommand by decorating a function.
Note
Under the standard implementation, is_global
is used to determine whether
the command should be bulk set by [tanjun.Client.declare_global_commands][]
or when declare_global_commands
is True
Warning
default_member_permissions
, dm_enabled
and is_global
are
ignored for commands within slash command groups.
Note
If you want your first response to be ephemeral while using
always_defer
, you must set default_to_ephemeral
to True
.
Examples:
@as_slash_command("ping", "Get the bot's latency")
async def ping_command(self, ctx: tanjun.abc.SlashContext) -> None:
start_time = time.perf_counter()
await ctx.rest.fetch_my_user()
time_taken = (time.perf_counter() - start_time) * 1_000
await ctx.respond(f"PONG\n - REST: {time_taken:.0f}mss")
PARAMETER | DESCRIPTION |
---|---|
name |
The command's name (supports localisation). This must fit discord's requirements. |
description |
The command's description (supports localisation). This should be inclusively between 1-100 characters in length. |
always_defer |
Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.
TYPE:
|
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
sort_options |
Whether this command should sort its set options based on whether they're required. If this is True then the options are re-sorted to meet the requirement from Discord that required command options be listed before optional ones.
TYPE:
|
validate_arg_keys |
Whether to validate that option keys match the command callback's signature.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.SlashCallbackSig], SlashCommand]
|
The decorator callback used to make a tanjun.SlashCommand. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
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.
PARAMETER | DESCRIPTION |
---|---|
months |
Either one or multiple months the schedule should run on. If this is not specified or an empty sequence then the schedule will run on all months.
TYPE:
|
weekly |
Whether the schedule should run on a weekly basis.
TYPE:
|
days |
Either one or multiple days the schedule should run on. When Otherwise this will refer to the days of the month ( If this is not specified or an empty sequence, then the schedule will on all days.
TYPE:
|
hours |
Either one or multiple hours the schedule should run on. If this is not specified or an empty sequence then the schedule will run on all hours.
TYPE:
|
minutes |
Either one or multiple minutes the schedule should run on. If this is not specified or an empty sequence then the schedule will run on all minutes.
TYPE:
|
seconds |
Either one or multiple seconds the schedule should run on. Defaults to the start of the minute if not specified or an empty sequence.
TYPE:
|
fatal_exceptions |
A sequence of exceptions that will cause the schedule to stop if raised by the callback, start callback or stop callback.
TYPE:
|
ignored_exceptions |
A sequence of exceptions that should be ignored if raised by the callback, start callback or stop callback.
TYPE:
|
timezone |
The timezone to use for the schedule. If this is not specified then the system's local timezone will be used. |
RETURNS | DESCRIPTION |
---|---|
collections.Callable[[_CallbackSigT], tanjun.scheduling.TimeSchedule[_CallbackSigT]]
|
The decorator used to create the schedule. This should be decorating an asynchronous function which takes no positional arguments, returns None and may use dependency injection. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
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 tanjun.as_loader and is only necessary if you wish to use the [tanjun.Client.unload_modules][] or [tanjun.Client.reload_modules][].
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback used to unload Tanjun components from a module. This should take one argument of type tanjun.Client (or
tanjun.abc.Client if
TYPE:
|
standard_impl |
Whether this unloader should only allow instances of tanjun.Client as opposed to tanjun.abc.Client.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
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)
Build a user tanjun.MenuCommand by decorating a function.
Note
Under the standard implementation, is_global
is used to determine whether
the command should be bulk set by [tanjun.Client.declare_global_commands][]
or when declare_global_commands
is True
Note
If you want your first response to be ephemeral while using
always_defer
, you must set default_to_ephemeral
to True
.
Examples:
@as_user_menu("user")
async def user_command(
self,
ctx: tanjun.abc.MenuContext,
user: hikari.User | hikari.InteractionMember,
) -> None:
await ctx.respond(f"Hello {user}")
PARAMETER | DESCRIPTION |
---|---|
name |
The command's name (supports localisation). This must be between 1 and 32 characters in length. |
always_defer |
Whether the contexts this command is executed with should always be deferred before being passed to the command's callback.
TYPE:
|
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MenuCallbackSig], MenuCommand]
|
The decorator callback used to make a tanjun.MenuCommand. This can either wrap a raw command callback or another callable command instance (e.g. tanjun.MenuCommand, tanjun.MessageCommand, tanjun.SlashCommand) and will manage loading the other command into a component when using tanjun.Component.load_from_scope. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
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
PARAMETER | DESCRIPTION |
---|---|
callback |
The callback to inject.
TYPE:
|
expire_after |
The amount of time to cache the result for in seconds. Leave this as None to cache for the runtime of the application.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
alluka.InjectedDescriptor[_T]
|
Injector used to resolve the cached callback. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If expire_after is not a valid value. If expire_after is not less than or equal to 0 seconds. |
inject_lc #
inject_lc(type_)
Make a LazyConstant injector.
This acts like alluka.inject and the result of it should also be assigned to a parameter's default to be used.
Note
For this to work, a LazyConstant
must've been set as a type dependency for the passed type_
.
PARAMETER | DESCRIPTION |
---|---|
type_ |
The type of the constant to resolve.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
alluka.InjectedDescriptor[_T]
|
Injector used to resolve the LazyConstant. |
Example#
@component.with_command
@tanjun.as_message_command
async def command(
ctx: tanjun.abc.MessageCommand,
application: hikari.Application = tanjun.inject_lc(hikari.Application)
) -> None:
raise NotImplementedError
...
async def resolve_app(
client: tanjun.abc.Client = tanjun.inject(type=tanjun.abc.Client)
) -> hikari.Application:
raise NotImplementedError
tanjun.Client.from_gateway_bot(...).set_type_dependency(
tanjun.LazyConstant[hikari.Application] = tanjun.LazyConstant(resolve_app)
)
slash_command_group #
slash_command_group(name, description, /, *, default_member_permissions=None, default_to_ephemeral=None, dm_enabled=None, is_global=True)
Create a slash command group.
Note
Unlike message command groups, slash command groups cannot be callable functions themselves.
Warning
default_member_permissions
, dm_enabled
and is_global
are
ignored for command groups within other slash command groups.
Note
Under the standard implementation, is_global
is used to determine whether
the command should be bulk set by [tanjun.Client.declare_global_commandsadd_command
or when declare_global_commands
is True
Examples:
Sub-commands can be added to the created slash command object through the following decorator based approach:
help_group = tanjun.slash_command_group("help", "get help")
@help_group.with_command
@tanjun.with_str_slash_option("command_name", "command name")
@tanjun.as_slash_command("command", "Get help with a command")
async def help_command_command(ctx: tanjun.abc.SlashContext, command_name: str) -> None:
...
@help_group.with_command
@tanjun.as_slash_command("me", "help me")
async def help_me_command(ctx: tanjun.abc.SlashContext) -> None:
...
component = tanjun.Component().add_slash_command(help_group)
PARAMETER | DESCRIPTION |
---|---|
name |
The name of the command group (supports localisation). This must fit discord's requirements. |
description |
The description of the command group (supports localisation). This should be inclusively between 1-100 characters in length. |
default_member_permissions |
Member permissions necessary to utilize this command by default. If this is None then the configuration for the parent component or client will be used.
TYPE:
|
default_to_ephemeral |
Whether this command's responses should default to ephemeral unless flags are set to override this. If this is left as None then the default set on the parent command(s), component or client will be in effect. |
dm_enabled |
Whether this command is enabled in DMs with the bot. If this is None then the configuration for the parent component or client will be used. |
is_global |
Whether this command is a global command.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
SlashCommandGroup
|
The command group. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
Raises a value error for any of the following reasons:
|
to_bool #
to_bool(value)
Convert user string input into a boolean value.
PARAMETER | DESCRIPTION |
---|---|
value |
The value to convert.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
bool
|
The converted value. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the value cannot be converted. |
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
PARAMETER | DESCRIPTION |
---|---|
value |
The value to parse.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
datetime.datetime
|
The parsed datetime. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the value cannot be parsed. |
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.
PARAMETER | DESCRIPTION |
---|---|
check |
The first check callback to combine. |
*checks |
Additional check callbacks to combine. |
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.Context], collections.abc.Coroutine[typing.Any, typing.Any, bool]]
|
A check which will pass if all of the provided check callbacks pass. |
with_any_checks #
with_any_checks(check, /, *checks, error=None, error_message, follow_wrapped=False, halt_execution=False, suppress=(errors.CommandError, errors.HaltExecution))
Add a check which'll pass if any of the provided checks pass through a decorator call.
This ensures that the callbacks are run in the order they were supplied in rather than concurrently.
PARAMETER | DESCRIPTION |
---|---|
check |
The first check callback to combine. |
*checks |
Additional check callbacks to combine. |
error |
Callback used to create a custom error to raise if the check fails. This takes priority over
TYPE:
|
error_message |
The error message to send in response as a command error if the check fails. This supports localisation and uses the check name
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
halt_execution |
Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False. This takes priority over
TYPE:
|
suppress |
Tuple of the exceptions to suppress when a check fails.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]
|
A decorator which adds the generated check to a command. |
with_argument #
with_argument(key, /, converters=(), *, default=UNDEFINED, 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):
...
PARAMETER | DESCRIPTION |
---|---|
key |
The string identifier of this argument (may be used to pass the result of this argument to the command's callback during execution).
TYPE:
|
converters |
The converter(s) this argument should use to handle values passed to it during parsing. If no converters are provided then the raw string value will be passed. Only the first converter to pass will be used.
TYPE:
|
default |
The default value of this argument, if left as UNDEFINED then this will have no default. |
greedy |
Whether or not this argument should be greedy (meaning that it takes in the remaining argument values).
TYPE:
|
min_length |
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 |
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 |
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 |
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 Whether this argument can be passed multiple times.
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]
|
Decorator function for the message command this argument is being added to. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If |
with_attachment_slash_option #
with_attachment_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add an attachment option to a slash command.
For more information on this function's parameters see tanjun.SlashCommand.add_attachment_option.
Examples:
@with_attachment_slash_option("name", "A name.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, name: hikari.Attachment) -> None:
...
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
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)
PARAMETER | DESCRIPTION |
---|---|
permissions |
The permission(s) required for this command to run. |
error |
Callback used to create a custom error to raise if the check fails. This should take 1 positional argument of type hikari.permissions.Permissions which represents the missing permissions required for this command to run. This takes priority over
TYPE:
|
error_message |
The error message to send in response as a command error if the check fails. Setting this to None will disable the error message allowing the command search to continue. This supports localisation and uses the check name
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
halt_execution |
Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False. This takes priority over
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]
|
A command decorator callback which adds the check. |
with_bool_slash_option #
with_bool_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a boolean option to a slash command.
For information on this function's parameters see tanjun.SlashCommand.add_bool_option.
Examples:
@with_bool_slash_option("flag", "Whether this flag should be enabled.", default=False)
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, flag: bool) -> None:
...
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
with_channel_slash_option #
with_channel_slash_option(name, description, /, *, types=None, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a channel option to a slash command.
For information on this function's parameters see tanjun.SlashCommand.add_channel_option.
Note
This will always result in hikari.interactions.command_interactions.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 | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
with_check #
with_check(check, /, *, follow_wrapped=False)
Add a generic check to a command.
PARAMETER | DESCRIPTION |
---|---|
check |
The check to add to this command. |
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.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.
PARAMETER | DESCRIPTION |
---|---|
bucket_id |
The concurrency limit bucket's ID.
TYPE:
|
error |
Callback used to create a custom error to raise if the check fails. This should two one str argument which is the limiting bucket's ID. This takes priority over
TYPE:
|
error_message |
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
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]
|
A decorator that 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}.', follow_wrapped=False, owners_exempt=True)
Add a pre-execution hook used to manage a command's cooldown through a decorator call.
Warning
Cooldowns will only work if there's a setup injected AbstractCooldownManager dependency with InMemoryCooldownManager being usable as a standard in-memory cooldown manager.
PARAMETER | DESCRIPTION |
---|---|
bucket_id |
The cooldown bucket's ID.
TYPE:
|
error |
Callback used to create a custom error to raise if the check fails. This should two arguments one of type str and datetime.datetime where the first is the limiting bucket's ID and the second is when said bucket can be used again. This takes priority over
TYPE:
|
error_message |
The error message to send in response as a command error if the check fails. This supports localisation and uses the check name
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
owners_exempt |
Whether owners should be exempt from the cooldown.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.ExecutableCommand], tanjun.abc.ExecutableCommand]
|
A decorator that adds a CooldownPreExecution hook to the command. |
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.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add this check to.
TYPE:
|
error |
Callback used to create a custom error to raise if the check fails. This takes priority over
TYPE:
|
error_message |
The error message to send in response as a command error if the check fails. Setting this to None will disable the error message allowing the command search to continue. This supports localisation and uses the check name
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
halt_execution |
Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False. This takes priority over
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.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=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True)
Add a float option to a slash command.
For information on this function's parameters see tanjun.SlashCommand.add_float_option.
Examples:
@with_float_slash_option("float_value", "Float value.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, float_value: float) -> None:
...
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
with_greedy_argument #
with_greedy_argument(key, /, converters=(), *, default=UNDEFINED, 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):
...
PARAMETER | DESCRIPTION |
---|---|
key |
The string identifier of this argument (may be used to pass the result of this argument to the command's callback during execution).
TYPE:
|
converters |
The converter(s) this argument should use to handle values passed to it during parsing. If no converters are provided then the raw string value will be passed. Only the first converter to pass will be used.
TYPE:
|
default |
The default value of this argument, if left as UNDEFINED then this will have no default. 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. |
min_length |
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 |
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 |
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 |
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 | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]
|
Decorator function for the message command this argument is being added to. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If |
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.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add this check to.
TYPE:
|
error |
Callback used to create a custom error to raise if the check fails. This takes priority over
TYPE:
|
error_message |
The error message to send in response as a command error if the check fails. Setting this to None will disable the error message allowing the command search to continue. This supports localisation and uses the check name
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
halt_execution |
Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False. This takes priority over
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.ExecutableCommanmd
|
The command this check was added to. |
with_int_slash_option #
with_int_slash_option(name, description, /, *, autocomplete=None, choices=None, converters=(), default=UNDEFINED_DEFAULT, key=None, min_value=None, max_value=None, pass_as_kwarg=True)
Add an integer option to a slash command.
For information on this function's parameters see tanjun.SlashCommand.add_int_option.
Examples:
@with_int_slash_option("int_value", "Int value.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, int_value: int) -> None:
...
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
with_member_slash_option #
with_member_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None)
Add a member option to a slash command.
For information on this function's arguments see tanjun.SlashCommand.add_member_option.
Note
This will always result in hikari.interactions.base_interactions.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 | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
with_mentionable_slash_option #
with_mentionable_slash_option(name, description, /, *, default=UNDEFINED_DEFAULT, key=None, pass_as_kwarg=True)
Add a mentionable option to a slash command.
For information on this function's arguments see tanjun.SlashCommand.add_mentionable_option.
Note
This may target roles, guild members or users and results in
hikari.User | hikari.InteractionMember | hikari.Role
.
Examples:
@with_mentionable_slash_option("mentionable", "Mentionable entity to target.")
@as_slash_command("command", "A command")
async def command(self, ctx: tanjun.abc.SlashContext, mentionable: [Role, InteractionMember, User]) -> None:
...
RETURNS | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.SlashCommand], tanjun.SlashCommand]
|
Decorator callback which adds the option to the command. |
with_multi_argument #
with_multi_argument(key, /, converters=(), *, default=UNDEFINED, 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]):
...
PARAMETER | DESCRIPTION |
---|---|
key |
The string identifier of this argument (may be used to pass the result of this argument to the command's callback during execution).
TYPE:
|
converters |
The converter(s) this argument should use to handle values passed to it during parsing. If no converters are provided then the raw string value will be passed. Only the first converter to pass will be used.
TYPE:
|
default |
The default value of this argument, if left as UNDEFINED then this will have no default. |
min_length |
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 |
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 |
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 |
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 | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]
|
Decorator function for the message command this argument is being added to. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If |
with_multi_option #
with_multi_option(key, name, /, *names, converters=(), default, empty_value=UNDEFINED, 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]):
...
PARAMETER | DESCRIPTION |
---|---|
key |
The string identifier of this option which will be used to pass the result of this argument to the command's callback during execution as a keyword argument.
TYPE:
|
name |
The name of this option used for identifying it in the parsed content.
TYPE:
|
*names |
Other names of this option used for identifying it in the parsed content.
TYPE:
|
default |
The default value of this argument, unlike arguments this is required for options. |
converters |
The converter(s) this argument should use to handle values passed to it during parsing. If no converters are provided then the raw string value will be passed. Only the first converter to pass will be used.
TYPE:
|
empty_value |
The value to use if this option is provided without a value. If left as UNDEFINED then this option will error if it's provided without a value. |
min_length |
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 |
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 |
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 |
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 | DESCRIPTION |
---|---|
collections.abc.Callable[[tanjun.abc.MessageCommand], tanjun.abc.MessageCommand]
|
Decorator function for the message command this option is being added to. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If |
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.
PARAMETER | DESCRIPTION |
---|---|
command |
The command to add this check to.
TYPE:
|
error |
Callback used to create a custom error to raise if the check fails. This takes priority over
TYPE:
|
error_message |
The error message to send in response as a command error if the check fails. Setting this to None will disable the error message allowing the command search to continue. This supports localisation and uses the check name
TYPE:
|
follow_wrapped |
Whether to also add this check to any other command objects this command wraps in a decorator call chain.
TYPE:
|
halt_execution |
Whether this check should raise tanjun.HaltExecution to end the execution search when it fails instead of returning False. This takes priority over
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tanjun.abc.ExecutableCommand
|
The command this check was added to. |
with_option #
with_option(key, name, /, *names, converters=(), default, empty_value=UNDEFINED, 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.