Skip to content

Commands

Using commands and events is the main way to interact with the bot.

NioBotException

Bases: Exception

Base exception for NioBot.

Warning

In some rare cases, all of exception, response and original may be None.

All other exceptions raised by this library will subclass this exception, so at least all the below are always available:

Attributes:

Name Type Description
message Optional[str]

A simple humanised explanation of the issue, if available.

response Optional[ErrorResponse]

The response object from the server, if available.

exception Optional[Union[ErrorResponse, BaseException]]

The exception that was raised, if available.

original Union[ErrorResponse, BaseException, None]

The original response, or exception if response was not available.

bottom_of_chain

bottom_of_chain(
    other: Optional[Union[Exception, ErrorResponse]] = None
) -> Union[BaseException, ErrorResponse]

Recursively checks the original attribute of the exception until it reaches the bottom of the chain.

This function finds you the absolute first exception that was raised.

Parameters:

Name Type Description Default
other Optional[Union[Exception, ErrorResponse]]

The other exception to recurse down. If None, defaults to the exception this method is called on.

None

Returns:

Type Description
Union[BaseException, ErrorResponse]

The bottom of the chain exception.

__str__

__str__() -> str

Returns a human-readable version of the exception.

__repr__

__repr__() -> str

Returns a developer-readable version of the exception.

GenericMatrixError

Bases: NioBotException

Exception for generic matrix errors where a valid response was expected, but got an ErrorResponse instead.

MessageException

Bases: NioBotException

Exception for message-related errors.

LoginException

Bases: NioBotException

Exception for login-related errors.

MediaException

Bases: MessageException

Exception for media-related errors.

MediaUploadException

Bases: MediaException

Exception for media-uploading related errors

MediaDownloadException

Bases: MediaException

Exception for media-downloading related errors

MediaCodecWarning

Bases: ResourceWarning

Warning that is dispatched when a media file is not in a supported codec.

You can filter this warning by using warnings.filterwarnings("ignore", category=niobot.MediaCodecWarning)

Often times, matrix clients are web-based, so they're limited to what the browser can display. This is usually:

  • h264/vp8/vp9/av1/theora video
  • aac/opus/vorbis/mp3/pcm_* audio
  • jpg/png/webp/avif/gif images

MetadataDetectionException

Bases: MediaException

Exception raised when metadata detection fails. Most of the time, this is an ffmpeg-related error

CommandError

Bases: NioBotException

Exception subclass for all command invocation related errors.

CommandNotFoundError

Bases: CommandError

Exception raised when a command is not found.

CommandPreparationError

Bases: CommandError

Exception subclass for errors raised while preparing a command for execution.

CommandDisabledError

Bases: CommandPreparationError

Exception raised when a command is disabled.

CommandArgumentsError

Bases: CommandPreparationError

Exception subclass for command argument related errors.

CommandParserError

Bases: CommandArgumentsError

Exception raised when there is an error parsing arguments.

CheckFailure

Bases: CommandPreparationError

Exception raised when a generic check call fails.

You should prefer one of the subclass errors over this generic one, or a custom subclass.

CheckFailure is often raised by the built-in checker when a check returns a falsy value without raising an error.

NotOwner

Bases: CheckFailure

Exception raised when the command invoker is not the owner of the bot.

InsufficientPower

Bases: CheckFailure

Exception raised when the command invoker does not have enough power to run the command.

Argument

Represents a command argument.

Example
from niobot import NioBot, command, Argument

bot = NioBot(...)

@bot.command("echo")
def echo(ctx: niobot.Context, message: str):
    await ctx.respond(message)

bot.run(...)

Parameters:

Name Type Description Default
name str

The name of the argument. Will be used to know which argument to pass to the command callback.

required
arg_type _T

The type of the argument (e.g. str, int, etc. or a custom type)

required
description Optional[str]

The description of the argument. Will be shown in the auto-generated help command.

None
default Any

The default value of the argument

...
required bool

Whether the argument is required or not. Defaults to True if default is ..., False otherwise.

...

__init__

__init__(
    name: str,
    arg_type: _T,
    *,
    description: Optional[str] = None,
    default: Any = ...,
    required: bool = ...,
    parser: Callable[
        [Context, Argument, str], Optional[_T]
    ] = ...,
    **kwargs
)

internal_parser staticmethod

internal_parser(
    _: Context, arg: Argument, value: str
) -> Optional[_T]

The default parser for the argument. Will try to convert the value to the argument type.

Command

Represents a command.

Example

Note

This example uses the command decorator, but you can also use the Command class directly, but you likely won't need to, unless you want to pass a custom command class.

All that the @command decorator does is create a Command instance and add it to the bot's commands, while wrapping the function its decorating.

from niobot import NioBot, command

bot = NioBot(...)

@bot.command("hello")
def hello(ctx: niobot.Context):
    await ctx.respond("Hello, %s!" % ctx.message.sender)

bot.run(...)

Parameters:

Name Type Description Default
name str

The name of the command. Will be used to invoke the command.

required
callback Callable

The callback to call when the command is invoked.

required
aliases Optional[list[str]]

The aliases of the command. Will also be used to invoke the command.

None
description Optional[str]

The description of the command. Will be shown in the auto-generated help command.

None
disabled bool

Whether the command is disabled or not. If disabled, the command will be hidden on the auto-generated help command, and will not be able to be invoked.

False
arguments Optional[list[Argument]]

A list of Argument instances. Will be used to parse the arguments given to the command. ctx is always the first argument, regardless of what you put here.

None
usage Optional[str]

A string representing how to use this command's arguments. Will be shown in the auto-generated help. Do not include the command name or your bot's prefix here, only arguments. For example: usage="<message> [times]" will show up as [p][command] <message> [times] in the help command.

None
hidden bool

Whether the command is hidden or not. If hidden, the command will be always hidden on the auto-generated help.

False
greedy bool

When enabled, CommandArgumentsError will not be raised if too many arguments are given to the command. This is useful for commands that take a variable amount of arguments, and retrieve them via Context.args.

False

display_usage property

display_usage: str

Returns the usage string for this command, auto-resolved if not pre-defined

autodetect_args staticmethod

autodetect_args(callback) -> list[Argument]

Attempts to auto-detect the arguments for the command, based on the callback's signature

Parameters:

Name Type Description Default
callback

The function to inspect

required

Returns:

Type Description
list[Argument]

A list of arguments. self, and ctx are skipped.

__eq__

__eq__(other)

Checks if another command's runtime ID is the same as this one's

invoke async

invoke(ctx: Context) -> Coroutine

Invokes the current command with the given context

Parameters:

Name Type Description Default
ctx Context

The current context

required

Raises:

Type Description
CommandArgumentsError

Too many/few arguments, or an error parsing an argument.

CheckFailure

A check failed

construct_context

construct_context(
    client: NioBot,
    room: MatrixRoom,
    src_event: RoomMessageText,
    invoking_prefix: str,
    meta: str,
    cls: type = Context,
) -> Context

Constructs the context for the current command.

You will rarely need to do this, the library automatically gives you a Context when a command is run.

Parameters:

Name Type Description Default
client NioBot

The current instance of the client.

required
room MatrixRoom

The room the command was invoked in.

required
src_event RoomMessageText

The source event that triggered the command. Must be nio.RoomMessageText.

required
invoking_prefix str

The prefix that triggered the command.

required
meta str

The invoking string (usually the command name, however may be an alias instead)

required
cls type

The class to construct the context with. Defaults to Context.

Context

Returns:

Type Description
Context

The constructed Context.

Module

Represents a module.

A module houses a set of commands and events, and can be used to modularise your bot, and organise commands and their respective code into multiple files and classes for ease of use, development, and maintenance.

Attributes:

Name Type Description
bot

The bot instance this module is mounted to.

__setup__

__setup__()

Setup function called once by NioBot.mount_module(). Mounts every command discovered.

__teardown__

__teardown__()

Teardown function called once by NioBot.unmount_module(). Removes any command that was mounted.

command

command(name: Optional[str] = None, **kwargs) -> Callable

Allows you to register commands later on, by loading modules.

This differs from NioBot.command() in that commands are not automatically added, you need to load them with bot.mount_module

Parameters:

Name Type Description Default
name Optional[str]

The name of the command. Defaults to function.name

None
kwargs

Any key-words to pass to Command

{}

Returns:

Type Description
Callable

check

check(
    function: Callable[
        [Context], Union[bool, Coroutine[None, None, bool]]
    ],
    name: Optional[str] = None,
) -> Callable

Allows you to register checks in modules.

@niobot.command()
@niobot.check(my_check_func, name="My Check")
async def my_command(ctx: niobot.Context):
    pass

Parameters:

Name Type Description Default
function Callable[[Context], Union[bool, Coroutine[None, None, bool]]]

The function to register as a check

required
name Optional[str]

A human-readable name for the check. Defaults to function.name

None

Returns:

Type Description
Callable

The decorated function.

event

event(name: str = None) -> Callable

Allows you to register event listeners in modules.

Parameters:

Name Type Description Default
name str

the name of the event (no on_ prefix)

None

Returns:

Type Description
Callable