App API Reference#

class lightbulb.app.BotApp(token: str, prefix: ~typing.Sequence[str] | ~typing.Callable[[~lightbulb.app.BotApp, ~hikari.messages.Message], ~typing.Sequence[str] | ~typing.Coroutine[~typing.Any, ~typing.Any, ~typing.Sequence[str]]] | None = None, ignore_bots: bool = True, owner_ids: ~typing.Sequence[int] = (), default_enabled_guilds: int | ~typing.Sequence[int] = (), help_class: ~typing.Type[~lightbulb.help_command.BaseHelpCommand] | None = <class 'lightbulb.help_command.DefaultHelpCommand'>, help_slash_command: bool = False, delete_unbound_commands: bool = True, case_insensitive_prefixes: bool = False, case_insensitive_prefix_commands: bool = False, **kwargs: ~typing.Any)[source]#

A subclassed implementation of the GatewayBot class containing a command handler. This should be instantiated instead of the superclass if you wish to use the command handler implementation provided.

Parameters:
  • token (str) – The bot account’s token.

  • prefix (Optional[PrefixT]) – The command prefix to use for prefix commands, or None if prefix commands will not be used.

  • ignore_bots (bool) – Whether or not prefix commands should ignore bots for invocation. Defaults to True.

  • owner_ids (Sequence[int]) – The IDs of the users that own the bot. If not provided then it will be fetched by fetch_owner_ids.

  • default_enabled_guilds (Union[int, Sequence[int]]) – The guild(s) to create application commands in by default if no guilds are specified per-command. Defaults to an empty tuple.

  • help_class (Optional[Type[BaseHelpCommand]]) – Class to use for the bot’s help command. Defaults to DefaultHelpCommand. If None, no help command will be added to the bot by default.

  • help_slash_command (bool) – Whether or not the help command should be implemented as a slash command as well as a prefix command. Defaults to False.

  • delete_unbound_commands (bool) – Whether or not the bot should delete application commands that it cannot find an implementation for when the bot starts. Defaults to True.

  • case_insensitive_prefixes (bool) – Wheter or not command prefixes should be case-insensitive. Defaults to False.

  • case_insensitive_prefix_commands (bool) – Whether or not prefix command names should be case-insensitive. Defaults to False.

  • **kwargs (Any) – Additional keyword arguments passed to the constructor of the GatewayBot class.

add_plugin(plugin: Plugin) None[source]#

Registers a plugin to the bot, adding all commands and listeners present in the plugin.

Parameters:

plugin (Plugin) – Plugin to register to the bot.

Returns:

None

check(check: Check | CheckCoroT) Check[source]#
check() Callable[[CheckCoroT], Check]

Adds a Check object or check function the bot’s checks. This method can be used as a first or second order decorator, or called manually with the Check instance or function to add as a check. If a function is decorated or passed in then it will be wrapped in a Check object before it is added to the bot.

command(cmd_like: CommandLike) CommandLike[source]#
command() Callable[[CommandLike], CommandLike]

Adds a CommandLike object as a command to the bot. This method can be used as a first or second order decorator, or called manually with the CommandLike instance to add as a command.

create_task(coro: Awaitable[Any], *, name: str | None = None) Task[Any][source]#

Wrap the given awaitable into an asyncio.Task and schedule its execution. This method functions the same as asyncio.create_task(), but keeps a reference to the task alive until execution is completed to ensure the task is not destroyed mid-execution.

Parameters:

coro (Awaitable[Any]) – Coroutine to wrap into a task.

Keyword Arguments:

name (Optional[str]) – The name of the task. Not required, defaults to None.

Returns:

Created task object.

Return type:

asyncio.Task

New in version 2.2.0.

async fetch_owner_ids() Sequence[Snowflake | int][source]#

Fetch the bot’s owner IDs, or return the given owner IDs on instantiation if provided.

Returns:

The IDs of the bot’s owners.

Return type:

Sequence[Snowflakeish]

async get_application_command_context(event: InteractionCreateEvent) ApplicationContext | None[source]#

Get the appropriate subclass instance of Application for the given event.

Parameters:

event (InteractionCreateEvent) – Event to get the context for.

Returns:

Context instance for the given event.

Return type:

ApplicationContext

get_message_command(name: str) MessageCommand | None[source]#

Gets the message command with the given name, or None if no command with that name was found.

Parameters:

name (str) – Name of the message command to get.

Returns:

Message command object with the given name, or None

if not found.

Return type:

Optional[MessageCommand]

async get_message_context(event: ~hikari.events.interaction_events.InteractionCreateEvent, command: ~lightbulb.commands.message.MessageCommand, cls: ~typing.Type[~lightbulb.context.message.MessageContext] = <class 'lightbulb.context.message.MessageContext'>) MessageContext[source]#

Get the MessageContext instance for the given event.

Parameters:
Returns:

Message context instance for the given event.

Return type:

MessageContext

get_plugin(name: str) Plugin | None[source]#

Gets the plugin with the given name, or None if no plugin with that name was found.

Parameters:

name (str) – Name of the plugin to get.

Returns:

Plugin object with the given name, or None if not found.

Return type:

Optional[Plugin]

get_prefix_command(name: str) PrefixCommand | None[source]#

Gets the prefix command with the given name, or None if no command with that name was found.

Parameters:

name (str) – Name of the prefix command to get.

Returns:

Prefix command object with the given name, or None

if not found.

Return type:

Optional[PrefixCommand]

async get_prefix_context(event: ~hikari.events.message_events.MessageCreateEvent, cls: ~typing.Type[~lightbulb.context.prefix.PrefixContext] = <class 'lightbulb.context.prefix.PrefixContext'>) PrefixContext | None[source]#

Get the PrefixContext instance for the given event, or None if no context could be created.

Parameters:
Returns:

Prefix context instance for the given event.

Return type:

Optional[PrefixContext]

get_slash_command(name: str) SlashCommand | None[source]#

Gets the slash command with the given name, or None if no command with that name was found.

Parameters:

name (str) – Name of the slash command to get.

Returns:

Slash command object with the given name, or None

if not found.

Return type:

Optional[SlashCommand]

async get_slash_context(event: ~hikari.events.interaction_events.InteractionCreateEvent, command: ~lightbulb.commands.slash.SlashCommand, cls: ~typing.Type[~lightbulb.context.slash.SlashContext] = <class 'lightbulb.context.slash.SlashContext'>) SlashContext[source]#

Get the SlashContext instance for the given event.

Parameters:
Returns:

Slash context instance for the given event.

Return type:

SlashContext

get_user_command(name: str) UserCommand | None[source]#

Gets the user command with the given name, or None if no command with that name was found.

Parameters:

name (str) – Name of the user command to get.

Returns:

User command object with the given name, or None

if not found.

Return type:

Optional[UserCommand]

async get_user_context(event: ~hikari.events.interaction_events.InteractionCreateEvent, command: ~lightbulb.commands.user.UserCommand, cls: ~typing.Type[~lightbulb.context.user.UserContext] = <class 'lightbulb.context.user.UserContext'>) UserContext[source]#

Get the UserContext instance for the given event.

Parameters:
Returns:

User context instance for the given event.

Return type:

UserContext

async handle_interaction_create_for_application_commands(event: InteractionCreateEvent) None[source]#

Application command InteractionCreateEvent listener. This handles fetching the context, dispatching events, and invoking the appropriate command.

Parameters:

event (InteractionCreateEvent) – Event that application commands will be processed for.

Returns:

None

async handle_interaction_create_for_autocomplete(event: InteractionCreateEvent) None[source]#

Autocomplete InteractionCreateEvent listener. This handles resolving the function to use for autocompletion, response conversion into CommandChoice and responding to the interaction with the provided options.

Parameters:

event (InteractionCreateEvent) – Event that autocomplete will be processed for.

Returns:

None

async handle_message_create_for_prefix_commands(event: MessageCreateEvent) None[source]#

Prefix command MessageCreateEvent listener. This handles fetching the context, dispatching events, and invoking the appropriate command.

Parameters:

event (MessageCreateEvent) – Event that prefix commands will be processed for.

Returns:

None

async invoke_application_command(context: ApplicationContext) None[source]#

Invokes the appropriate application command for the given context and handles event dispatching for the command invocation.

Parameters:

context (ApplicationContext) – Context to invoke application commands under.

Returns:

None

load_extensions(*extensions: str) None[source]#

Load external extension(s) into the bot. Extension name follows the format <directory>.<filename> Each extension must contain a function load which takes a single argument which will be the BotApp instance you are loading the extension into.

Parameters:

extensions (str) – The name of the extension(s) 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.

load_extensions_from(*paths: str | Path, recursive: bool = False, must_exist: bool = True) None[source]#

Load all external extensions from the given directories. Files that begin with an underscore ( _ ) are ignored. Every extension must contain a function load which takes a single argument which will be the BotApp instance you are loading the extension into.

Parameters:

*paths (Union[str, pathlib.Path]) – The directories to load extensions from. These can be relative or absolute directories. In the case that a directory is absolute, the extension name will be set as though the directory was relative.

Keyword Arguments:
  • recursive (bool) – Whether to search the directories recursively. Defaults to False.

  • must_exist (bool) – Whether all directories must exist before extensions can be loaded. If this is False and a directory does not exist, the directory will be ignored. If this is True, a FileNotFoundError is thrown if any directory does not exist. Defaults to True.

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 any directory to load extensions from does not exist and must_exist is True.

  • ValueError – If the path provided is not relative to the current working directory.

async maybe_dispatch_error_event(event: CommandErrorEvent, priority_handlers: Sequence[None | Callable[[CommandErrorEvent], Coroutine[Any, Any, bool | None]]]) bool[source]#

Attempts to handle the event first using the given priority_handlers, falling back to dispatching the given event to global listeners.

Parameters:
  • event (CommandErrorEvent) – Event to attempt to handle.

  • priority_handlers (Sequence[Union[None, ListenerT) – Handlers to attempt to use to handle the event before falling back to global event listeners.

Returns:

Whether or not the given event was handled or dispatched successfully.

Return type:

bool

print_banner(banner: str | None, allow_color: bool, force_color: bool, extra_args: Dict[str, str] | None = None) None[source]#

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 (Optional[str]) – The package to find a banner.txt in.

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

    This will take precedence over allow_color if both are specified.

  • extra_args (Optional[Dict[str, str]]) – If provided, extra $-substitutions to use when printing the banner. Default substitutions can not be overwritten.

Raises:

ValueError – If extra_args contains a default $-substitution.

async process_prefix_commands(context: PrefixContext) None[source]#

Invokes the appropriate command for the given context.

Parameters:

context (context.prefix.PrefixContext) – Context to invoke the command under.

Returns:

None

async purge_application_commands(*guild_ids: Snowflake | int, global_commands: bool = False) None[source]#

Purges all application commands from the guilds with the specified IDs, and all the global application commands if global_commands is True. 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 application commands from.

Keyword Arguments:

global_commands (bool) – Whether or not to purge global slash commands from the bot.

Returns:

None

reload_extensions(*extensions: str) None[source]#

Reload bot extension(s). This method is atomic and so the bot will revert to the previous loaded state if an extension encounters a problem during unloading or loading.

Parameters:

extensions (str) – The name of the extension(s) to be reloaded.

Returns:

None

remove_command(command: Command | CommandLike) None[source]#

Removes a command or command-like object from the bot.

Parameters:

command (Union[Command, CommandLike) – Command or command-like object to remove from the bot.

Returns:

None

remove_plugin(plugin_or_name: Plugin | str) None[source]#

Unregisters a plugin from the bot, removing all commands and listeners present in the plugin.

Parameters:

plugin_or_name (Union[Plugin, str]) – Plugin or name of the plugin to unregister from the bot.

Returns:

None

async sync_application_commands() None[source]#

Sync all application commands registered to the bot with discord.

Returns:

None

New in version 2.2.0.

unload_extensions(*extensions: str) None[source]#

Unload external extension(s) from the bot. This method relies on a function, unload existing in the extensions which the bot will use to remove all commands and/or plugins from the bot.

Parameters:

extensions (str) – The name of the extension(s) 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.

application: t.Optional[hikari.Application]#

The Application for the bot account. This will always be None before the bot has logged in.

d: data_store.DataStore#

A DataStore instance enabling storage of custom data without subclassing.

default_enabled_guilds: t.Sequence[int]#

The default guilds that application commands will be enabled in.

extensions: t.List[str]#

A list of the currently loaded extensions.

property help_command: BaseHelpCommand | None#

The current help command instance registered to the bot.

ignore_bots: bool#

Whether or not other bots will be ignored when invoking prefix commands.

property message_commands: MutableMapping[str, MessageCommand]#

Mapping of command name to command object containing all message commands registered to the bot.

owner_ids: t.Sequence[int]#

The owner ID(s) for the owner(s) of the bot account.

property plugins: MutableMapping[str, Plugin]#

Mapping of plugin name to plugin object containing all plugins registered to the bot.

property prefix_commands: MutableMapping[str, PrefixCommand]#

Mapping of command name to command object containing all prefix commands registered to the bot.

property slash_commands: MutableMapping[str, SlashCommand]#

Mapping of command name to command object containing all slash commands registered to the bot.

property user_commands: MutableMapping[str, UserCommand]#

Mapping of command name to command object containing all user commands registered to the bot.

lightbulb.app.when_mentioned_or(prefix_provider: Sequence[str] | Callable[[BotApp, Message], Sequence[str] | Coroutine[Any, Any, Sequence[str]]]) Callable[[BotApp, Message], Coroutine[Any, Any, Sequence[str]]][source]#

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 – A str prefix, Sequence[str] of prefixes, or sync or async callable that returns a prefix or sequence of prefixes. If None, only the bot’s mentions will be used.

Example

# The below are all valid
app = lightbulb.BotApp(prefix=lightbulb.when_mentioned_or("!"), ...)

app = lightbulb.BotApp(prefix=lightbulb.when_mentioned_or(["!", "?"]), ...)

# Using only mentions as the prefix
app = lightbulb.BotApp(prefix=lightbulb.when_mentioned_or(None), ...)

# Using with a get_prefix function
def get_prefix(app, message):
    # Do something to get the prefixes
    return prefixes

app = lightbulb.BotApp(prefix=lightbulb.when_mentioned_or(get_prefix), ...)