Readme update, version update, examples update
This commit is contained in:
145
README.md
145
README.md
@@ -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,78 +23,115 @@ 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`.
|
||||||
|
|
||||||
|
You need to create `MatrixBot` object to create a bot. This is the common way
|
||||||
|
of creating a bot:
|
||||||
```python
|
```python
|
||||||
|
import asyncio
|
||||||
from mab import *
|
from mab import *
|
||||||
|
|
||||||
async def on_media_with_body(ctx: EventContext):
|
# Run until Ctrl+C
|
||||||
"""To be called when a message with image/video and caption is received."""
|
async def main():
|
||||||
print(ctx[CTX_BODY])
|
# 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())
|
||||||
```
|
```
|
||||||
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 *
|
|
||||||
|
|
||||||
filters = (
|
To reduce amount of `if`s in your code, **filters** concept is introduced. When
|
||||||
~SenderIsBotFilter()
|
you add a callback to the instance of the bot, you also provide a filter object.
|
||||||
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO])
|
Filters are created like that:
|
||||||
& BodyExistsFilter()
|
```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()
|
||||||
|
|
||||||
|
# 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()
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
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
|
The concept of **Context Variables** is introduced to avoid the usage of
|
||||||
this:
|
*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
|
```python
|
||||||
from mab import *
|
async def simple_callback(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
|
await ctx.bot.send.text(
|
||||||
# let's assume you create your MatrixBot as `bot` variable here
|
ctx.room,
|
||||||
|
f"You have said `{vars[CTX_MESSAGE].body}`!"
|
||||||
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)
|
|
||||||
|
|
||||||
...
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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/).
|
|
||||||
|
|
||||||
## 🏷️ Versioning
|
## 🏷️ Versioning
|
||||||
|
|
||||||
Releases are tagged in this repository using the `vX.Y.Z` format. If the commit
|
Releases are tagged in this repository using the `vX.Y.Z` format. If the commit
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
Reference in New Issue
Block a user