API Reference¶
Command Handler¶
- class lightbulb.command_handler.Bot(token: str, *, prefix: Optional[Union[str, Iterable[str], Callable[[Bot, hikari.messages.Message], Union[Coroutine[None, None, Union[str, Iterable[str]]], str, Iterable[str]]]]] = None, insensitive_commands: bool = False, ignore_bots: bool = True, owner_ids: Iterable[int] = (), help_class: Type[lightbulb.help.HelpCommand] = <class 'lightbulb.help.HelpCommand'>, delete_unbound_slash_commands: bool = True, recreate_changed_slash_commands: bool = True, slash_commands_only: bool = False, default_enabled_guilds: Optional[Union[int, Iterable[int]]] = None, **kwargs: hikari.undefined.UndefinedType)¶
A subclassed implementation of
hikari.impl.bot.GatewayBot
which contains a command handler. This should be instantiated instead of the superclass if you want to be able to use the command handler implementation provided.The prefix argument will accept any of the following:
A single string, eg
'!'
An iterable (such as a list) of strings, eg
['!', '?']
A function or coroutine that takes only two arguments,
bot
andmessage
, and that returns a single string or iterable of strings.
- Parameters
prefix – The bot’s command prefix, iterable of prefixes, or callable that returns a prefix or iterable of prefixes.
insensitive_commands (
bool
) – Whether or not commands should be case-insensitive or not. Defaults to False (commands are case-sensitive).ignore_bots (
bool
) – Ignore other bot’s messages invoking your bot’s commands if True (default), else not. invoked by other bots. Defaults toTrue
.owner_ids (List[
int
]) – IDs that the bot should treat as owning the bot.help_class (
HelpCommand
) – The uninstantiated class the bot should use for it’s help command. Defaults toHelpCommand
. Any class passed should always be this class or subclass of this class.delete_unbound_slash_commands (
bool
) – Whether or not to delete unbound slash commands when the bot starts. This will remove any slash commands that do not have aSlashCommand
object bound to them when the bot starts but are registered according to discord’s API. Defaults toTrue
.recreate_changed_slash_commands (
bool
) – Whether or not to send the new version of the slash command to discord if the bot detects that the version on discord does not match the local version. Defaults toTrue
.slash_commands_only (
bool
) – Whether or not the bot will only be using slash commands to interact with discord. Defaults toFalse
. If this isFalse
and no prefix is provided then an error will be raised. IfTrue
, then you do not need to provide a prefix.default_enabled_guilds (Union[
int
, Iterable[int
] ]) – The IDs of the guilds you want slash commands to be enabled in by default. If this is an empty sequence orNone
, commands will be global by default, and you will need to manually specify the guild ID per command to change this. If you only want to enable a single guild, you can pass the ID directly instead of a one-element sequence. Defaults toNone
.**kwargs – Other parameters passed to the
hikari.impl.bot.GatewayBot
constructor.
- add_check(func: Union[Callable[[lightbulb.context.Context], Coroutine[None, None, bool]], lightbulb.checks.Check]) None ¶
Add a coroutine as a global check for the bot.
This coroutine will be called before any command invocation.
- Parameters
func (Callable[[
Context ], Coroutine[ ``None`
,None
,bool
]]) – The coroutine to add as a global check.- Returns
None
- add_command(func: Union[Callable, lightbulb.commands.Command], **kwargs) lightbulb.commands.Command ¶
Adds a command to the bot. Similar to the
command
decorator.- Parameters
func (
typing.Callable
) – The function or command object to register as a command.- Keyword Arguments
**kwargs – See
command
for valid kwargs.- Returns
Command added to the bot.
- Return type
- Raises
NameError – If the name or an alias of the command being added conflicts with an existing command.
Example
import lightbulb bot = lightbulb.Bot(...) async def ping(ctx): await ctx.respond("Pong!") bot.add_command(ping)
See also
- add_group(func: Union[Callable, lightbulb.commands.Group], **kwargs) lightbulb.commands.Group ¶
Adds a command group to the bot. Similar to the
group
decorator.- Parameters
func (Union[
typing.Callable
,Group
]) – The function or group object to register as a command group.- Keyword Arguments
**kwargs – See
group
for valid kwargs.- Returns
Group added to the bot.
- Return type
- Raises
AttributeError – If the name or an alias of the group being added conflicts with an existing command.
See also
- add_plugin(plugin: Union[lightbulb.plugins.Plugin, Type[lightbulb.plugins.Plugin]]) None ¶
Add a
Plugin
instance or class to the bot, including all of the plugin commands.If a class is passed in instead of a plugin instance, then the bot will attempt to instantiate it and then add the newly-created plugin instance to the bot.
- add_slash_command(command: Union[Type[lightbulb.slash_commands.commands.SlashCommand], Type[lightbulb.slash_commands.commands.SlashCommandGroup]], create: bool = False) None ¶
Registers a slash command with the bot.
- Parameters
command (Union[Type[
SlashCommand
], Type[SlashCommandGroup
]]) – The slash command class to register to the bot. This should not be an instance.create (
bool
) – Whether or not to send a create request to discord when the command is added. Defaults toFalse
.
- Returns
None
Warning
The
create
argument must beFalse
if the command is being added to the bot before the bot has started (i.e.bot.run()
has not yet been called).
- autodiscover_slash_commands(create: bool = False) None ¶
Automatically discovers all slash command classes in the current extension and adds each of them to the bot.
This should only be used in an extension’s
load
function.- Parameters
create (
bool
) – Whether or not to send a create request to discord when the command is added. Defaults toFalse
.- Returns
None
- autoremove_slash_commands(delete: bool = False) None ¶
Automatically discovers all slash command classes in the current extension and removes each of them from the bot.
This should only be used in an extension’s
unload
function.- Parameters
delete (
bool
) – Whether or not to delete the command from discord when it is removed. Defaults toFalse
.- Returns
None
- check()¶
A decorator that registers a coroutine as a global check.
This check coroutine will be called before any command invocation.
Example
bot = lightbulb.Bot(...) @bot.check() async def global_guild_only(ctx): return ctx.guild_id is not None
See also
- command(**kwargs) Callable ¶
A decorator that registers a coroutine as a command for the handler.
- Keyword Arguments
**kwargs – See
command
for valid kwargs.
Example
bot = lightbulb.Bot(...) @bot.command() async def ping(ctx): await ctx.respond("Pong!")
See also
- async fetch_owner_ids() None ¶
Fetches the IDs of the bot’s owner(s) from the API and stores them in
owner_ids
- Returns
None
- get_command(name: str) Optional[lightbulb.commands.Command] ¶
Get a command object from its registered name.
- get_context(message: hikari.messages.Message, prefix: str, invoked_with: str, invoked_command: lightbulb.commands.Command) lightbulb.context.Context ¶
Get the
Context
instance for the given arguments. This should be overridden if you wish to supply a customContext
class to your commands.- Parameters
- Returns
The context to be used for the command invocation.
- Return type
- get_plugin(name: str) Optional[lightbulb.plugins.Plugin] ¶
Get a plugin object from its registered name.
- get_slash_command(name: str) Optional[Union[lightbulb.slash_commands.commands.SlashCommand, lightbulb.slash_commands.commands.SlashCommandGroup]] ¶
Gets the slash command with the given name, or
None
if one with that name does not exist.- Parameters
name (
str
) – The name of the slash command to get the object for.- Returns
- Retrieved slash command or
None
if not found.
- Retrieved slash command or
- Return type
Optional[
BaseSlashCommand
]
- get_slash_command_context(event: hikari.events.interaction_events.InteractionCreateEvent, command: Union[lightbulb.slash_commands.commands.SlashCommand, lightbulb.slash_commands.commands.SlashCommandGroup]) lightbulb.slash_commands.context.SlashCommandContext ¶
Get the
SlashCommandContext
instance for the given arguments. This should be overridden if you wish to supply a customSlashCommandContext
class to your slash commands.- Parameters
event (
hikari.InteractionCreateEvent
) – The event this context is for.command (Union[
SlashCommand
,SlashCommandGroup
]) – Command invoked for the event.
- Returns
Context to use for the command invocation.
- Return type
- group(**kwargs) Callable ¶
A decorator that registers a coroutine as a command group for the handler.
- Keyword Arguments
**kwargs – See
group
for valid kwargs.
Example
bot = lightbulb.Bot(...) @bot.group() async def foo(ctx): await ctx.respond("Bar")
See also
command()
for how to add subcommands to a group.
- async handle(event: hikari.events.message_events.MessageCreateEvent) None ¶
The message listener that deals with validating the invocation messages. If invocation message is valid then it will delegate parsing and invocation to
Bot.process_commands_for_event
.You can override this method to customise how the bot should validate that a message could contain a command invocation, for example making it ignore specific guilds or users.
If you choose to override this method, it should await
Bot.process_commands_for_event
otherwise no commands will ever be invoked.- Parameters
event (
hikari.events.message.MessageCreateEvent
) – The message create event containing a possible command invocation.- Returns
None
- async handle_slash_commands(event: hikari.events.interaction_events.InteractionCreateEvent) None ¶
The InteractionCreateEvent listener that handles slash command invocations and resolves and invokes the correct callback from the event payload.
- Parameters
event (
hikari.InteractionCreateEvent
) – The InteractionCreateEvent for the slash command invocation.- Returns
None
- load_extension(extension: str) None ¶
Load an external extension into the bot. Extension name follows the format
<directory>.<filename>
The extension must contain a functionload
which takes a single argument which will be the bot instance you are loading the extension into.- Parameters
extension (
str
) – The name of the extension to load.- Returns
None
- Raises
ExtensionAlreadyLoaded – If the extension has already been loaded.
ExtensionMissingLoad – If the extension to be loaded does not contain a
load
function.ExtensionNotFound – If the extension to be loaded does not exist.
Example
This method is useful when wanting to split your bot up into multiple files. An example extension is seen below -
example.py
and would be loaded by calling the following:bot.load_extension("example")
import lightbulb class MyPlugin(lightbulb.Plugin): ... def load(bot): bot.add_plugin(MyPlugin())
- load_extensions_from(path: Union[str, pathlib.Path], *, recursive: bool = False, must_exist: bool = False) None ¶
Load all external extensions from a given directory. Files that begin with an underscore ( _ ) are ignored. Every extension must contain a function
load
which takes a single argument which will be the bot instance you are loading the extension into.- Parameters
path (Union[
str
,pathlib.Path
]) – The directory to load extensions from.- Keyword Arguments
recursive (
bool
) – Whether to search the directory recursively. Defaults to False.must_exist (
bool
) – Whether the directory must exist before extensions can be loaded. If this is False and the directory does not exist, no extensions will be loaded. If this is True, aFileNotFoundError
is thrown if the directory does not exist. Defaults to False.
- Returns
None
- Raises
ExtensionAlreadyLoaded – If the extension has already been loaded.
ExtensionMissingLoad – If the extension to be loaded does not contain a
load
function.ExtensionNotFound – If the extension to be loaded does not exist.
FileNotFoundError – If the directory to load extensions from does not exist and
must_exist
is True.
- static print_banner(banner: Optional[str], allow_color: bool, force_color: bool) None ¶
Print the banner.
This allows library vendors to override this behaviour, or choose to inject their own “branding” on top of what hikari provides by default.
Normal users should not need to invoke this function, and can simply change the banner argument passed to the constructor to manipulate what is displayed.
- Parameters
banner (typing.Optional[builtins.str]) – The package to find a banner.txt in.
allow_color (builtins.bool) – A flag that allows advising whether to allow color if supported or not. Can be overridden by setting a “CLICOLOR” environment variable to a non-“0” string.
force_color (builtins.bool) – A flag that allows forcing color to always be output, even if the terminal device may not support it. Setting the “CLICOLOR_FORCE” environment variable to a non-“0” string will override this.
note (!!!) – force_color will always take precedence over allow_color.
- async process_commands_for_event(event: hikari.events.message_events.MessageCreateEvent) None ¶
Carries out all command and argument parsing, evaluates checks and ultimately invokes a command if the event passed is deemed to contain a command invocation.
It is not recommended that you override this method - if you do you should make sure that you know what you are doing.
- Parameters
event (
hikari.MessageCreateEvent
) – The event to process commands for.- Returns
None
- async purge_slash_commands(*guild_ids: Union[hikari.snowflakes.Snowflake, int], global_commands: bool = False) None ¶
Purges all slash commands from the guilds with the specified IDs, and all the global slash commands if
global_commands
isTrue
. Useful if you want to teardown old slash commands from the bot and cannot be bothered to fetch them individually yourself. If neither guild_ids nor global_commands is specified then this method will do nothing.- Parameters
*guild_ids (
hikari.Snowflakeish
) – IDs for the guilds to purge slash commands from.- Keyword Arguments
global_commands (
bool
) – Whether or not to purge global slash commands from the bot.- Returns
None
- reload_all_extensions() None ¶
Reload all bot extensions. This method is atomic and so the bot will revert to the previous loaded state if the extensions encounter problems during unloading or loading.
- Returns
None
- reload_extension(extension: str) None ¶
Reload a bot extension. This method is atomic and so the bot will revert to the previous loaded state if the extension encounters a problem during unloading or loading.
- Parameters
extension (
str
) – The name of the extension to be reloaded.- Returns
None
- reload_extensions(*extensions: str) None ¶
Reload multiple bot extensions. This method is atomic and so the bot will revert to the previous loaded state if the extensions encounter problems during unloading or loading.
- Parameters
*extensions (
*str
) – The name of the extension to be reloaded.- Returns
None
- remove_command(name: str) Optional[str] ¶
Remove a command from the bot and return its name or
None
if no command was removed.
- remove_plugin(name: str) Optional[str] ¶
Remove a plugin from the bot and return its name or
None
if no plugin was removed.
- remove_slash_command(name: str, delete: bool = False) Optional[str] ¶
Remove a slash command from the bot and return its name or
None
if no command was removed.
- async resolve_args_for_command(context: lightbulb.context.Context, command: lightbulb.commands.Command, raw_arg_string: str) Tuple[List[str], Dict[str, str]] ¶
Resolve the appropriate command arguments from an unparsed string containing the raw command arguments and attempt to convert them into the appropriate types given the type hint.
This method can be overridden if you wish to customise how arguments are parsed and converted for all the commands. If you override this then it is important that it at least returns a tuple containing an empty list if no positional arguments were resolved, and an empty dict if no keyword arguments were resolved.
If you override this method then you may find the
StringView
class useful for extracting the arguments from the raw string and the propertyarg_details
which contains information about the command’s arguments and which are optional or required.- Parameters
- Returns
- Positional and keyword
arguments the command should be invoked with.
- Return type
Tuple[ List[
str
], Dict[str1, :obj:`str
] ]- Raises
TooManyArguments – The command does not ignore extra arguments and too many arguments were supplied by the user.
NotEnoughArguments – Not enough arguments were provided by the user to fill all required argument fields.
ConverterFailure – Argument value conversion failed.
- async send_help(context: lightbulb.context.Context, obj: Optional[Union[lightbulb.commands.Command, lightbulb.plugins.Plugin]] = None) None ¶
Send help to the provided context to the specified object, or send the bot’s help overview if no object to send help for is supplied.
- unload_all_extensions() None ¶
Unload all external extensions from the bot. This method relies on a function,
unload
existing in all extensions which the bot will use to remove all commands and/or plugins from the bot.- Returns
None
- Raises
ExtensionNotLoaded – If the extension has not been loaded.
ExtensionMissingUnload – If the extension does not contain an
unload
function.
- unload_extension(extension: str) None ¶
Unload an external extension from the bot. This method relies on a function,
unload
existing in the extension which the bot will use to remove all commands and/or plugins from the bot.- Parameters
extension (
str
) – The name of the extension to unload.- Returns
None
- Raises
ExtensionNotLoaded – If the extension has not been loaded.
ExtensionMissingUnload – If the extension does not contain an
unload
function.ExtensionNotFound – If the extension to be unloaded does not exist.
Example
import lightbulb class MyPlugin(lightbulb.Plugin): ... def load(bot): bot.add_plugin(MyPlugin()) def unload(bot): bot.remove_plugin("MyPlugin")
- unload_extensions(*extensions: str) None ¶
Unload multiple external extensions from the bot. This method relies on a function,
unload
existing in the extensions to be unloaded which the bot will use to remove all commands and/or plugins from the bot.- Parameters
*extensions (
*str
) – The names of the extensions to unload.- Returns
None
- Raises
ExtensionNotLoaded – If the extension has not been loaded.
ExtensionMissingUnload – If the extension does not contain an
unload
function.ExtensionNotFound – If the extension to be unloaded does not exist.
- walk_commands() Generator[lightbulb.commands.Command, None, None] ¶
A generator that walks through all commands and subcommands registered to the bot.
- Yields
Command
– All commands, groups and subcommands registered to the bot.
- property app: Optional[hikari.guilds.PartialApplication]¶
The application instance for the bot. Will be
None
unless the bot is running.
- commands: typing.Set[commands.Command]¶
A set containing all commands and groups registered to the bot.
- default_enabled_guilds: typing.Iterable[int]¶
An iterable of the enabled guilds to use by default.
- extensions: typing.List[str]¶
A list of extensions currently loaded to the bot.
- property help_command: lightbulb.help.HelpCommand¶
The instance of the help class used by the bot.
- owner_ids: typing.Iterable[int]¶
Iterable of the bot’s owner IDs. This can be set by
Bot.fetch_owner_ids()
if not given in the constructor.
- plugins: typing.MutableMapping[str, plugins.Plugin]¶
A mapping of plugin name to plugin object currently added to the bot.
- slash_commands: typing.Set[typing.Union[slash_commands.SlashCommand, slash_commands.SlashCommandGroup]]¶
A set containing all slash commands registered to the bot.
- lightbulb.command_handler.when_mentioned_or(prefix_provider: Union[str, Iterable[str], Callable[[Bot, hikari.messages.Message], Union[Coroutine[None, None, Union[str, Iterable[str]]], str, Iterable[str]]]]) Callable[[lightbulb.command_handler.Bot, hikari.messages.Message], Coroutine[None, None, Iterable[str]]] ¶
Helper function which allows the bot’s mentions to be used as the command prefix, as well as any other prefix(es) passed in or supplied by the
prefix_provider
.- Parameters
prefix_provider – An object that is a prefix, contains prefixes, or returns prefixes.
Example
# The below are all valid bot = lightbulb.Bot(prefix=lightbulb.when_mentioned_or("!"), ...) bot = lightbulb.Bot(prefix=lightbulb.when_mentioned_or(["!", "?"]), ...) # Using only mentions as the prefix bot = lightbulb.Bot(prefix=lightbulb.when_mentioned_or(None), ...) # Using with a get_prefix function def get_prefix(bot, message): # Do something to get the prefixes return prefixes bot = lightbulb.Bot(prefix=lightbulb.when_mentioned_or(get_prefix), ...)
Commands¶
- class lightbulb.commands.Command(callback: Callable[[lightbulb.context.Context], Coroutine[None, None, None]], name: str, allow_extra_arguments: bool, aliases: Iterable[str], hidden: bool, parent: Optional[Any] = None)¶
Bases:
object
A command that can be invoked by a user. When invoked, the callback will be called with a set argument ctx, an instance of the
Context
class, and any other arguments supplied by the user.- Parameters
callback – The coroutine to register as the command’s callback.
name (
str
) – The name to register the command to.allow_extra_arguments (
bool
) – Whether or not the command should error when run with too many arguments.aliases (Iterable[
str
]) – Additional names to register the command to.hidden (
bool
) – Whether or not to show the command in the bot’s help overview.parent (Optional[
Group
]) – The parent group for the command, orNone
if the command has no parent.
- add_check(check_func: checks_.Check) None ¶
Add a check to an instance of
Command
or a subclass. The check passed must be an awaitable function taking a single argument which will be an instance ofContext
. It must also either return a boolean denoting whether or not the check passed, or raise an instance ofCheckFailure
or a subclass.- Parameters
check_func (
Check
) – Check to add to the command- Returns
None
Example
async def author_name_startswith_foo(ctx): return ctx.author.username.startswith("foo") bot.get_command("foo").add_check(Check(author_name_startswith_foo))
See also
check()
- after_invoke()¶
A decorator to register a coroutine to be run after the command is invoked.
The coroutine can take only one argument which will be an instance of the
Context
for the command.
- before_invoke()¶
A decorator to register a coroutine to be run before the command is invoked.
The coroutine can take only one argument which will be an instance of the
Context
for the command.
- command_error()¶
A decorator to register a coroutine as the command’s error handler. Any return from the error handler will be used to determine whether or not the error was handled successfully. A return of any truthy object will prevent the event from propagating further down the listener chain. Returning a falsy value will mean that any global command error listener will then be called.
The coroutine can only take one argument, which will be an instance of
CommandErrorEvent
unless in a class in which case it may also take theself
argument.Example
@lightbulb.check(lightbulb.owner_only) @bot.command() async def foo(ctx): await ctx.respond("bar") @foo.command_error() async def on_foo_error(event): # This will be called if someone other than the # bot's owner tries to run the command foo return
- async invoke(context: lightbulb.context.Context, *args: str, **kwargs: str) Any ¶
Invoke the command with given args and kwargs. Cooldowns and converters will be processed however this method bypasses all command checks.
- Parameters
context (
Context
) – The command invocation context.*args – The positional arguments to invoke the command with.
- Keyword Arguments
**kwargs – The keyword arguments to invoke the command with.
- async is_runnable(context: lightbulb.context.Context) bool ¶
Run all the checks for the command to determine whether or not it is runnable in the given context.
- property aliases: Iterable[str]¶
The command’s aliases.
- Returns
Aliases for the command.
- Return type
Iterable[
str
]
- property arg_details: lightbulb.commands.SignatureInspector¶
An inspection of the arguments that a command takes.
- Returns
Details about the command’s arguments.
- Return type
- bot_required_permissions: hikari.Permissions¶
The permissions the bot requires for a user to be able to run the command. These are extracted from the permission check decorator(s) on the command.
- property callback: Callable¶
The command’s callback coroutine
- Returns
The callback coroutine for the command
- Return type
Callable
- property checks: Iterable[Callable[[lightbulb.context.Context], bool]]¶
The command’s checks.
- cooldown_manager: typing.Optional[cooldowns.CooldownManager]¶
The cooldown manager being used for the command. If
None
then the command does not have a cooldown.
- parent: typing.Optional[Group]¶
The parent group for the command. If
None
then the command is not a subcommand.
- property plugin: typing.Optional[plugins.Plugin]¶
The plugin the command is registered to. If
None
then it was defined outside of a plugin.
- property qualified_name: str¶
The fully qualified name of the command, taking into account whether or not the command is a subcommand.
- Returns
Qualified name of the command.
- Return type
- user_required_permissions: hikari.Permissions¶
The permissions required by a user to run the command. These are extracted from the permission check decorator(s) on the command.
- class lightbulb.commands.Group(*args, insensitive_commands: bool = False, inherit_checks: bool = True, **kwargs)¶
Bases:
lightbulb.commands.Command
A command group. This is invoked the same way as a normal command, however it has support for subcommands which can be registered to the group and invoked as separate commands.
- Parameters
*args – The args passed to
Command
in its constructor- Keyword Arguments
- add_check(check_func: checks_.Check) None ¶
Add a check to an instance of
Command
or a subclass. The check passed must be an awaitable function taking a single argument which will be an instance ofContext
. It must also either return a boolean denoting whether or not the check passed, or raise an instance ofCheckFailure
or a subclass.- Parameters
check_func (
Check
) – Check to add to the command- Returns
None
Example
async def author_name_startswith_foo(ctx): return ctx.author.username.startswith("foo") bot.get_command("foo").add_check(Check(author_name_startswith_foo))
See also
check()
- command(**kwargs)¶
A decorator that registers a callable as a subcommand for the command group.
- Keyword Arguments
**kwargs – Kwargs passed to
command
Example
bot = lightbulb.Bot(token="token_here", prefix="!") @bot.group() async def foo(ctx): await ctx.respond("Invoked foo") @foo.command() async def bar(ctx): await ctx.respond("Invoked foo bar")
- get_subcommand(name: str) lightbulb.commands.Command ¶
Get a command object for a subcommand of the group from it’s registered name.
- group(**kwargs)¶
A decorator that registers a callable as a subgroup for the command group.
- Keyword Arguments
**kwargs – Kwargs passed to
group
- walk_commands() Generator[lightbulb.commands.Command, None, None] ¶
A generator that walks through all commands and subcommands registered to this group.
- Yields
Command
– All commands, groups and subcommands registered to this group.
- property plugin: typing.Optional[plugins.Plugin]¶
The plugin the command is registered to. If
None
then it was defined outside of a plugin.
- subcommands: typing.Set[Command]¶
A set containing all subcommands registered to the group.
- class lightbulb.commands.SignatureInspector(command: lightbulb.commands.Command)¶
Bases:
object
Contains information about the arguments that a command takes when it is invoked.
- Parameters
command (
Command
) – The command to inspect the arguments of.
- get_converter(annotation) Union[lightbulb.converters._BaseConverter[lightbulb.commands.T], lightbulb.converters._BaseConverter[List[lightbulb.commands.T]]] ¶
Resolve the converter order for a given type annotation recursively.
- Parameters
annotation – The parameter’s type annotation.
- Returns
The top level converter for the parameter
- parse_signature(callback, signature: inspect.Signature)¶
Parse the command’s callback signature into a list of the converters used for each command argument.
- Parameters
callback – The command’s callback
signature (
inspect.Signature
) – The signature of the command callback.
- Returns
List of converters for command arguments in the correct order.
- lightbulb.commands.command(**kwargs)¶
A decorator to convert a coroutine into a
Command
object.- Keyword Arguments
name (Optional[
str
]) – Name to register the command to. Defaults to the name of the coroutine.allow_extra_arguments (Optional[
bool
]) – Whether or not the command should error when run with more arguments than it takes. Defaults to True - will not raise an error.aliases (Iterable[
str
]) – Iterable of aliases which will also invoke the command.hidden (
bool
) – Whether or not the command should be hidden from the help command. Defaults toFalse
.cls (
Command
) – The class to use to instantiate the command object from. Defaults toCommand
.
- lightbulb.commands.group(**kwargs)¶
A decorator to convert a coroutine into a
Group
object.- Keyword Arguments
name (Optional[
str
]) – Name to register the command to. Defaults to the name of the coroutine.allow_extra_arguments (Optional[
bool
]) – Whether or not the command should error when run with more arguments than it takes. Defaults to True - will not raise an error.aliases (Optional[ Iterable[
str
] ]) – Iterable of aliases which will also invoke the command.hidden (
bool
) – Whether or not the command should be hidden from the help command. Defaults toFalse
.insensitive_commands (
bool
) – Whether or not subcommands should be case-insensitive. Defaults to False.cls (
Command
) – The class to use to instantiate the group object from. Defaults toGroup
.inherit_checks (
bool
) – Whether or not subcommands should inherit checks added to the base group.
- lightbulb.commands.typing_override(ns: Dict[str, Any])¶
Add additional assistance to
typing.get_type_hints
for when command signatures cannot be resolved correctly. This can be called as a function or used as a decorator.Most users should never run into this problem.
- Parameters
ns (Dict[
str
,typing.Any
) – Dictionary of string annotation name/symbol to the object that the annotation should be resolved into.
Plugins¶
- class lightbulb.plugins.EventListenerDescriptor(event_type: Optional[Type[lightbulb.plugins.EventT_co]], callback: Callable[[Any, lightbulb.plugins.EventT_co], Coroutine[Any, Any, None]])¶
Descriptor for a listener.
This provides the same introspective logic as
hikari.GatewayBot.listen()
, but does so using a descriptor instead of directly subscribing the function. This is detected when loading plugins as a way of defining event listeners within plugins lazily.It may either consume an explicit event type, or introspect the given callback to get the type hint on the given callback for the event parameter after self.
This will only work with instance-method style classes.
- class lightbulb.plugins.Plugin(*, name: Optional[str] = None)¶
Independent class that can be loaded and unloaded from the bot to allow for hot-swapping of commands.
To use in your own bot you should subclass this for each plugin you wish to create. Don’t forget to call
super().__init__()
if you override the__init__
method.- Parameters
name (Optional[
str
]) – The name to register the plugin under. If unspecified will be the class name.
Example
import lightbulb bot = lightbulb.Bot(...) class MyPlugin(lightbulb.Plugin): @lightbulb.command() async def ping(self, ctx): await ctx.respond("Pong!") bot.add_plugin(MyPlugin())
- commands¶
A set containing all commands and groups registered to the plugin.
- listeners: MutableMapping[Type[hikari.events.base_events.Event], MutableSequence[lightbulb.plugins.EventListenerDescriptor]]¶
Mapping of event to a listener method containing all listeners registered to the plugin.
- name¶
The plugin’s registered name.
- async plugin_check(context: lightbulb.context.Context) bool ¶
A check method called for only the commands inside the plugin.
This method must be a coroutine and return a boolean-like value or raise an error when called.
- plugin_remove() None ¶
A method that will be called just before the plugin is removed from the bot. This method cannot be a coroutine, it must be a regular function.
You may with use this for any cleanup that the plugin may require.
- walk_commands() Generator[lightbulb.commands.Command, None, None] ¶
A generator that walks through all commands, groups and subcommands registered to this plugin.
- Yields
Command
– All commands, groups and subcommands registered to this plugin.
- lightbulb.plugins.listener(event_type: Optional[Type[lightbulb.plugins.EventT_co]] = None) Callable[[lightbulb.plugins.T], lightbulb.plugins.EventListenerDescriptor] ¶
A decorator that registers a plugin method as an event listener.
- Parameters
event_type (Optional[
hikari.Event
]) – The event to listen to. If unspecified then it will be inferred from the method’s typehint.
Example
import lightbulb import hikari class TestPlugin(lightbulb.Plugin): @plugins.listener(hikari.MessageCreateEvent) async def print_message(self, event): print(event.message.content)
Checks¶
Error
Note that all check decorators must be above the command decorator otherwise your code will not work.
- class lightbulb.checks.Check(predicate: Callable[[Union[lightbulb.context.Context, lightbulb.slash_commands.context.SlashCommandContext]], Union[Coroutine[None, None, bool], bool]], *, slash_command_predicate: Optional[Callable[[lightbulb.slash_commands.context.SlashCommandContext], Union[Coroutine[None, None, bool], bool]]] = None, add_to_command_hook: Optional[Callable[[lightbulb.commands.Command], None]] = None)¶
Class representing a check for both message and slash commands.
- Parameters
predicate – Check predicate function for both message and slash commands. Must return a boolean or raise an error.
- Keyword Arguments
slash_command_predicate – If provided, an alternative predicate function to use for slash commands. Defaults to the same function as
predicate
.add_to_command_hook – A function to run when the check is added to the command. Must take a single argument, which will be the command object that the check is added to. This hook is not run for slash commands.
- lightbulb.checks.dm_only: Check = <lightbulb.checks.Check object>¶
Prevents a command from being used in a guild. This check supports slash commands.
- lightbulb.checks.guild_only: Check = <lightbulb.checks.Check object>¶
Prevents a command from being used in direct messages. This check supports slash commands.
- lightbulb.checks.owner_only: Check = <lightbulb.checks.Check object>¶
Prevents a command from being used by anyone other than the owner of the application. This check supports slash commands.
- lightbulb.checks.bot_only: Check = <lightbulb.checks.Check object>¶
Prevents a command from being used by anyone other than a bot.
- lightbulb.checks.webhook_only: Check = <lightbulb.checks.Check object>¶
Prevents a command from being used by anyone other than a webhook.
- lightbulb.checks.human_only: Check = <lightbulb.checks.Check object>¶
Prevents a command from being used by anyone other than a human.
- lightbulb.checks.has_roles(role1: snowflakes.SnowflakeishOr[hikari.PartialRole], *role_ids: snowflakes.SnowflakeishOr[hikari.PartialRole], mode: typing.Literal['all', 'any'] = 'all') Check ¶
Prevents a command from being used by anyone missing roles according to the given mode. This check supports slash commands.
- Parameters
role1 (
SnowflakeishOr
[PartialRole
]) – Role ID to check for.*role_ids (
SnowflakeishOr
[PartialRole
]) – Additional role IDs to check for.
- Keyword Arguments
mode (Literal["all", "any"]) – The mode to check roles using. If
"all"
, all role IDs passed will be required. If"any"
, the invoker will only be required to have one of the specified roles. Defaults to"all"
.
Example
@lightbulb.check(lightbulb.has_roles(123, 456, 789)) @bot.command() async def foo(ctx): ...
Note
This check will also prevent commands from being used in DMs, as you cannot have roles in a DM channel.
- lightbulb.checks.has_guild_permissions(perm1: hikari.permissions.Permissions, *permissions: hikari.permissions.Permissions) lightbulb.checks.Check ¶
Prevents the command from being used by a member missing any of the required guild permissions (this takes into account both role permissions and channel overwrites, where channel overwrites take priority). This check supports slash commands.
- Parameters
perm1 (
hikari.Permissions
) – Permission to check for.*permissions (
hikari.Permissions
) – Additional permissions to check for.
Note
This check will also prevent commands from being used in DMs, as you cannot have permissions in a DM channel.
Warning
This check is unavailable if your application is stateless and/or missing the intent
hikari.Intents.GUILDS
and will always raise an error on command invocation if either of these conditions are not met.
- lightbulb.checks.bot_has_guild_permissions(perm1: hikari.permissions.Permissions, *permissions: hikari.permissions.Permissions) lightbulb.checks.Check ¶
Prevents the command from being used if the bot is missing any of the required guild permissions (this takes into account both role permissions and channel overwrites).
- Parameters
perm1 (
hikari.Permissions
) – Permission to check for.*permissions (
hikari.Permissions
) – Additional permissions to check for.
Note
This check will also prevent commands from being used in DMs, as you cannot have permissions in a DM channel.
Warning
This check is unavailable if your application is stateless and/or missing the intent
hikari.Intents.GUILDS
and will always raise an error on command invocation if either of these conditions are not met.
- lightbulb.checks.has_role_permissions(perm1: hikari.permissions.Permissions, *permissions: hikari.permissions.Permissions) lightbulb.checks.Check ¶
Prevents the command from being used by a member missing any of the required role permissions.
- Parameters
perm1 (
hikari.Permissions
) – Permission to check for.*permissions (
hikari.Permissions
) – Additional permissions to check for.
Note
This check will also prevent commands from being used in DMs, as you cannot have permissions in a DM channel.
Warning
This check is unavailable if your application is stateless and/or missing the intent
hikari.Intents.GUILDS
and will always raise an error on command invocation if either of these conditions are not met.
- lightbulb.checks.bot_has_role_permissions(perm1: hikari.permissions.Permissions, *permissions: hikari.permissions.Permissions) lightbulb.checks.Check ¶
Prevents the command from being used if the bot is missing any of the required role permissions.
- Parameters
perm1 (
hikari.Permissions
) – Permission to check for.*permissions (
hikari.Permissions
) – Additional permissions to check for.
Note
This check will also prevent commands from being used in DMs, as you cannot have permissions in a DM channel.
Warning
This check is unavailable if your application is stateless and/or missing the intent
hikari.Intents.GUILDS
and will always raise an error on command invocation if either of these conditions are not met.
- lightbulb.checks.has_channel_permissions(perm1: hikari.permissions.Permissions, *permissions: hikari.permissions.Permissions) lightbulb.checks.Check ¶
Prevents the command from being used by a member missing any of the required channel permissions (permissions granted by a permission overwrite).
- Parameters
perm1 (
hikari.Permissions
) – Permission to check for.*permissions (
hikari.Permissions
) – Additional permissions to check for.
Note
This check will also prevent commands from being used in DMs, as you cannot have permissions in a DM channel.
Warning
This check is unavailable if your application is stateless and/or missing the intent
hikari.Intents.GUILDS
and will always raise an error on command invocation if either of these conditions are not met.
- lightbulb.checks.bot_has_channel_permissions(perm1: hikari.permissions.Permissions, *permissions: hikari.permissions.Permissions) lightbulb.checks.Check ¶
Prevents the command from being used if the bot is missing any of the required channel permissions (permissions granted by a permission overwrite).
- Parameters
perm1 (
hikari.Permissions
) – Permission to check for.*permissions (
hikari.Permissions
) – Additional permissions to check for.
Note
This check will also prevent commands from being used in DMs, as you cannot have permissions in a DM channel.
Warning
This check is unavailable if your application is stateless and/or missing the intent
hikari.Intents.GUILDS
and will always raise an error on command invocation if either of these conditions are not met.
- lightbulb.checks.has_attachment(*extensions: str) lightbulb.checks.Check ¶
Prevents the command from being used if the invocation message does not include any attachments.
- Parameters
*extensions (
str
) – If specified, attachments with a different file extension will cause the check to fail.
Example
@lightbulb.check(lightbulb.has_attachment(".yaml", ".json")) @bot.command() async def foobar(ctx): print(ctx.attachments[0].filename)
Note
If
extensions
is specified then all attachments must conform to the restriction.
- lightbulb.checks.check(check_func: Union[lightbulb.checks.Check, Callable[[Union[lightbulb.context.Context, lightbulb.slash_commands.context.SlashCommandContext]], Union[Coroutine[None, None, bool], bool]]]) Callable[[lightbulb.checks.T_inv], lightbulb.checks.T_inv] ¶
A decorator which adds a check function to a command. The check function can be a coroutine (async def) and must take a single argument, which will be the command context.
This acts as a shortcut to calling
add_check()
on a command instance.- Parameters
check_func (Union[
Check
, Callable[[Context
], Union[Coroutine[Any, Any,bool
],bool
]]) – The function, coroutine or Check object to add to the command as a check.
Example
async def check_message_contains_hello(ctx): return "hello" in ctx.message.content @checks.check(check_message_contains_hello) @bot.command() async def foo(ctx): await ctx.respond("Bar")
See also
- lightbulb.checks.check_exempt(predicate: Callable[[Union[lightbulb.context.Context, lightbulb.slash_commands.context.SlashCommandContext]], Union[Coroutine[None, None, bool], bool]]) Callable[[lightbulb.checks.T_inv], lightbulb.checks.T_inv] ¶
A decorator which allows all checks to be bypassed if the
predicate
conditions are met. Predicate can be a coroutine or a normal function but must take a single argument -context
- and must return a boolean -True
if checks should be bypassed orFalse
if not.- Parameters
predicate – The callable which determines if command checks should be bypassed or not.
Example
@checks.check_exempt(lambda ctx: ctx.author.id == 1234) @checks.guild_only() @bot.command() async def foo(ctx): await ctx.respond("foo")
Context¶
- class lightbulb.context.Context(bot: command_handler.Bot, message: hikari.Message, prefix: str, invoked_with: str, command: commands.Command)¶
The context a command was invoked under.
- Parameters
bot (
Bot
) – The bot instance that received the command.message (
hikari.messages.Message
) – The message the context was created from.prefix (
str
) – The prefix used in the context.invoked_with (
str
) – The name or alias used to invoke a command.command (
Command
) – The command that was invoked.
Note
For information on types for the various properties see
hikari.messages.Message
.- get_channel() Optional[hikari.channels.TextableChannel] ¶
The cached
hikari.TextableChannel
instance for the context’s channel ID.This will be None if the bot is stateless, the channel is not found in the cache, or the context is for a command run in DMs.
- get_guild() Optional[hikari.guilds.Guild] ¶
The cached
hikari.Guild
instance for the context’s guild ID.This will be None if the bot is stateless, the guild is not found in the cache, or the context is for a command run in DMs.
- async respond(content: undefined.UndefinedOr[typing.Any] = UNDEFINED, *, attachment: undefined.UndefinedOr[files.Resourceish] = UNDEFINED, attachments: undefined.UndefinedOr[typing.Sequence[files.Resourceish]] = UNDEFINED, component: undefined.UndefinedOr[special_endpoints.ComponentBuilder] = UNDEFINED, components: undefined.UndefinedOr[typing.Sequence[special_endpoints.ComponentBuilder]] = UNDEFINED, embed: undefined.UndefinedOr[embeds_.Embed] = UNDEFINED, embeds: undefined.UndefinedOr[typing.Sequence[embeds_.Embed]] = UNDEFINED, nonce: undefined.UndefinedOr[str] = UNDEFINED, tts: undefined.UndefinedOr[bool] = UNDEFINED, reply: typing.Union[undefined.UndefinedType, snowflakes.SnowflakeishOr[PartialMessage], bool] = UNDEFINED, mentions_everyone: undefined.UndefinedOr[bool] = UNDEFINED, mentions_reply: undefined.UndefinedOr[bool] = UNDEFINED, user_mentions: undefined.UndefinedOr[typing.Union[snowflakes.SnowflakeishSequence[users_.PartialUser], bool]] = UNDEFINED, role_mentions: undefined.UndefinedOr[typing.Union[snowflakes.SnowflakeishSequence[guilds.PartialRole], bool]] = UNDEFINED) Message ¶
Create a message in the channel this message belongs to.
- Parameters
content (hikari.undefined.UndefinedOr[typing.Any]) –
If provided, the message contents. If hikari.undefined.UNDEFINED, then nothing will be sent in the content. Any other value here will be cast to a builtins.str.
If this is a hikari.embeds.Embed and no embed nor embeds kwarg is provided, then this will instead update the embed. This allows for simpler syntax when sending an embed alone.
Likewise, if this is a hikari.files.Resource, then the content is instead treated as an attachment if no attachment and no attachments kwargs are provided.
attachment (hikari.undefined.UndefinedOr[hikari.files.Resourceish],) – If provided, the message attachment. This can be a resource, or string of a path on your computer or a URL.
attachments (hikari.undefined.UndefinedOr[typing.Sequence[hikari.files.Resourceish]],) – If provided, the message attachments. These can be resources, or strings consisting of paths on your computer or URLs.
component (hikari.undefined.UndefinedOr[hikari.api.special_endpoints.ComponentBuilder]) – If provided, builder object of the component to include in this message.
components (hikari.undefined.UndefinedOr[typing.Sequence[hikari.api.special_endpoints.ComponentBuilder]]) – If provided, a sequence of the component builder objects to include in this message.
embed (hikari.undefined.UndefinedOr[hikari.embeds.Embed]) – If provided, the message embed.
embeds (hikari.undefined.UndefinedOr[typing.Sequence[hikari.embeds.Embed]]) – If provided, the message embeds.
tts (hikari.undefined.UndefinedOr[builtins.bool]) – If provided, whether the message will be TTS (Text To Speech).
nonce (hikari.undefined.UndefinedOr[builtins.str]) – If provided, a nonce that can be used for optimistic message sending.
reply (typing.Union[hikari.undefined.UndefinedType, hikari.snowflakes.SnowflakeishOr[hikari.messages.PartialMessage], builtins.bool]) – If provided and builtins.True, reply to this message. If provided and not builtins.bool, the message to reply to.
mentions_everyone (hikari.undefined.UndefinedOr[builtins.bool]) – If provided, whether the message should parse @everyone/@here mentions.
mentions_reply (hikari.undefined.UndefinedOr[builtins.bool]) –
If provided, whether to mention the author of the message that is being replied to.
This will not do anything if not being used with reply.
user_mentions (hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.users.PartialUser], builtins.bool]]) – If provided, and builtins.True, all mentions will be parsed. If provided, and builtins.False, no mentions will be parsed. Alternatively this may be a collection of hikari.snowflakes.Snowflake, or hikari.users.PartialUser derivatives to enforce mentioning specific users.
role_mentions (hikari.undefined.UndefinedOr[typing.Union[hikari.snowflakes.SnowflakeishSequence[hikari.guilds.PartialRole], builtins.bool]]) – If provided, and builtins.True, all mentions will be parsed. If provided, and builtins.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.
note (!!!) –
Attachments can be passed as many different things, to aid in convenience.
- If a pathlib.PurePath or builtins.str to a valid URL, the
resource at the given URL will be streamed to Discord when sending the message. Subclasses of hikari.files.WebResource such as hikari.files.URL, hikari.messages.Attachment, hikari.emojis.Emoji, EmbedResource, etc will also be uploaded this way. This will use bit-inception, so only a small percentage of the resource will remain in memory at any one time, thus aiding in scalability.
- If a hikari.files.Bytes is passed, or a builtins.str
that contains a valid data URI is passed, then this is uploaded with a randomized file name if not provided.
- If a hikari.files.File, pathlib.PurePath or
builtins.str that is an absolute or relative path to a file on your file system is passed, then this resource is uploaded as an attachment using non-blocking code internally and streamed using bit-inception where possible. This depends on the type of concurrent.futures.Executor that is being used for the application (default is a thread pool which supports this behaviour).
- Returns
The created message.
- Return type
- Raises
hikari.errors.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; reply not found or not in the same channel; too many components.
hikari.errors.UnauthorizedError – If you are unauthorized to make the request (invalid/missing token).
hikari.errors.ForbiddenError – If you lack permissions to send messages in the given channel.
hikari.errors.NotFoundError – If the channel is not found.
hikari.errors.InternalServerError – If an internal error occurs on Discord while handling the request.
builtins.ValueError – If more than 100 unique objects/entities are passed for role_mentions or user_mentions.
builtins.TypeError – If both attachment and attachments are specified.
- async send_help(obj: typing.Union[commands.Command, plugins.Plugin] = None) None ¶
Send help for the given object or the bot’s help overview if no object is supplied to the current context.
- property attachments: Sequence[hikari.messages.Attachment]¶
The attachments to the context message.
- property author: hikari.users.User¶
The user who invoked the command.
- property channel_id: hikari.snowflakes.Snowflake¶
ID of the channel the command was invoked in.
- property clean_prefix: str¶
The context’s prefix, cleaned to remove user mentions. If the bot is stateless, then this just returns the raw prefix.
- property edited_timestamp: Optional[datetime.datetime]¶
Optional timestamp of the previous edit of the context message.
- property guild_id: Optional[hikari.snowflakes.Snowflake]¶
ID of the guild the command was invoked in, or None if the command was invoked in DMs.
- property member: Optional[hikari.guilds.Member]¶
Optional member corresponding to the context author.
- property mentions: hikari.messages.Mentions¶
The mentions that exist in the message that triggered the command.
- property message_id: hikari.snowflakes.Snowflake¶
ID of the message that invoked the command.
- property timestamp: datetime.datetime¶
The timestamp the context message was sent at.
Converters¶
Lightbulb will attempt to convert command arguments using the type or function specified by the type hints of each argument. By default, any types that can be converted to from a string are supported - eg int or float.
Example:
@bot.command()
async def to_int(ctx, number: int):
await ctx.respond(f"{number}, {type(number)}")
# If ran with the argument "10"
# The output would be: 10, <class 'int'>
Supplied in this module are further utility functions that can be specified as type hints in order to convert arguments into more complex types - eg member or channel objects.
You can also write your own converters. A converter can be any callable and should take a single argument, which
will be an instance of the WrappedArg
class. The arg value and command invocation
context can be accessed through this instance from the attributes data
and context
respectively.
Hikari classes are also available as type hints in place of the lightbulb converters and will be internally converted into the necessary converter for the command to behave as expected. A list of all available classes along with the converters they ‘replace’ can be seen below:
hikari.User
(user_converter
)hikari.Member
(member_converter
)hikari.TextableChannel
(text_channel_converter
)hikari.GuildVoiceChannel
(guild_voice_channel_converter
)hikari.GuildCategory
(category_converter
)hikari.Role
(role_converter
)hikari.Emoji
(emoji_converter
)hikari.GuildPreview
(guild_converter
)hikari.Message
(message_converter
)hikari.Invite
(invite_converter
)hikari.Colour
(colour_converter
)hikari.Color
(color_converter
)
Warning
For the supplied converters, some functionality will not be possible depending on the intents and/or cache settings of your bot application and object. If the bot does not have a cache then the converters can only work for arguments of ID or mention and not any form of name.
- class lightbulb.converters.WrappedArg(seq: str, context: lightbulb.context.Context)¶
Bases:
collections.UserString
A wrapped command argument containing the invocation context of the command for which the argument is to be converted under, accessible through the
context
attribute.This class acts like a string so any operations that will work on a string will also work on this class.
The raw string argument can be accessed through the
data
attribute.
- async lightbulb.converters.user_converter(arg: lightbulb.converters.WrappedArg) hikari.users.User ¶
Converter to transform a command argument into a
hikari.UserImpl
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The user object resolved from the argument.
- Return type
hikari.UserImpl
- Raises
ConverterFailure – If the argument could not be resolved into a user object.
Example
@bot.command() async def username(ctx, user: lightbulb.user_converter): await ctx.respond(user.username)
- async lightbulb.converters.member_converter(arg: lightbulb.converters.WrappedArg) hikari.guilds.Member ¶
Converter to transform a command argument into a
Member
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The member object resolved from the argument.
- Return type
Member
- Raises
ConverterFailure – If the argument could not be resolved into a member object.
- async lightbulb.converters.text_channel_converter(arg: lightbulb.converters.WrappedArg) hikari.channels.TextableChannel ¶
Converter to transform a command argument into a
TextableChannel
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The channel object resolved from the argument.
- Return type
hikari.TextableChannel
- Raises
ConverterFailure – If the argument could not be resolved into a channel object.
- async lightbulb.converters.guild_voice_channel_converter(arg: lightbulb.converters.WrappedArg) hikari.channels.GuildVoiceChannel ¶
Converter to transform a command argument into a
GuildVoiceChannel
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The channel object resolved from the argument.
- Return type
GuildVoiceChannel
- Raises
ConverterFailure – If the argument could not be resolved into a channel object.
- async lightbulb.converters.category_converter(arg: lightbulb.converters.WrappedArg) hikari.channels.GuildCategory ¶
Converter to transform a command argument into a
GuildCategory
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The category object resolved from the argument.
- Return type
GuildCategory
- Raises
ConverterFailure – If the argument could not be resolved into a category object.
- async lightbulb.converters.role_converter(arg: lightbulb.converters.WrappedArg) hikari.guilds.Role ¶
Converter to transform a command argument into a
Role
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The role object resolved from the argument.
- Return type
Role
- Raises
ConverterFailure – If the argument could not be resolved into a role object.
- async lightbulb.converters.emoji_converter(arg: lightbulb.converters.WrappedArg) hikari.emojis.Emoji ¶
Converter to transform a command argument into a
Emoji
object.Note that this does not validate unicode emojis to ensure they are defined as standard emojis. See https://github.com/nekokatt/hikari/issues/270 for discussion on supporting this.
- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The emoji object resolved from the argument.
- Return type
Emoji
- Raises
ConverterFailure – If the argument could not be resolved into an emoji object.
- async lightbulb.converters.guild_converter(arg: lightbulb.converters.WrappedArg) hikari.guilds.GuildPreview ¶
Converter to transform a command argument into a
Guild
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The guild object resolved from the argument.
- Return type
Guild
- Raises
ConverterFailure – If the argument could not be resolved into a guild object.
- async lightbulb.converters.message_converter(arg: lightbulb.converters.WrappedArg) hikari.messages.Message ¶
Converter to transform a command argument into a
Message
object. Note that this converter will only return messages from the same context that the command was invoked from, that is to say the channel ID of the command invocation and the fetched message must be the same.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The message object resolved from the argument.
- Return type
Message
- Raises
ConverterFailure – If the argument could not be resolved into a message object.
- async lightbulb.converters.invite_converter(arg: lightbulb.converters.WrappedArg) hikari.invites.Invite ¶
Converter to transform a command argument into an
Invite
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The invite object resolved from the argument.
- Return type
Invite
- Raises
ConverterFailure – If the argument could not be resolved into an invite object.
- async lightbulb.converters.colour_converter(arg: lightbulb.converters.WrappedArg) hikari.colors.Color ¶
Converter to transform a command argument into a
Colour
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The colour object resolved from the argument.
- Return type
Colour
- Raises
ConverterFailure – If the argument could not be resolved into a colour object.
- async lightbulb.converters.color_converter(arg: lightbulb.converters.WrappedArg) hikari.colors.Color ¶
Alias for
colour_converter
- async lightbulb.converters.timestamp_converter(arg: lightbulb.converters.WrappedArg) datetime.datetime ¶
Converter to transform a command argument into a
datetime.datetime
object.- Parameters
arg (
WrappedArg
) – Argument to transform.- Returns
The datetime object resolved from the argument.
- Return type
- Raises
ConverterFailure – If the argument could not be resolved into a datetime object.
- class lightbulb.converters.Greedy(*args, **kwds)¶
Bases:
Generic
[lightbulb.converters.T
]A special converter that greedily consumes arguments until it either runs out of arguments, or a parser error is encountered. Due to this behaviour, most input errors will be silently ignored.
Example
@bot.command() async def foo(ctx, foo: Greedy[int]): # if called with <p>foo 1 2 3 4 5 # then the arg foo would contain [1, 2, 3, 4, 5] ...
Cooldowns¶
- class lightbulb.cooldowns.CooldownStatus(value: Any)¶
Bases:
int
,hikari.internal.enums.Enum
The status of a cooldown bucket
- EXPIRED = <CooldownStatus.EXPIRED: 0>¶
The cooldown bucket has expired
- INACTIVE = <CooldownStatus.INACTIVE: 1>¶
The cooldown bucket timer has not been activated yet
- ACTIVE = <CooldownStatus.ACTIVE: 2>¶
The cooldown bucket timer is currently active
- property value¶
Return the value of the enum member.
- class lightbulb.cooldowns.Bucket(length: float, max_usages: int)¶
Bases:
abc.ABC
Base class for representing a cooldown bucket. All buckets should inherit from this class.
- Parameters
- commands_run¶
Commands run for this bucket since it was created.
- start_time¶
The start time of the bucket cooldown. This is relative to
time.perf_counter()
.
- abstract classmethod extract_hash(context: typing.Union[context_.Context, slash_context.SlashCommandContext]) typing.Hashable ¶
Extracts the hash from the context which links a command usage to a single cooldown bucket.
- :param context (Union[
Context
: obj:`~.slash_commands.SlashCommandContext]): The context the command was invoked under.
- :paramobj:`~.slash_commands.SlashCommandContext]): The context the
command was invoked under.
- Returns
Hashable object linking the context to a cooldown bucket.
- Return type
- :param context (Union[
- acquire() lightbulb.cooldowns.CooldownStatus ¶
Get the current state of the cooldown and add a command usage if the cooldown is not currently active or has expired.
- Returns
The status of the cooldown bucket.
- Return type
- class lightbulb.cooldowns.GlobalBucket(length: float, max_usages: int)¶
Bases:
lightbulb.cooldowns.Bucket
Global cooldown bucket. All cooldowns will be applied globally if you use this bucket.
- class lightbulb.cooldowns.UserBucket(length: float, max_usages: int)¶
Bases:
lightbulb.cooldowns.Bucket
User cooldown bucket. All cooldowns will be applied per user if you use this bucket.
- class lightbulb.cooldowns.ChannelBucket(length: float, max_usages: int)¶
Bases:
lightbulb.cooldowns.Bucket
Channel cooldown bucket. All cooldowns will be applied per channel if you use this bucket.
- class lightbulb.cooldowns.GuildBucket(length: float, max_usages: int)¶
Bases:
lightbulb.cooldowns.Bucket
Guild cooldown bucket. All cooldowns will be applied per guild if you use this bucket. The command will still be permitted to be run in DMs in which case the DM channel ID will be used as the cooldown identifier instead of a guild ID.
- class lightbulb.cooldowns.CooldownManager(length: float, usages: int, bucket: Type[lightbulb.cooldowns.Bucket])¶
- class lightbulb.cooldowns.CooldownManager(*, callback: typing.Callable[[typing.Union[context_.Context, slash_context.SlashCommandContext]], Bucket])
Bases:
object
The cooldown manager for a command.
- Parameters
- cooldowns: MutableMapping[Hashable, lightbulb.cooldowns.Bucket]¶
Mapping of a hashable to a
Bucket
representing the currently stored cooldowns.
- async add_cooldown(context: typing.Union[context_.Context, slash_context.SlashCommandContext]) None ¶
Add a cooldown under the given context. If an expired bucket already exists then it will be overwritten.
- :param context (Union[
Context
: obj:`~.slash_commands.SlashCommandContext]): The context to add a cooldown under.
- :paramobj:`~.slash_commands.SlashCommandContext]): The context to
add a cooldown under.
- Returns
None
- :param context (Union[
- reset_cooldown(context: typing.Union[context_.Context, slash_context.SlashCommandContext]) None ¶
Reset the cooldown under the given context.
- :param context (Union[
Context
: obj:`~.slash_commands.SlashCommandContext]): The context to reset the cooldown under.
- :paramobj:`~.slash_commands.SlashCommandContext]): The context to reset
the cooldown under.
- Returns
None
- :param context (Union[
- lightbulb.cooldowns.cooldown(length: float, usages: int, bucket: Type[lightbulb.cooldowns.Bucket], *, manager_cls: Type[lightbulb.cooldowns.CooldownManager] = <class 'lightbulb.cooldowns.CooldownManager'>)¶
Decorator which adds a cooldown to a command.
- Parameters
- Keyword Arguments
manager_cls (Type[
CooldownManager
]) – The uninstantiated class to use as the command’s cooldown manager. Defaults toCooldownManager
.
Example
@lightbulb.cooldown(10, 1, lightbulb.UserBucket) @bot.command() async def ping(ctx): await ctx.respond("Pong!")
This would make it so that each user can only use the
ping
command once every ten seconds.
- lightbulb.cooldowns.dynamic_cooldown(callback: typing.Callable[[context_.Context], Bucket], *, manager_cls: typing.Type[CooldownManager] = <class 'lightbulb.cooldowns.CooldownManager'>)¶
Decorator which adds a more customized cooldown to a command.
- Parameters
callback (Callable[[
Context
],Bucket
]) – The callback that takes a Context object and returns a Bucket object.- Keyword Arguments
manager_cls (Type[
CooldownManager
]) – The uninstantiated class to use as the command’s cooldown manager. Defaults toCooldownManager
.
Example
def callback(ctx): if ctx.author.id in ctx.bot.owner_ids: return lightbulb.UserBucket(0, 1) return lightbulb.UserBucket(10, 1) @lightbulb.dynamic_cooldown(callback) @bot.command() async def ping(ctx): await ctx.respond("Pong!")
This would make it so that owners bypass the cooldown and general users can only use the
ping
command once every ten seconds.
Events¶
- class lightbulb.events.CommandCompletionEvent(*, app: command_handler.Bot, command: commands.Command, context: context_.Context)¶
Bases:
lightbulb.events.LightbulbEvent
Event type dispatched when a command invocation occurred and was completed successfully. This means that all checks must have passed and that no errors can have been raised during the command invocation.
This requires one of the following combinations of intents in order to be dispatched:
hikari.intents.Intents.DM_MESSAGES
hikari.intents.Intents.GUILD_MESSAGES
- command¶
The command that this event was triggered for.
- context¶
The context that this event was triggered for.
- class lightbulb.events.CommandErrorEvent(*, app: command_handler.Bot, exception: errors.LightbulbError, context: typing.Optional[context_.Context] = None, message: hikari.Message, command: typing.Optional[commands.Command] = None)¶
Bases:
lightbulb.events.LightbulbEvent
Event type to subscribe to for the processing of all command errors raised by the handler.
Example
from lightbulb.events import CommandErrorEvent bot = lightbulb.Bot(token="token_here", prefix="!") @bot.listen(CommandErrorEvent) async def handle_command_error(event): ...
This requires one of the following combinations of intents in order to be dispatched:
hikari.intents.Intents.DM_MESSAGES
hikari.intents.Intents.GUILD_MESSAGES
- command¶
The command that this event was triggered for.
- context¶
The context that this event was triggered for. Will be
None
forCommandNotFound
errors.
- property exc_info: typing.Tuple[typing.Type[errors.LightbulbError], errors.LightbulbError, typing.Optional[types.TracebackType]]¶
The exception triplet compatible with context managers and
traceback
helpers.
- exception¶
The exception that triggered this event.
- message¶
The message that this event was triggered for.
- property traceback: types.TracebackType¶
The traceback for this event’s exception.
- class lightbulb.events.CommandInvocationEvent(*, app: command_handler.Bot, command: commands.Command, context: context_.Context)¶
Bases:
lightbulb.events.LightbulbEvent
Event dispatched when a command is invoked, regardless of whether or not the checks passed or failed, or an error was raised during command invocation.
This requires one of the following combinations of intents in order to be dispatched:
hikari.intents.Intents.DM_MESSAGES
hikari.intents.Intents.GUILD_MESSAGES
- command¶
The command that this event was triggered for.
- context¶
The context that this event was triggered for.
- class lightbulb.events.SlashCommandCompletionEvent(*, app: command_handler.Bot, command: slash_commands.BaseSlashCommand, context: slash_commands.SlashCommandContext)¶
Bases:
lightbulb.events.LightbulbEvent
Event type dispatched when a slash command invocation occurred and was completed successfully. This means that all checks must have passed and that no errors can have been raised during the command invocation.
This requires one of the following combinations of intents in order to be dispatched:
hikari.intents.Intents.DM_MESSAGES
hikari.intents.Intents.GUILD_MESSAGES
- command¶
The slash command that this event was triggered for.
- context¶
The context that this event was triggered for.
- class lightbulb.events.SlashCommandErrorEvent(*, app: command_handler.Bot, exception: errors.LightbulbError, context: slash_commands.SlashCommandContext, command: typing.Union[slash_commands.SlashCommand, slash_commands.SlashCommandGroup])¶
Bases:
lightbulb.events.LightbulbEvent
Event type to subscribe to for the processing of all slash command errors raised by the handler.
This requires one of the following combinations of intents in order to be dispatched:
hikari.intents.Intents.DM_MESSAGES
hikari.intents.Intents.GUILD_MESSAGES
- command¶
The slash command that this event was triggered for.
- context¶
The context that this event was triggered for.
- property exc_info: typing.Tuple[typing.Type[errors.LightbulbError], errors.LightbulbError, typing.Optional[types.TracebackType]]¶
The exception triplet compatible with context managers and
traceback
helpers.
- exception¶
The exception that triggered this event.
- property traceback: types.TracebackType¶
The traceback for this event’s exception.
- class lightbulb.events.SlashCommandInvocationEvent(*, app: command_handler.Bot, command: slash_commands.BaseSlashCommand, context: slash_commands.SlashCommandContext)¶
Bases:
lightbulb.events.LightbulbEvent
Event dispatched when a slash command is invoked, regardless of whether or not the checks passed or failed, or an error was raised during command invocation.
This requires one of the following combinations of intents in order to be dispatched:
hikari.intents.Intents.DM_MESSAGES
hikari.intents.Intents.GUILD_MESSAGES
- command¶
The slash command that this event was triggered for.
- context¶
The context that this event was triggered for.
Errors¶
- exception lightbulb.errors.LightbulbError¶
Bases:
Exception
Base for any exception raised by lightbulb.
- exception lightbulb.errors.ExtensionError(text: str)¶
Bases:
lightbulb.errors.LightbulbError
Base exception for errors incurred during the loading and unloading of extensions.
- exception lightbulb.errors.ExtensionAlreadyLoaded(text: str)¶
Bases:
lightbulb.errors.ExtensionError
Exception raised when an extension already loaded is attempted to be loaded.
- exception lightbulb.errors.ExtensionNotLoaded(text: str)¶
Bases:
lightbulb.errors.ExtensionError
Exception raised when an extension not already loaded is attempted to be unloaded.
- exception lightbulb.errors.ExtensionMissingLoad(text: str)¶
Bases:
lightbulb.errors.ExtensionError
Exception raised when an extension is attempted to be loaded but does not contain a load function
- exception lightbulb.errors.ExtensionMissingUnload(text: str)¶
Bases:
lightbulb.errors.ExtensionError
Exception raised when an extension is attempted to be unloaded but does not contain an unload function
- exception lightbulb.errors.CommandError¶
Bases:
lightbulb.errors.LightbulbError
Base exception for errors incurred during handling of commands.
- exception lightbulb.errors.CommandNotFound(invoked_with: str)¶
Bases:
lightbulb.errors.CommandError
Exception raised when a command when attempted to be invoked but one with that name could not be found.
- exception lightbulb.errors.NotEnoughArguments(command: lightbulb.commands.Command, missing_args: List[str])¶
Bases:
lightbulb.errors.CommandError
Exception raised when a command is run without a sufficient number of arguments.
- command: lightbulb.commands.Command¶
The command string that was attempted to be invoked.
- exception lightbulb.errors.TooManyArguments(command: lightbulb.commands.Command)¶
Bases:
lightbulb.errors.CommandError
Exception raised when a command is run with too many arguments, and the command has been defined to not accept any extra arguments when invoked.
- command: lightbulb.commands.Command¶
The command string that was attempted to be invoked.
- exception lightbulb.errors.ConverterFailure(text: Optional[str] = None)¶
Bases:
lightbulb.errors.CommandError
Exception raised when a converter for a command argument fails.
- exception lightbulb.errors.CommandIsOnCooldown(text: str, command: lightbulb.commands.Command, retry_in: float)¶
Bases:
lightbulb.errors.CommandError
Exception raised when a command is attempted to be run but is currently on cooldown.
- command: lightbulb.commands.Command¶
The command that is on cooldown.
- exception lightbulb.errors.CommandSyntaxError¶
Bases:
lightbulb.errors.CommandError
,abc.ABC
Base error raised if a syntax issue occurs parsing invocation arguments.
- exception lightbulb.errors.PrematureEOF¶
Bases:
lightbulb.errors.CommandSyntaxError
Error raised if EOF (end of input) was reached, but more content was expected.
- exception lightbulb.errors.UnclosedQuotes(text: str)¶
Bases:
lightbulb.errors.CommandSyntaxError
Error raised when no closing quote is found for a quoted argument.
- text¶
The text that caused the error to be raised.
- exception lightbulb.errors.CheckFailure(text: Optional[str] = None)¶
Bases:
lightbulb.errors.CommandError
Base error that is raised when a check fails for a command. Anything raised by a check should inherit from this class.
- exception lightbulb.errors.OnlyInGuild(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when a command marked as guild only is attempted to be invoked in DMs.
- exception lightbulb.errors.OnlyInDM(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when a command marked as DM only is attempted to be invoked in a guild.
- exception lightbulb.errors.NotOwner(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when a command marked as owner only is attempted to be invoked by another user.
- exception lightbulb.errors.BotOnly(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when the command invoker is not a bot.
- exception lightbulb.errors.HumanOnly(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when the command invoker is not an human.
- exception lightbulb.errors.NSFWChannelOnly(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when a command that must be invoked in an NSFW channel is attempted to be invoked outside of one.
- exception lightbulb.errors.MissingRequiredRole(text: str)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when the member invoking a command is missing one or more role required.
- exception lightbulb.errors.MissingRequiredPermission(text: str, permissions: hikari.permissions.Permissions)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when the member invoking a command is missing one or more permission required.
- permissions: hikari.permissions.Permissions¶
Permission(s) the bot is missing.
- exception lightbulb.errors.BotMissingRequiredPermission(text: str, permissions: hikari.permissions.Permissions)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when the bot is missing one or more permission required for the command to be run.
- permissions: hikari.permissions.Permissions¶
Permission(s) the bot is missing.
- exception lightbulb.errors.MissingRequiredAttachment(text)¶
Bases:
lightbulb.errors.CheckFailure
Error raised when the command invocation message is missing an attachment, or an attachment with the correct file extension.
- exception lightbulb.errors.CommandInvocationError(text: str, original: Exception)¶
Bases:
lightbulb.errors.CommandError
Error raised if an error is encountered during command invocation. This will only be raised if all the checks passed and an error was raised somewhere inside the command. This effectively acts as a wrapper for the original exception for easier handling in an error handler.
- exception lightbulb.errors.SlashCommandInvocationError(text: str, original: Exception)¶
Bases:
lightbulb.errors.CommandError
Error raised if an error is encountered during slash command invocation. This will only be raised if all the checks passed and an error was raised somewhere inside the command.
Help¶
- class lightbulb.help.HelpCommand(bot: command_handler.Bot)¶
The default help command implementation. This class should be subclassed if you wish to customise the format or other aspects of the bot’s help command.
- Parameters
bot (
Bot
) – Bot instance to add the help command class to.
- async object_not_found(context: context_.Context, name: str) None ¶
Method called when help is requested for an object that does not exist.
- async resolve_help_obj(context: context_.Context, obj: typing.List[str]) None ¶
Resolve the object to send help information for from the arguments passed to the help command.
- async send_command_help(context: context_.Context, command: commands.Command) None ¶
Method called when the help command is run with an argument that resolves into the name of a registered command.
- async send_group_help(context: context_.Context, group: commands.Group) None ¶
Method called when the help command is run with an argument that resolves into the name of a registered command group.
- async send_help_overview(context: context_.Context) None ¶
Method called when the help command is run without any arguments.
- Parameters
context (
Context
) – Context to send the help to.- Returns
None
- async static send_paginated_help(text: typing.Sequence[str], context: context_.Context) None ¶
Paginate the help text using
StringPaginator
and send each of the created pages to the context in order. Note that by default, only the help overview is paginated as this is the most likely to exceed the 2000 character message limit.
- async lightbulb.help.filter_commands(context: context_.Context, command_list: typing.Iterable[commands.Command]) typing.List[commands.Command] ¶
Filter a list of
Command
andGroup
, removing any commands that cannot be run under the given context by running all checks for each command in turn.
- lightbulb.help.get_command_signature(command: lightbulb.commands.Command) str ¶
Get the command signature (usage) for a command or command group. The signature is returned in the format:
<command name> <required arg> [optional arg]
- lightbulb.help.get_help_text(obj: Union[lightbulb.commands.Command, lightbulb.plugins.Plugin]) str ¶
Get the help text for a command, group or plugin, extracted from its docstring.