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 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. 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 ## ✨ Features
The library supports the following features: The library supports the following features:
@@ -27,77 +23,114 @@ install the latest stable version of the library:
```bash ```bash
apt install libmagic1-dev libolm-dev 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` `libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
is needed for E2EE to work. is needed for E2EE to work.
Please inspect [`examples/image_bot.py`](examples/image_bot.py), Please refer to [examples](examples/) for some basic bots. Examples are the best
[`examples/echo_bot.py`](examples/echo_bot.py) or open [`examples/`](examples/) introduction to this library. They are tested manually on each tagged commit.
directory to find usage examples. Examples require that you set You need to set `MAB_SERVER`, `MAB_USER` and `MAB_PASSWORD` environment
`MATRIX_HOMESERVER` and `MATRIX_USERNAME` environment variables. Examples create variables to pass server, username and password to the example.
`session_storage` directory in working directory.
| Variable | Example value |
|----------------|------------------------------|
| `MAB_SERVER` | `https://matrix.example.org` |
| `MAB_USER` | `localusername` |
| `MAB_PASSWORD` | `1337--w4-w1ll-r0ck-y0u!` |
## 🚀 Usage ## 🚀 Usage
If you use `mab`, your application will *most likely* be using **callbacks** to The architecture of `mab` is quite primitive. You define your callback
react to user actions. `mab` uses filter-based callback system to avoid exposing functions, you register them and you start the bot. When an event of interest
raw `nio-matrix` event objects. 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: First of all, most encryption things are done transparently and automatically.
1. **Define the callback as `async` function that take 1 argument of type The most important thing that is not provided by `matrix-nio` is automatic
`EventContext`.** For example, this callback would print the caption of the **asynchronous** decryption of the files you download. You don't need to worry
message: about it **at all** when you use `mab`.
```python
from mab import *
async def on_media_with_body(ctx: EventContext): You need to create `MatrixBot` object to create a bot. This is the common way
"""To be called when a message with image/video and caption is received.""" of creating a bot:
print(ctx[CTX_BODY]) ```python
``` import asyncio
2. **Define the conditions your callback must be called on.** For example, you from mab import *
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 *
filters = ( # Run until Ctrl+C
~SenderIsBotFilter() async def main():
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO]) # Create the config for the bot object
& BodyExistsFilter() bot_config = MatrixBotConfig(
) matrix_homeserver_url="https://matrix.example.org",
``` matrix_username_localpart="username-here",
4. **Add the callback to your `MatrixBot` instance.** For example, if you would storage_directory="session_storage"
have used everything from above, then your code would look something like )
this: # Create the bot itself
```python bot = MatrixBot(bot_config)
from mab import * # 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 reduce amount of `if`s in your code, **filters** concept is introduced. When
"""To be called when a message with image/video and caption is received.""" you add a callback to the instance of the bot, you also provide a filter object.
print(ctx[CTX_BODY]) Filters are created like that:
```python
# Filter that is True for new message
new_message = NewMessageFilter()
filters = ( # Filter that is True for message sent not by the user we are logged in as
~SenderIsBotFilter() sent_by_user = ~SenderIsBotFilter()
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO])
& BodyExistsFilter()
)
bot.add_callback(filters, on_media_with_body)
... # 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 # Filter that is True for messages that have file attached to them
filters set context variables which can be accessed by has_file = MessageHasFileFilter()
`context[CTX_KEY_NAME]`-like syntax. Possible variables are defined in
[this file](src/mab/context.py). Filters are implemented in # Filter that is True for messages with nonempty body
[files of this directory](src/mab/filters/). 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 ## 🏷️ Versioning

View File

@@ -6,13 +6,9 @@ def check_environment() -> None:
This function checks if required environment variables are set. It prints This function checks if required environment variables are set. It prints
problem resolution guide and exits using `sys.exit(1)` on problem. problem resolution guide and exits using `sys.exit(1)` on problem.
""" """
if "MATRIX_HOMESERVER" not in os.environ: if "MAB_SERVER" not in os.environ:
print("Please set `MATRIX_HOMESERVER` environment variable!") print("Please set `MAB_SERVER` environment variable!")
print("P.S. use something like this in your shell:")
print(" export MATRIX_HOMESERVER=\"https://matrix.server.net\"")
sys.exit(1) sys.exit(1)
if "MATRIX_USERNAME" not in os.environ: if "MAB_USER" not in os.environ:
print("Please set `MATRIX_USERNAME` environment variable!") print("Please set `MAB_USER` environment variable!")
print("P.S. use something like this in your shell:")
print(" export MATRIX_USERNAME=\"megakiller228\"")
sys.exit(1) sys.exit(1)

View File

@@ -116,8 +116,8 @@ async def main() -> None:
check_environment() check_environment()
config = MatrixBotConfig( config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MATRIX_USERNAME"], matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage" storage_directory="session_storage"
) )
bot = MatrixBot(config) bot = MatrixBot(config)

View File

@@ -24,8 +24,8 @@ async def main() -> None:
check_environment() check_environment()
config = MatrixBotConfig( config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MATRIX_USERNAME"], matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage" storage_directory="session_storage"
) )
bot = MatrixBot(config) bot = MatrixBot(config)

View File

@@ -80,8 +80,8 @@ async def main() -> None:
check_environment() check_environment()
config = MatrixBotConfig( config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MATRIX_USERNAME"], matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage" storage_directory="session_storage"
) )
bot = MatrixBot(config) bot = MatrixBot(config)

View File

@@ -88,8 +88,8 @@ async def main() -> None:
check_environment() check_environment()
config = MatrixBotConfig( config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MATRIX_USERNAME"], matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage" storage_directory="session_storage"
) )
bot = MatrixBot(config) bot = MatrixBot(config)

View File

@@ -44,8 +44,8 @@ async def main() -> None:
check_environment() check_environment()
config = MatrixBotConfig( config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MATRIX_USERNAME"], matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage" storage_directory="session_storage"
) )
bot = MatrixBot(config) bot = MatrixBot(config)

View File

@@ -137,8 +137,8 @@ async def main() -> None:
logging.getLogger("nio").setLevel(logging.CRITICAL+1) logging.getLogger("nio").setLevel(logging.CRITICAL+1)
check_environment() check_environment()
config = MatrixBotConfig( config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"], matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MATRIX_USERNAME"], matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage" storage_directory="session_storage"
) )
bot = MatrixBot(config) bot = MatrixBot(config)