Skip to content

Event Reference

A little note about event names

Event names are never prefixed with on_, so make sure you're listening to events like message, not on_message!

While trying to listen for an on_ prefixed event will still work, it will throw warnings in the console, and may be deprecated in the future.


NioBot-specific events

There are two types of events in niobot: those that are dispatched by niobot itself, and those that're dispatched by matrix-nio. In order to keep backwards compatability, as well as high flexibility and extensibility, niobot's NioBot class actually subclasses nio.AsyncClient. This means that anything you can do with matrix-nio, you can do with niobot.

However, for simplicity, niobot dispatches its own events independently of matrix-nio. These events are listed below.

You can listen to these events with niobot.NioBot.on_event.

Example
import niobot

bot = niobot.NioBot(...)


@bot.on_event("ready")
async def on_ready(result):
    print("Bot is ready!")
    print("Logged in as:", bot.user_id)


bot.run(...)

event_loop_running async

event_loop_running() -> Optional[Any]

An event that is fired once the event loop is running.

You should use this event to perform any startup tasks.

This event is fired before the bot logs in, and before the first sync() is performed.

This means that if, for example, you wanted to initialise a database, or make some HTTP request in a module, You can @[nio]bot.event("event_loop_running") do it here.

Initialising a database in a module
import niobot
import aiosqlite

class MyModule(niobot.Module):
    def __init__(self, bot):
        super().__init__(bot)
        self.db = None

    @niobot.event("event_loop_running")
    async def event_loop_running(self):
        self.db = await aiosqlite.connect("mydb.db")
        await self.db.execute(...)
        await self.db.commit

ready async

ready(result: SyncResponse) -> Optional[Any]

An event that is fired when the bot's first sync() is completed.

This indicates that the bot successfully logged in, synchronised with the server, and is ready to receive events.

Parameters:

Name Type Description Default
result SyncResponse

The response from the sync.

required

message async

message(
    room: MatrixRoom, event: RoomMessage
) -> Optional[Any]

An event that is fired when the bot receives a message in a room that it is in.

This event is dispatched before commands are processed, and as such the convenient niobot.Context is unavailable.

Not every message is a text message

As of v1.2.0, the message event is dispatched for every decrypted message type, as such including videos, images, audio, and text. Prior for v1.2.0, this was only dispatched for text messages.

Please check either the type of the event (i.e. isinstance(event, niobot.RoomMessageText)) or the event.source["content"]["msgtype"] to determine the type of the message.

Tip

If you want to be able to use the niobot.Context in your event handlers, you should use the command event instead.

Furthermore, if you want more fine-grained control over how commands are parsed and handled, you should override niobot.NioBot.process_message instead of using the message event.

Parameters:

Name Type Description Default
room MatrixRoom

The room that the message was received in.

required
event RoomMessage

The raw event that triggered the message.

required

command async

command(ctx: Context) -> Optional[Any]

This event is dispatched once a command is finished being prepared, and is about to be invoked.

This event is dispatched after the message event, but before command_complete and command_error.

This event features the original context, which can be used to access the message, the command, and the arguments.

Parameters:

Name Type Description Default
ctx Context

The context of the command.

required

command_complete async

command_complete(
    ctx: Context, result: Any
) -> Optional[Any]

This event is dispatched after a command has been invoked, and has completed successfully.

This event features the context, which can be used to access the message, the command, and the arguments.

Parameters:

Name Type Description Default
ctx Context

The context of the command.

required
result Any

The result of the command (the returned value of the callback)

required

command_error async

command_error(
    ctx: Context, error: CommandError
) -> Optional[Any]

This event is dispatched after a command has been invoked, and has completed with an error.

This event features the context, which can be used to access the message, the command, and the arguments.

Getting the original error

As the error is wrapped in a niobot.CommandError, you can access the original error by accessing the CommandError.original attribute.

@bot.event("command_error")
async def on_command_error(ctx, error):
    original_error = error.original
    print("Error:", original_error)

It is encouraged that you inform the end user about an error that has occurred, as by default the error is simply logged to the console. Don't forget, you've got the whole Context instance - use it!

Parameters:

Name Type Description Default
ctx Context

The context of the command.

required
error CommandError

The error that was raised.

required

raw async

raw(room: MatrixRoom, event: Event) -> Optional[Any]

This is a special event that is handled when you directly pass a niobot.Event to on_event.

You cannot listen to this in the traditional sense of "on_event('name')" as it is not a named event. But, this extensibility allows you to listen directly for events not covered by the library.

Example

The below code will listen directly for the redaction event and will print out the redaction details.

See the nio events documentation for more details and a list of available events.x

import niobot

@bot.on_event(niobot.RedactionEvent)  # listen for redactions
async def on_redaction(room, event):
    print(f"{event.sender} redacted {event.redacts} for {event.reason!r} in {room.display_name}")

matrix-nio events

See the matrix-nio documentation for the base-library set of events.

Remember, you'll need to use nio.Client.add_event_callback in order to listen to these!

New in v1.2.0

You can now listen to matrix-nio events with niobot.NioBot.on_event! Just pass the raw event type to the decorator, rather than a string.