- Updated to v0.8.0 - Added note about rate limitting to README - Updated examples to work with new callback system - Updated README to describe new callback system correctly - Added branch_bot.py example - Updated database so internal functions are prefixed with underscore now - Replaced MatrixBot.add_room_event_callback with MatrixBot.add_callback - Database schema version is 4 now - Added room state to database to simplify user code - Added RoomStateFilter
6.7 KiB
🤖 mab
mab (MAtrix Bot) is a very simple Python package that can be used to develop very simple Matrix bots. It does not aim to be the best library out there, but it aims to be convenient and usable for relatively serious projects.
Important
You may need to tweak rate limits for your bot account in the server admin settings in order the server not to throttle your bot. Check Ketasa if you use Synapse.
✨ Features
The library supports the following features:
- Completely
asynciobased - Filter-based callback system
- Downloading and transparently decrypting files
- Sending files
- Sending images
- Sending videos with automatic thumbnail generation (requires
ffmpeg)
📦 Installation
Use apt to install required system packages and pip to install the package.
You may need to use root privileges to use apt. It's highly recommended you
use venv or another Python virtual environment. Here are the commands to
install the latest stable version of the library:
apt install libmagic1-dev libolm-dev
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.8.0
libmagic1-dev is needed for automatic file MIME type detection, libolm-dev
is needed for E2EE to work.
Please refer to examples for some basic bots. Examples are the best
introduction to this library. They are tested manually on each tagged commit.
You need to set MAB_SERVER, MAB_USER and MAB_PASSWORD environment
variables to pass server, username and password to the example.
| Variable | Example value |
|---|---|
MAB_SERVER |
https://matrix.example.org |
MAB_USER |
localusername |
MAB_PASSWORD |
1337--w4-w1ll-r0ck-y0u! |
🚀 Usage
The architecture of mab is quite primitive. You define your callback
functions, you register them and you start the bot. When an event of interest
happens your callback functions get called. That's it. However, some spices are
poured in to enhance the development experience a little bit.
First of all, most encryption things are done transparently and automatically.
The most important thing that is not provided by matrix-nio is automatic
asynchronous decryption of the files you download. You don't need to worry
about it at all when you use mab.
You need to create MatrixBot object to create a bot. This is the common way
of creating a bot:
import asyncio
from mab import *
async def main():
# Create the config for the bot object
bot_config = MatrixBotConfig(
matrix_homeserver_url="https://matrix.example.org",
matrix_username_localpart="username-here",
storage_directory="session_storage"
)
# Create the bot itself
bot = MatrixBot(bot_config)
# Add callbacks (use `None` instead of callback name to print debug info)
bot.add_callback(~SenderIsBotFilter(), None)
# Run until Ctrl+C
await bot.run()
asyncio.run(main())
To reduce amount of ifs in your code, filter concept is introduced. When
you add a callback to the instance of the bot, you also provide a filter object.
Filters are created like that:
# Filter that is True for users in `admins_list`
admins_list = [
"@server-admin:matrix.example.org",
"@bot-admin:matrix.example.org"
]
sent_by_admin = SenderIsFilter(admins_list)
# Filter that is True for messages that have file attached to them
has_file = MessageHasFileFilter()
# Filter that is True for messages with nonempty body
has_body = BodyExistsFilter()
In fact, you can't create usable bot with just these filters. You need to combine them in different ways. So all filters support bitwise logical operators on them. For example, if you'd like to create a filter for a callback that must be called each time a different user adds a reaction to some message, you'd write something like that:
# Define the list of admins
admin_list = [
"@admin-ivan:matrix.example.org",
"@admin-vladimir:matrix.example.org"
]
# Define the filter
the_filter = (
MessageHasFileFilter()
& SenderIsFilter(admin_list)
)
Sometimes it is useful to add some sort of hierarchy for your callbacks to
simplify the code. That's the moment when Branch concept becomes useful.
Let's assume you want to add specific event handlers that are executed only for
users from admin_list. You would write something like that:
is_admin = SenderIsFilter(admin_list)
delete_command_filter = is_admin & BodyCommandFilter("delete")
create_command_filter = is_admin & BodyCommandFilter("create")
bot.callbacks.add_callback(delete_command_filter, callback_1)
bot.callbacks.add_callback(create_command_filter, callback_2)
You can logically organize these events in one branch to manage them more efficiently:
admin_branch = Branch(SenderIsFilter(admin_list))
admin_branch.add_callback(BodyCommandFilter("delete"), callback_1)
admin_branch.add_callback(BodyCommandFilter("create"), callback_2)
bot.callbacks.add_branch(admin_branch)
Please refer to branch_bot.py for detailed usage example.
The concept of Context Variables is introduced to avoid the usage of
somewhat complex matrix-nio objects. Context variables are key-value pairs
passed to your event callbacks. Think of them as environment variables passed
to programs.
Here's an example of simple event callback implementation
async def simple_callback(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(
ctx.room,
f"You have said `{vars[CTX_MESSAGE].body}`!"
)
🏷️ Versioning
Releases are tagged in this repository using the vX.Y.Z format. If the commit
is not tagged, it must be treated as versionless and should not be used for your
application.
X(Major): Breaking architectiral changes or complete rewrites. Existing code will break. Note that0.Y.Zversions are considered very unstable, the API may change at any time and some features do not work as expected.Y(Minor): Breaking API changes, feature removals, or behavioral modifications. Existing code will likely break.Z(Patch): Backward-compatible feature additions, bug fixes, or internal changes. Existing code will not break.
🛠️ Development
Here's the list of commands you should execute to get started with development
(including cloning the repository and installing required packages). Please note
that your workflow may use something other than venv.
apt install libmagic1-dev libolm-dev
git clone https://git.tyukalov.su/nikita/mab
cd mab
python3 -m venv .venv
. .venv/bin/activate
pip install -e .