Readme update, version update, examples update

This commit is contained in:
2026-12-01 21:22:57 +03:00
parent d442aa7322
commit 86b1c6c142
8 changed files with 109 additions and 80 deletions

151
README.md
View File

@@ -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])
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()
filters = (
~SenderIsBotFilter()
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO])
& BodyExistsFilter()
)
bot.add_callback(filters, on_media_with_body)
# Filter that is True for message sent not by the user we are logged in as
sent_by_user = ~SenderIsBotFilter()
...
```
# 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)
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 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

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)