From 86b1c6c142e6f2822ac86a95e98ccc08eec7dbf5 Mon Sep 17 00:00:00 2001 From: nikita Date: Tue, 1 Dec 2026 21:22:57 +0300 Subject: [PATCH] Readme update, version update, examples update --- README.md | 153 ++++++++++++++++++++++++--------------- examples/_environment.py | 12 +-- examples/command_bot.py | 4 +- examples/echo_bot.py | 4 +- examples/file_bot.py | 4 +- examples/image_bot.py | 4 +- examples/reaction_bot.py | 4 +- examples/room_bot.py | 4 +- 8 files changed, 109 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 615b553..a8ef0da 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,6 @@ 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. ->[!NOTE] -> Latest *"stable"* version is `v0.6.1`. Next version tag will be set when the -> library will become more usable and more stable. Upcoming version is `v0.7.0`. - ## ✨ Features The library supports the following features: @@ -27,77 +23,114 @@ install the latest stable version of the library: ```bash apt install libmagic1-dev libolm-dev -python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.6.1 +python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.7.0 ``` `libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev` is needed for E2EE to work. -Please inspect [`examples/image_bot.py`](examples/image_bot.py), -[`examples/echo_bot.py`](examples/echo_bot.py) or open [`examples/`](examples/) -directory to find usage examples. Examples require that you set -`MATRIX_HOMESERVER` and `MATRIX_USERNAME` environment variables. Examples create -`session_storage` directory in working directory. +Please refer to [examples](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 -If you use `mab`, your application will *most likely* be using **callbacks** to -react to user actions. `mab` uses filter-based callback system to avoid exposing -raw `nio-matrix` event objects. +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. -This is the workflow you will most likely follow: -1. **Define the callback as `async` function that take 1 argument of type - `EventContext`.** For example, this callback would print the caption of the - message: - ```python - from mab import * +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`. - async def on_media_with_body(ctx: EventContext): - """To be called when a message with image/video and caption is received.""" - print(ctx[CTX_BODY]) - ``` -2. **Define the conditions your callback must be called on.** For example, you - may want your callback to be called when `the sender is not the bot` and - `the message contains textual body` and (`the message is an image` or - `the message is a video`). -3. **Define the conditions as `filters`.** Most of them are pretty - straightforward. For example, if you want to use the conditions from above: - ```python - from mab import * +You need to create `MatrixBot` object to create a bot. This is the common way +of creating a bot: +```python +import asyncio +from mab import * - filters = ( - ~SenderIsBotFilter() - & MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO]) - & BodyExistsFilter() - ) - ``` -4. **Add the callback to your `MatrixBot` instance.** For example, if you would - have used everything from above, then your code would look something like - this: - ```python - from mab import * +# Run until Ctrl+C +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() - # let's assume you create your MatrixBot as `bot` variable here +asyncio.run(main()) +``` - async def on_media_with_body(ctx: EventContext): - """To be called when a message with image/video and caption is received.""" - print(ctx[CTX_BODY]) - - filters = ( - ~SenderIsBotFilter() - & MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO]) - & BodyExistsFilter() - ) - bot.add_callback(filters, on_media_with_body) +To reduce amount of `if`s in your code, **filters** 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: +```python +# Filter that is True for new message +new_message = NewMessageFilter() - ... - ``` +# Filter that is True for message sent not by the user we are logged in as +sent_by_user = ~SenderIsBotFilter() -Filters support bitwise operators to implement complex matching logic. Some -filters set context variables which can be accessed by -`context[CTX_KEY_NAME]`-like syntax. Possible variables are defined in -[this file](src/mab/context.py). Filters are implemented in -[files of this directory](src/mab/filters/). +# 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: +```python +# Define the list of admins +admin_list = [ + "@admin-ivan:matrix.example.org", + "@admin-vladimir:matrix.example.org" +] +# Define the filter +the_filter = ( + MessageReactionFilter() + & ~SenderIsBotFilter() +) +``` + +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** +```python +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 diff --git a/examples/_environment.py b/examples/_environment.py index 75fa6dd..3005147 100644 --- a/examples/_environment.py +++ b/examples/_environment.py @@ -6,13 +6,9 @@ def check_environment() -> None: This function checks if required environment variables are set. It prints problem resolution guide and exits using `sys.exit(1)` on problem. """ - if "MATRIX_HOMESERVER" not in os.environ: - print("Please set `MATRIX_HOMESERVER` environment variable!") - print("P.S. use something like this in your shell:") - print(" export MATRIX_HOMESERVER=\"https://matrix.server.net\"") + if "MAB_SERVER" not in os.environ: + print("Please set `MAB_SERVER` environment variable!") sys.exit(1) - if "MATRIX_USERNAME" not in os.environ: - print("Please set `MATRIX_USERNAME` environment variable!") - print("P.S. use something like this in your shell:") - print(" export MATRIX_USERNAME=\"megakiller228\"") + if "MAB_USER" not in os.environ: + print("Please set `MAB_USER` environment variable!") sys.exit(1) \ No newline at end of file diff --git a/examples/command_bot.py b/examples/command_bot.py index bedfce8..5115469 100644 --- a/examples/command_bot.py +++ b/examples/command_bot.py @@ -116,8 +116,8 @@ async def main() -> None: check_environment() config = MatrixBotConfig( - matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], - matrix_username_localpart=os.environ["MATRIX_USERNAME"], + matrix_homeserver_url=os.environ["MAB_SERVER"], + matrix_username_localpart=os.environ["MAB_USER"], storage_directory="session_storage" ) bot = MatrixBot(config) diff --git a/examples/echo_bot.py b/examples/echo_bot.py index c3e47fe..5ab34e7 100644 --- a/examples/echo_bot.py +++ b/examples/echo_bot.py @@ -24,8 +24,8 @@ async def main() -> None: check_environment() config = MatrixBotConfig( - matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], - matrix_username_localpart=os.environ["MATRIX_USERNAME"], + matrix_homeserver_url=os.environ["MAB_SERVER"], + matrix_username_localpart=os.environ["MAB_USER"], storage_directory="session_storage" ) bot = MatrixBot(config) diff --git a/examples/file_bot.py b/examples/file_bot.py index 535ff1e..37d9f3a 100644 --- a/examples/file_bot.py +++ b/examples/file_bot.py @@ -80,8 +80,8 @@ async def main() -> None: check_environment() config = MatrixBotConfig( - matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], - matrix_username_localpart=os.environ["MATRIX_USERNAME"], + matrix_homeserver_url=os.environ["MAB_SERVER"], + matrix_username_localpart=os.environ["MAB_USER"], storage_directory="session_storage" ) bot = MatrixBot(config) diff --git a/examples/image_bot.py b/examples/image_bot.py index c55c395..88de7f9 100644 --- a/examples/image_bot.py +++ b/examples/image_bot.py @@ -88,8 +88,8 @@ async def main() -> None: check_environment() config = MatrixBotConfig( - matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], - matrix_username_localpart=os.environ["MATRIX_USERNAME"], + matrix_homeserver_url=os.environ["MAB_SERVER"], + matrix_username_localpart=os.environ["MAB_USER"], storage_directory="session_storage" ) bot = MatrixBot(config) diff --git a/examples/reaction_bot.py b/examples/reaction_bot.py index ec02266..7fbd035 100644 --- a/examples/reaction_bot.py +++ b/examples/reaction_bot.py @@ -44,8 +44,8 @@ async def main() -> None: check_environment() config = MatrixBotConfig( - matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], - matrix_username_localpart=os.environ["MATRIX_USERNAME"], + matrix_homeserver_url=os.environ["MAB_SERVER"], + matrix_username_localpart=os.environ["MAB_USER"], storage_directory="session_storage" ) bot = MatrixBot(config) diff --git a/examples/room_bot.py b/examples/room_bot.py index 855906c..153b339 100644 --- a/examples/room_bot.py +++ b/examples/room_bot.py @@ -137,8 +137,8 @@ async def main() -> None: logging.getLogger("nio").setLevel(logging.CRITICAL+1) check_environment() config = MatrixBotConfig( - matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], - matrix_username_localpart=os.environ["MATRIX_USERNAME"], + matrix_homeserver_url=os.environ["MAB_SERVER"], + matrix_username_localpart=os.environ["MAB_USER"], storage_directory="session_storage" ) bot = MatrixBot(config)