Manual

This is a manual for simplematrixbotlib that includes documentation, examples, and more.

Installation

How to install the simplematrixbotlib package

The simplematrixbotlib package can be installed from pypi or from the git repository.

Installing from PyPi

Run the following command in your terminal or cmd prompt to install simplematrixbotlib from pypi

python -m pip install simplematrixbotlib

Installing from Git Repo

Run the following command in your terminal or cmd prompt to download the repository to your machine.

git clone --branch master https://github.com/KrazyKirby99999/simple-matrix-bot-lib.git

The package is located under (current directory)/simple-matrix-bot-lib as simplematrixbotlib.

Importing

How to import simplematrixbotlib

Importing simplematrixbotlib requires installation of the package first.

Importing

Importing the simplematrixbotlib package is done with the following python code.

import simplematrixbotlib as botlib

Referring to the package as “botlib” is optional, however this is how the simplematrixbotlib will be referred to throughout this manual and the rest of the documentation.

Usage of Creds class

How to use the Creds class

The Creds class is a class that handles login credentials. The source is located at simplematrixbotlib/auth.py.

Creating an instance of the Creds class

An instance can be created using the following python code.

creds = botlib.Creds(
    homeserver="https://example.org",
    username="username",
    password="password",
    session_stored_file="session.txt"
    )

or

creds = botlib.Creds(
    homeserver="https://example.org",
    login_token="MDA..gZ2"
    session_stored_file="session.txt"
    )

The homeserver argument is always required. The username, and password arguments are also required unless the login_token argument is used. The keyword “login_token” must be specified when the login_token argument is used. Although the login_token can only be used to authenticate with the homeserver once, it is required in every run of the bot in order to encrypt/decrypt the session data such as the access_token. If the login_token is used and the session_stored_file argument is set to None, then the bot will only be able to run once per login_token. The session_stored_file argument is optional and allows for specific data relating to each session such as the access token and the device name to be preserved across each run of the bot.

Usage of Bot class

How to use the Bot class

The Bot class is a class that handles most of the functionality of a bot created with Simple-Matrix-Bot-Lib. The source is located at simplematrixbotlib/bot.py.

Creating an instance of the Bot class

An instance can be created using the following python code.

bot = botlib.Bot(
    creds=creds
    )

The creds argument is neccesary, and is an instance of the Creds class.

Running the Bot

When the Bot is ready to be started, the run method can be used to run the Bot. An example is shown in the following python code.

bot.run()

Usage of Listener class

How to use the Listener class

The Listener class is a class that is used to specify reactions to the events that occur in Matrix rooms. The source is located at simplematrixbotlib/listener.py

Accessing a Listener instance

An instance of the Listener class is automatically created when an instance of the Bot class is created. An example is shown in the following python code.

bot = botlib.Bot(creds)
bot.listener #Instance of the Listener class

Using the on_message_event decorator

The on_message_event method of the Listener class may be used to execute actions based on messages that are sent in rooms that the bot is a member of. Example usage of on_message_event is shown in the following python code.

@bot.listener.on_message_event
async def example(room, message):
    print(f"A message({message.content}) was sent in a room({room.room_id}).")

When any message is sent, the function will be called with room as a Room object representing each room that that the bot is a member of, and message as a RoomMessage object representing the message that was sent.

Using the on_custom_event decorator

The on_custom_event method of the Listener class may be used to execute actions based on any event that is sent in rooms that the bot is a member of. Example usage of on_custom_event is shown in the following python code.

import nio

@bot.listener.on_custom_event(nio.InviteMemberEvent)
async def example(room, event):
    if event.membership == "join":
        print(f"A user joined the room({room.room_id}).")
    if event.membership == "leave":
        print(f"A user left the room({room.room_id}).")

The on_custom_event method is almost identical to the on_message_event method. on_custom_event takes an argument that allows the developer to specify the event type for the Bot to respond to. Information on events can be found in the matrix-nio docs.

Using the on_startup decorator

The on_startup method of the Listener class may be used to execute actions upon the starting of the Bot. Example usage of the on_startup method is show in the following python code.

@bot.listener.on_startup
async def room_joined(room_id):
    print(f"This account is a member of a room with the id {room_id}")

When the bot is run, for each room that the Bot is a member of, the function will be called with room_id as a string that corresponds to the room_id of the room.

Usage of Match and MessageMatch classes

How to use the Match class

The Match class is a class that handles matching/filtering of the content of events. The source is located at simplematrixbotlib/match.py

Creating an instance of the Match class

An instance can be created using the following python code.

match = botlib.Match(
    room=room,
    event=event,
    bot=bot
)

The room, event, and bot arguments are neccesary. The room and event arguments should be the same as the arguments of the handler function. The bot argument should be the same as the instance of the Bot class. This class is intended to be used with non-message events, as the MessageMatch class is a child class of this class, and has message-specific methods. A list of methods for the Match class is shown below.

List of Methods:

Method

Explanation

Match.is_from_user_id(userid)

Returns True if the userid argument matches the event’s sender.

Match.is_not_from_this_bot()

Returns True if the event is not sent by this bot.

Example:

bot.listener.on_message_event
async def example(room, event):
    match = botlib.Match(room, event, bot)
    if match.is_not_from_this_bot():
        print(f"A user sent a message in room {room.room_id}")

How to use the MessageMatch class

The MessageMatch class is a class that handles matching/filtering of message events. It is a subclass of the Match class, and thus methods of the Match class can also be used with the MessageMatch class. The source is located at simplematrixbotlib/match.py

Creating an instance of the MessageMatch class

An instance can be created using the following python code.

match = botlib.MessageMatch(
    room=room,
    event=event,
    bot=bot,
    prefix="/"
)

The room, event, and bot arguments are necessary. The bot argument is an instance of the Bot class. The room and event arguments are the same as the arguments specified when creating a handler function to be used with the Listener.on_message_event method. The prefix argument is usually used as the beginning of messages that are intended to be commands, usually “!”, “/” or another short string. An example handler function that uses MessageMatch is shown in the following python code.

bot.listener.on_message_event
async def example(room, message):
    match = botlib.MessageMatch(room, message, bot, "!")
    if match.command("help") and match.prefix(): # Matches any message that begins with "!help "
        #Respond to help command

As said earlier, the prefix argument is optional. An example handler function without it is shown in the following python code.

bot.listener.on_message_event
async def example(room, message):
    match = botlib.MessageMatch(room, message, bot)
    if match.command("help"): # Matches any message that begins with "help "
        #Respond to help command

A list of methods for the Match class is shown below. Methods from the Match class can also be used with the MessageMatch class.

List of Methods:

Method

Explanation

MessageMatch.command() or MessageMatch.command(command)

The “command” is the beginning of messages that are intended to be commands, but after the prefix; e.g. “help”. Returns the command if the command argument is empty. Returns True if the command argument is equivalent to the command.

MessageMatch.prefix()

Returns True if the message begins with the prefix specified during the initialization of the instance of the MessageMatch class. Returns True if no prefix was specified during the initialization.

MessageMatch.args()

Returns a list of strings; each string is part of the message separated by a space, with the exception of the part of the message before the first space (the prefix and command). Returns an empty list if it is a single-word command.

MessageMatch.contains(string)

Returns True if the message contains the value specified in the string argument.

Usage of the Api class

How to use the Api class

The Api class is a class that is used to simplify interaction with the matrix-nio library that Simple-Matrix-Bot-Lib is built upon. The source is located at simplematrixbotlib/api.py

Accessing an Api instance

An instance of the Api class is automatically created when an instance of the Bot class is created. An example is shown in the following python code.

bot = botlib.Bot(creds)
bot.api #Instance of the Api class

Using the send_text_message method

The send_text_message method of the Api class can be used to send text messages in Matrix rooms. An example is shown in the following python code.

async def example(room, message):
    match = botlib.MessageMatch(room, message, bot)
    example_message = "Hello World"
    if match.is_not_from_this_bot():
        bot.api.send_text_message(
            room_id=room.room_id,
            message=example_message)

Both arguments are required. The room_id argument is the id of the destination room. The message argument is the string that is to be sent as a message.

Using the send_image_message method

The send_image_message method of the Api class can be used to send image messages in Matrix rooms. An example is shown in the following python code.

async def example(room, message):
    match = botlib.MessageMatch(room, message, bot)
    example_image="./img/example.png"
    if match.is_not_from_this_bot():
        bot.api.send_image_message(
            room_id=room.room_id,
            image_filepath=example_image)

Both arguments are required. The room_id argument is the id of the destination room. The image_filepath argument is a string that is the path to the image file that is to be sent as a message.

Using the send_markdown_message method

The send_markdown_message method of the Api class can be used to send markdown messages in Matrix rooms. An example is shown in the following python code.

async def example(room, message):
    match = botlib.MessageMatch(room, message, bot)
    example_markdown = "# Hello World from [simplematrixbotlib](https://github.com/KrazyKirby99999/simple-matrix-bot-lib)!"
    if match.is_not_from_this_bot():
        await bot.api.send_markdown_message(
            room_id=room.room_id,
            message=example_markdown)

Both arguments are required. The room_id argument is the id of the destination room. The message argument is the string with markdown syntax that is to be sent as a message.