Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b99b2fa9bf | |||
| 86b1c6c142 | |||
| d442aa7322 | |||
| 2ace008068 | |||
| 3b929a1d88 | |||
| cbbafb7778 | |||
| eab2e8acb8 | |||
| 05a286b57a | |||
| 4b4c434bd8 | |||
| b7a471659d | |||
| d758bdedac | |||
| b5210359b1 | |||
| ada7af9dd6 | |||
| d5367ebc6b | |||
| eacb0c0d25 | |||
| 33efd5e104 | |||
| 17031500e9 | |||
| afcd3f53f4 | |||
| b22e7b4903 | |||
| 2867582c01 | |||
| 16b849ebd8 | |||
| 35bd68516a | |||
| 86257a70e3 | |||
| 43b5d8e3a6 | |||
| 0e9b621895 | |||
| f3f1e24c0b | |||
| 2e4228b22a | |||
| 0b79d78715 | |||
| a90cd66d3e | |||
| cb520814d8 | |||
| 4287a0d20c | |||
| e10c920a56 | |||
| 156afd6b61 | |||
| 2d47483d55 | |||
| fc4f664a5c | |||
| fa97e4b098 | |||
| 1fe4434e16 | |||
| 4f0792b9aa | |||
| 31fbcb4697 | |||
| 3e15ae426c | |||
| b8e598715c | |||
| f58c8601d1 | |||
| 159a43ebe6 | |||
| 9f4cd4948a | |||
| d14e110525 | |||
| 3d74cb737b | |||
| 7d6230881b | |||
| 5fd87879ca | |||
| 90c5ae7a78 | |||
| 1ba1094a42 | |||
| 0ea2b0e51a | |||
|
|
363b9a3d45 | ||
|
|
bc3a7500e2 | ||
|
|
8dd1f55fdd | ||
| b62473c468 | |||
| d8bf1818d7 | |||
| d41b588adc |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -1,6 +1,9 @@
|
||||
__pycache__/
|
||||
session_storage/
|
||||
*.vscode
|
||||
.venv/
|
||||
dist/
|
||||
*.egg-info/
|
||||
*.swp
|
||||
*.swo
|
||||
*.swo
|
||||
*.tmp
|
||||
186
README.md
186
README.md
@@ -1,58 +1,160 @@
|
||||
# mab
|
||||
# 🤖 mab
|
||||
|
||||
**mab** *(MAtrix Bot)* is a **very** simple Python package that can be used to
|
||||
develop **very** simple Matrix bots. I have decided to make something like this
|
||||
because I wasn't satisfied by simplicity and usage of other libraries. So
|
||||
this library does not aim to be "the best matrix bot library", it only aims to
|
||||
be good enough for me.
|
||||
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.
|
||||
|
||||
## Installation
|
||||
## ✨ Features
|
||||
|
||||
Use `pip` to install this package:
|
||||
The library supports the following features:
|
||||
- **Completely `asyncio` based**
|
||||
- **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:
|
||||
|
||||
```bash
|
||||
python -m pip install git+https://git.tyukalov.su/nikita/mab
|
||||
apt install libmagic1-dev libolm-dev
|
||||
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.7.1
|
||||
```
|
||||
|
||||
## Basic usage
|
||||
`libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
|
||||
is needed for E2EE to work.
|
||||
|
||||
This is the most simple bot you can create
|
||||
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
|
||||
|
||||
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:
|
||||
```python
|
||||
import asyncio
|
||||
from mab import MatrixBot, MatrixBotConfig
|
||||
from nio import MatrixRoom, MatrixMessageText
|
||||
from mab import *
|
||||
|
||||
bot: MatrixBot
|
||||
|
||||
async def on_room_message_text(room: MatrixRoom, event: RoomMessageText) -> None:
|
||||
global bot
|
||||
# do not respond to ourselves
|
||||
if event.sender == bot.get_client().user_id:
|
||||
return
|
||||
text = f"You message contains {len(event.body)} symbols"
|
||||
await bot.send_text_to_room(room.room_id, text)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
global bot
|
||||
# create and start the bot
|
||||
cfg = MatrixBotConfig(
|
||||
matrix_homeserver_url="matrix.domain.su",
|
||||
matrix_username_localpart="nagibator666",
|
||||
storage_directory=Path("storage_nagibator666")
|
||||
# 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"
|
||||
)
|
||||
bot = MatrixBot(matrix_bot_config)
|
||||
bot.start()
|
||||
# wait for Ctrl+C
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except:
|
||||
pass
|
||||
# stop the bot
|
||||
await bot.stop()
|
||||
# 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()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
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()
|
||||
|
||||
# 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
|
||||
|
||||
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 that `0.Y.Z` versions 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`.
|
||||
```bash
|
||||
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 .
|
||||
```
|
||||
72
docs/ContextVariables.md
Normal file
72
docs/ContextVariables.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# For `mab` user
|
||||
|
||||
## What is Context Variable?
|
||||
|
||||
**Context Variables** system is used to get rid of `matrix-nio` when possible.
|
||||
To keep it short let's just say that `mab` looks at the event returned by
|
||||
`matrix-nio` and tries to convert it to simplified `pydantic` model.
|
||||
Simplified model is more than enough in most cases but you can use raw events
|
||||
if needed.
|
||||
|
||||
## How do Context Variables work?
|
||||
|
||||
From user's perspective the system is quite easy. Your event callback takes
|
||||
two positional arguments: `ctx` (of type `EventContext`) and `vars` (of type
|
||||
`ContextVars`). One should use `ctx` argument to access raw `matrix-nio` data
|
||||
and `MatrixBot` that has invoked the callback. `vars` should be used when you'd
|
||||
like to access simplified data model (e.g. get message body or attached file
|
||||
size). Example callback syntax that uses both:
|
||||
```python
|
||||
from mab import *
|
||||
|
||||
...
|
||||
|
||||
async def callback(ctx: EventContext, vars: ContextVars) -> None:
|
||||
response = f"Your message text is '{vars[CTX_MESSAGE].body}'"
|
||||
await ctx.bot.send.text(ctx.room, response)
|
||||
...
|
||||
```
|
||||
`CTX_MESSAGE` is so called **variable key** that you should use to access the
|
||||
context variable. If the key is not set then `RuntimeError` will be raised.
|
||||
|
||||
# For `mab` developer
|
||||
|
||||
The following rules must be considered when adding new context variables or
|
||||
models:
|
||||
1. If a model can be added to existing subpackage of `mab.context.vars` then
|
||||
it should be added there
|
||||
2. If a model does not fit into any existing subpackage then a new subpackage
|
||||
must be introduced
|
||||
3. `src/mab/context/vars/SUBPACKAGE/types.py` must **ALWAYS** exist and define
|
||||
types related to the subpackage (e.g. `message` subpackage introduces
|
||||
`Message` model)
|
||||
4. `src/mab/context/vars/SUBPACKAGE/keys.py` must exist if the subpackage
|
||||
introduces keys used with `ContextVars` (e.g. `message` subpackage
|
||||
introduces `CTX_MESSAGE` key)
|
||||
5. `src/mab/context/vars/SUBPACKAGE/builders.py` must exist if the subpackage
|
||||
introduces so called **autobuilders** - functions decorated with the
|
||||
following syntax:
|
||||
```python
|
||||
@mab.context.vars.ContextVarsPopulator.autobuilder
|
||||
async def _example_autobuilder(ctx: EventContext, vars: ContextVars) -> None:
|
||||
vars[CTX_EXAMPLE] = Example(example=1)
|
||||
```
|
||||
Functions decorated like this will be called when a new event is returned
|
||||
by `matrix-nio`.
|
||||
6. `__init__.py` of a subpackage must **ALWAYS** exist and have the following
|
||||
structure:
|
||||
```python
|
||||
from .types import *
|
||||
from .keys import *
|
||||
from . import builders # if exists
|
||||
```
|
||||
The goal of `__init__.py` is to make sure that `builders.py` is imported and
|
||||
to introduce members of `types.py` and `keys.py` into its namespace.
|
||||
7. All subpackages must be imported in `src/mab/__init__.py` using the
|
||||
following syntax:
|
||||
```python
|
||||
from .context.vars.command import *
|
||||
from .context.vars.message import *
|
||||
```
|
||||
|
||||
Please refer to `src/mab/context/vars/` for examples
|
||||
14
examples/_environment.py
Normal file
14
examples/_environment.py
Normal file
@@ -0,0 +1,14 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
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 "MAB_SERVER" not in os.environ:
|
||||
print("Please set `MAB_SERVER` environment variable!")
|
||||
sys.exit(1)
|
||||
if "MAB_USER" not in os.environ:
|
||||
print("Please set `MAB_USER` environment variable!")
|
||||
sys.exit(1)
|
||||
145
examples/command_bot.py
Normal file
145
examples/command_bot.py
Normal file
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
This example implements Matrix bot that can execute some commands.
|
||||
|
||||
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||
the bot.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import html
|
||||
import os
|
||||
import traceback
|
||||
import logging
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_help_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!help"""
|
||||
HELP_MESSAGE = (
|
||||
"<strong>Here is the list of the commands:</strong><br>"
|
||||
"<ul>"
|
||||
"<li><code>!help</code> - this help message</li>"
|
||||
"<li><code>!time</code> - get UNIX timestamp</li>"
|
||||
"<li><code>!raise</code> - raise <code>RuntimeError()</code></li>"
|
||||
"<li><code>!assert</code> - perform <code>assert</code> that will fail</li>"
|
||||
"<li><code>!mul A B [C] [D]...</code> - multiply A, B... and so on</li>"
|
||||
"<li><code>!args arg1 [arg2] ... [arg5]</code> - command that takes 1..5 arguments</li>"
|
||||
"</ul>"
|
||||
)
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
HELP_MESSAGE,
|
||||
is_html=True
|
||||
)
|
||||
|
||||
async def on_time_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!time"""
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
f"Current UNIX timestamp is <strong>{int(time.time())}</strong>",
|
||||
is_html=True
|
||||
)
|
||||
|
||||
async def on_raise_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!raise"""
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"<strong>Executing <code>raise RuntimeError()</code>...</strong>",
|
||||
is_html=True
|
||||
)
|
||||
raise RuntimeError()
|
||||
|
||||
async def on_assert_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!assert"""
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"<strong>Executing <code>assert False</code>...</strong>",
|
||||
is_html=True
|
||||
)
|
||||
assert False
|
||||
|
||||
async def on_mul_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!mul"""
|
||||
try:
|
||||
numbers = [float(v) for v in vars[CTX_COMMAND].args]
|
||||
v = numbers[0]
|
||||
for n in numbers[1:]:
|
||||
v *= n
|
||||
response = " * ".join(html.escape("%.2f" % n) for n in numbers)
|
||||
response += f" = <strong>{html.escape(str(v))}<strong>"
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
response,
|
||||
is_html=True
|
||||
)
|
||||
except Exception as e:
|
||||
await ctx.bot.send.text(ctx.room, f"Could not process the command: {e}")
|
||||
|
||||
async def on_args_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!args"""
|
||||
try:
|
||||
response = (
|
||||
f"Prefix: <code>{vars[CTX_COMMAND].prefix}</code><br>"
|
||||
f"Verb: <code>{vars[CTX_COMMAND].verb}</code><br>"
|
||||
f"Arguments: <code>{len(vars[CTX_COMMAND].args)}</code><br>"
|
||||
f"Arguments are:<br><ol>"
|
||||
)
|
||||
for arg in vars[CTX_COMMAND].args:
|
||||
response += f"<li><code>{html.escape(arg)}</code></li>"
|
||||
response += "</ol>"
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
response,
|
||||
is_html=True
|
||||
)
|
||||
except:
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
f"Could not process the command: {traceback.format_exc()}"
|
||||
)
|
||||
|
||||
async def invalid_usage(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when the bot used incorrectly."""
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"Use <code>!help</code>",
|
||||
is_html=True)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||
check_environment()
|
||||
|
||||
config = MatrixBotConfig(
|
||||
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||
matrix_username_localpart=os.environ["MAB_USER"],
|
||||
storage_directory="session_storage"
|
||||
)
|
||||
bot = MatrixBot(config)
|
||||
|
||||
COMMANDS = {
|
||||
on_help_command: BodyCommandFilter(["help", "?"]),
|
||||
on_time_command: BodyCommandFilter("time"),
|
||||
on_raise_command: BodyCommandFilter("raise"),
|
||||
on_assert_command: BodyCommandFilter("assert"),
|
||||
on_mul_command: BodyCommandFilter("mul", min_args=2),
|
||||
on_args_command: BodyCommandFilter("args", min_args=1, max_args=5),
|
||||
}
|
||||
for callback, filter in COMMANDS.items():
|
||||
f = ~SenderIsBotFilter() & filter
|
||||
bot.add_callback(f, callback)
|
||||
bot.add_callback(~SenderIsBotFilter() & NewMessageFilter(), invalid_usage)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
43
examples/echo_bot.py
Normal file
43
examples/echo_bot.py
Normal file
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
This example implements Matrix bot that echoes all text messages it receives.
|
||||
|
||||
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||
the bot.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import logging
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_text_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a text message arrives."""
|
||||
await ctx.bot.send.text(ctx.room, vars[CTX_MESSAGE].body)
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||
check_environment()
|
||||
|
||||
config = MatrixBotConfig(
|
||||
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||
matrix_username_localpart=os.environ["MAB_USER"],
|
||||
storage_directory="session_storage"
|
||||
)
|
||||
bot = MatrixBot(config)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
|
||||
on_text_message)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
102
examples/file_bot.py
Normal file
102
examples/file_bot.py
Normal file
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
This example implements Matrix bot that calculates SHA256 for a file sent by
|
||||
user.
|
||||
|
||||
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||
the bot.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import aiofiles
|
||||
import os
|
||||
import logging
|
||||
import hashlib
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_text_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a text message arrives."""
|
||||
await ctx.bot.send.text(ctx.room, "Please send a file/image/video/audio")
|
||||
|
||||
async def on_file_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a file arrives."""
|
||||
sha = hashlib.sha256()
|
||||
does_temp_exist = False
|
||||
file = vars[CTX_MESSAGE].file
|
||||
if not file:
|
||||
return
|
||||
if not file.filesize:
|
||||
file.filesize = 0
|
||||
if file.filesize > 1_000_000:
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"The file is larger than 1 MB, downloading to filesystem"
|
||||
)
|
||||
await ctx.bot.download.file(ctx, path="temp.tmp")
|
||||
async with aiofiles.open("temp.tmp", "rb") as f:
|
||||
while True:
|
||||
data = await f.read(64 * 1024)
|
||||
if not data:
|
||||
break
|
||||
sha.update(data)
|
||||
does_temp_exist = True
|
||||
else:
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"The file is smaller than 1 MB, downloading to RAM"
|
||||
)
|
||||
content = await ctx.bot.download.file(ctx, path=None)
|
||||
sha.update(content)
|
||||
# result
|
||||
response = f"SHA256 for file `{file.filename}`"
|
||||
response += f" ({file.filesize} bytes, {file.filename})"
|
||||
await ctx.bot.send.file_bytes(
|
||||
room=ctx.room,
|
||||
data=sha.hexdigest().encode("utf-8"),
|
||||
filename="hash of the file.txt",
|
||||
mime_type="text/plain",
|
||||
text=response
|
||||
)
|
||||
# resend the file to test uploading
|
||||
if does_temp_exist:
|
||||
await ctx.bot.send.file(
|
||||
room=ctx.room,
|
||||
path="temp.tmp",
|
||||
filename=file.filename,
|
||||
text="This is the file you have sent, but it was reuploaded"
|
||||
)
|
||||
try:
|
||||
os.unlink("temp.tmp")
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||
check_environment()
|
||||
|
||||
config = MatrixBotConfig(
|
||||
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||
matrix_username_localpart=os.environ["MAB_USER"],
|
||||
storage_directory="session_storage"
|
||||
)
|
||||
bot = MatrixBot(config)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
|
||||
on_text_message)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & MessageHasFileFilter() & NewMessageFilter(),
|
||||
on_file_message)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
130
examples/image_bot.py
Normal file
130
examples/image_bot.py
Normal file
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
This example implements Matrix bot that generates a pixelized noise image with
|
||||
specified maximum R, G and B values.
|
||||
|
||||
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||
the bot.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import random
|
||||
from PIL import Image, ImageFilter
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_gen_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when `!gen R G B` command is received."""
|
||||
# convert R, G and B to floats
|
||||
try:
|
||||
r, g, b = [float(f) for f in vars[CTX_COMMAND].args]
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, "Invalid arguments")
|
||||
return
|
||||
await ctx.bot.send.text(ctx.room, "Generating the noise...")
|
||||
# create the basic noise
|
||||
img = Image.new("RGB", (16, 16))
|
||||
for x in range(img.width):
|
||||
for y in range(img.height):
|
||||
col = (random.random() * r, random.random() * g, random.random() * b)
|
||||
img.putpixel(
|
||||
(x, y),
|
||||
tuple(int(c * 255) for c in col)
|
||||
)
|
||||
# pixelized upscale
|
||||
img = img.resize((2048, 2048), resample=Image.Resampling.NEAREST)
|
||||
# save to buffer
|
||||
buf = BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
buf.seek(0)
|
||||
buf = buf.read()
|
||||
# send
|
||||
await ctx.bot.send.image_bytes(ctx.room, buf, "noise.png")
|
||||
|
||||
async def on_image(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when an image is received."""
|
||||
# download
|
||||
s = time.time()
|
||||
data = await ctx.bot.download.file(ctx)
|
||||
took_time = time.time() - s
|
||||
# convert to Image
|
||||
with BytesIO(data) as buf:
|
||||
img = Image.open(buf)
|
||||
# apply effects
|
||||
blur = ImageFilter.GaussianBlur(
|
||||
radius=min(img.size[0] // 10, 5)
|
||||
)
|
||||
img = img.filter(blur)
|
||||
# save to buffer
|
||||
buf = BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
buf.seek(0)
|
||||
buf = buf.read()
|
||||
# send
|
||||
await ctx.bot.send.image_bytes(
|
||||
ctx.room,
|
||||
buf,
|
||||
"blurred.png",
|
||||
text="Download and decryption took %.4f seconds" % took_time
|
||||
)
|
||||
|
||||
async def on_wrong_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a wrong message is received."""
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"Text me something like <code>!gen 0.1 0.7 1.0</code> or send an image to blur",
|
||||
is_html=True
|
||||
)
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||
check_environment()
|
||||
|
||||
config = MatrixBotConfig(
|
||||
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||
matrix_username_localpart=os.environ["MAB_USER"],
|
||||
storage_directory="session_storage"
|
||||
)
|
||||
bot = MatrixBot(config)
|
||||
command_filter = MessageTypeFilter(MessageType.TEXT) & BodyCommandFilter(
|
||||
verbs=["gen"],
|
||||
min_args=3,
|
||||
max_args=3
|
||||
)
|
||||
|
||||
# callback for message that
|
||||
# 1. are sent not by this bot
|
||||
# 2. do match the command filter
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & command_filter,
|
||||
on_gen_command)
|
||||
|
||||
# callback for new image message
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & MessageTypeFilter(MessageType.IMAGE) & NewMessageFilter(),
|
||||
on_image
|
||||
)
|
||||
|
||||
# callback for message that
|
||||
# 1. are sent not by this bot
|
||||
# 2. are new messages (not edits)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & BodyExistsFilter() & NewMessageFilter(),
|
||||
on_wrong_message
|
||||
)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
81
examples/reaction_bot.py
Normal file
81
examples/reaction_bot.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
This example implements Matrix bot that works with reactions.
|
||||
|
||||
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||
the bot.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import logging
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def bump_count(bot: MatrixBot) -> int:
|
||||
"""Bump count of reactions processed and return new value. Uses bot's
|
||||
database for storage."""
|
||||
val = await bot.load_value("reactions_processed")
|
||||
val = 0 if val is None else int.from_bytes(val)
|
||||
val += 1
|
||||
await bot.save_value("reactions_processed", val.to_bytes(8))
|
||||
return val
|
||||
|
||||
async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a specific reaction is added."""
|
||||
sender = vars[CTX_REACTION].sender
|
||||
reaction = vars[CTX_REACTION].reaction
|
||||
count = await bump_count(ctx.bot)
|
||||
response = f"(Specific reaction) {sender}: {reaction}. Total reactions processed: {count}"
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
response
|
||||
)
|
||||
|
||||
async def on_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a reaction is added."""
|
||||
sender = vars[CTX_REACTION].sender
|
||||
reaction = vars[CTX_REACTION].reaction
|
||||
count = await bump_count(ctx.bot)
|
||||
response = f"(Generic reaction) {sender}: {reaction}. Total reactions processed: {count}"
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
response
|
||||
)
|
||||
|
||||
async def on_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a message is received."""
|
||||
await bump_count(ctx.bot)
|
||||
await ctx.bot.send.reaction(ctx.room, vars[CTX_ROOM_EVENT].event_id, "👀")
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||
check_environment()
|
||||
|
||||
config = MatrixBotConfig(
|
||||
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||
matrix_username_localpart=os.environ["MAB_USER"],
|
||||
storage_directory="session_storage"
|
||||
)
|
||||
bot = MatrixBot(config)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & MessageReactionFilter(reaction=["❤️", "👍"]),
|
||||
on_specific_reaction)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & MessageReactionFilter(),
|
||||
on_reaction)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & NewMessageFilter(),
|
||||
on_message)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
240
examples/room_bot.py
Normal file
240
examples/room_bot.py
Normal file
@@ -0,0 +1,240 @@
|
||||
"""
|
||||
This example implements Matrix bot that does some rooms stuff.
|
||||
|
||||
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||
the bot.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import random
|
||||
import traceback
|
||||
import logging
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_help_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""Help message"""
|
||||
RESPONSE = (
|
||||
"Here's how you use the bot:"
|
||||
"\n"
|
||||
"\n!create - create a new room"
|
||||
"\n!leave - leave the room"
|
||||
"\n!forget - leave the room and forget it"
|
||||
"\n!join <room_id> - join the room (requires invitation)"
|
||||
"\n!invite <room_id> <user_id> - invite the user to the room"
|
||||
"\n!kick <room_id> <user_id> - kick the user from the room"
|
||||
"\n!ban <room_id> <user_id> - ban the user from the room"
|
||||
"\n!unban <room_id> <user_id> - unban the user from the room"
|
||||
"\n!members <room_id> - get list of room members"
|
||||
)
|
||||
await ctx.bot.send.text(ctx.room, RESPONSE)
|
||||
|
||||
async def on_cmd_create(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!create"""
|
||||
await ctx.bot.rooms.create()
|
||||
alias = "".join([random.choice("abcdefghj") for i in range(10)])
|
||||
name = alias.capitalize()
|
||||
topic = "This room was craeted by the example bot"
|
||||
try:
|
||||
res = await ctx.bot.rooms.create(
|
||||
alias=alias,
|
||||
name=name,
|
||||
topic=topic,
|
||||
invite_list=[vars[CTX_ROOM_EVENT].sender]
|
||||
)
|
||||
await ctx.bot.send.text(ctx.room, f"Created the room {res}")
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def on_cmd_leave(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!leave"""
|
||||
await ctx.bot.send.text(ctx.room, "Leaving this room")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.leave(ctx.room)
|
||||
|
||||
async def on_cmd_forget(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!forget"""
|
||||
await ctx.bot.send.text(ctx.room, "Leaving the room and forgetting it")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.leave(ctx.room)
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.forget(ctx.room)
|
||||
|
||||
async def on_cmd_join(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!join"""
|
||||
try:
|
||||
room_id = vars[CTX_COMMAND].args[0]
|
||||
await ctx.bot.send.text(ctx.room, f"Joining the room {room_id}")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.join(room_id)
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def on_cmd_invite(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!invite"""
|
||||
try:
|
||||
room_id = vars[CTX_COMMAND].args[0]
|
||||
user_id = vars[CTX_COMMAND].args[1]
|
||||
await ctx.bot.send.text(ctx.room, f"Inviting {user_id} to {room_id}")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.invite(room_id, user_id)
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def on_cmd_kick(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!kick"""
|
||||
try:
|
||||
room_id = vars[CTX_COMMAND].args[0]
|
||||
user_id = vars[CTX_COMMAND].args[1]
|
||||
await ctx.bot.send.text(ctx.room, f"Kicking {user_id} from {room_id}")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.kick(room_id, user_id, "Testing rooms")
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def on_cmd_ban(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!ban"""
|
||||
try:
|
||||
room_id = vars[CTX_COMMAND].args[0]
|
||||
user_id = vars[CTX_COMMAND].args[1]
|
||||
await ctx.bot.send.text(ctx.room, f"Banning {user_id} in {room_id}")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.ban(room_id, user_id, "Testing rooms")
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def on_cmd_unban(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!unban"""
|
||||
try:
|
||||
room_id = vars[CTX_COMMAND].args[0]
|
||||
user_id = vars[CTX_COMMAND].args[1]
|
||||
await ctx.bot.send.text(ctx.room, f"Unbanning {user_id} in {room_id}")
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.rooms.unban(room_id, user_id)
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def on_cmd_members(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!members"""
|
||||
try:
|
||||
room_id = vars[CTX_COMMAND].args[0]
|
||||
await ctx.bot.send.text(ctx.room, f"Listing members of {room_id}")
|
||||
await asyncio.sleep(1)
|
||||
members = await ctx.bot.rooms.members(room_id)
|
||||
for m in members:
|
||||
await ctx.bot.send.text(ctx.room, f"{m.display_name} - {m.user_id}", is_html=False)
|
||||
await asyncio.sleep(1)
|
||||
await ctx.bot.send.text(ctx.room, f"Done")
|
||||
except:
|
||||
await ctx.bot.send.text(ctx.room, traceback.format_exc())
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||
check_environment()
|
||||
config = MatrixBotConfig(
|
||||
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||
matrix_username_localpart=os.environ["MAB_USER"],
|
||||
storage_directory="session_storage"
|
||||
)
|
||||
bot = MatrixBot(config)
|
||||
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("create")
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_create
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("leave")
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_leave
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("forget")
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_forget
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("join", min_args=1)
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_join
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("invite", min_args=2)
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_invite
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("kick", min_args=2)
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_kick
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("ban", min_args=2)
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_ban
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("unban", min_args=2)
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_unban
|
||||
)
|
||||
#
|
||||
fitler = (
|
||||
~SenderIsBotFilter()
|
||||
& BodyCommandFilter("members", min_args=1)
|
||||
)
|
||||
bot.add_callback(
|
||||
fitler,
|
||||
on_cmd_members
|
||||
)
|
||||
#
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & NewMessageFilter() & BodyExistsFilter(),
|
||||
on_help_message
|
||||
)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -4,49 +4,23 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "mab"
|
||||
version = "0.0.1"
|
||||
version = "0.7.1"
|
||||
authors = [
|
||||
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
|
||||
]
|
||||
description = "Very simple async matrix bot library"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
requires-python = ">=3.13"
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Operating System :: OS Independent",
|
||||
]
|
||||
dependencies = [
|
||||
"aioconsole==0.8.2",
|
||||
"aiofiles==25.1.0",
|
||||
"aiohappyeyeballs==2.7.1",
|
||||
"aiohttp==3.14.3",
|
||||
"aiohttp_socks==0.12.0",
|
||||
"aiosignal==1.4.0",
|
||||
"atomicwrites==1.4.1",
|
||||
"attrs==26.1.0",
|
||||
"build==1.5.0",
|
||||
"cachetools==7.1.7",
|
||||
"frozenlist==1.8.0",
|
||||
"h11==0.16.0",
|
||||
"h2==4.4.1",
|
||||
"hpack==4.2.0",
|
||||
"hyperframe==6.1.0",
|
||||
"idna==3.19",
|
||||
"jsonschema==4.26.0",
|
||||
"jsonschema-specifications==2025.9.1",
|
||||
"matrix-nio==0.26.0",
|
||||
"multidict==6.7.1",
|
||||
"packaging==26.3",
|
||||
"peewee==3.19.0",
|
||||
"propcache==0.5.2",
|
||||
"pycryptodome==3.23.0",
|
||||
"pyproject_hooks==1.2.0",
|
||||
"python-socks==3.0.0",
|
||||
"referencing==0.37.0",
|
||||
"rpds-py==2026.6.3",
|
||||
"unpaddedbase64==2.1.0",
|
||||
"vodozemac==0.10.0",
|
||||
"yarl==1.24.5",
|
||||
"matrix-nio[e2e]==0.26.0",
|
||||
"aiosqlite==0.22.1",
|
||||
"python-magic==0.4.27",
|
||||
"pillow==12.3.0",
|
||||
"pydantic==2.14.4"
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
from . import bot
|
||||
from . import types
|
||||
|
||||
# Bot and its config types
|
||||
from .bot import MatrixBot
|
||||
from .types import MatrixBotConfig
|
||||
|
||||
from .bot import MatrixBot
|
||||
# Introduce all filters into mab namespace
|
||||
from .filters import *
|
||||
|
||||
__all__ = [
|
||||
# module names
|
||||
"bot",
|
||||
"types",
|
||||
# Types for callback arguments
|
||||
from .context import EventContext
|
||||
from .context.vars import ContextVars
|
||||
|
||||
# .types
|
||||
"MatrixBotConfig",
|
||||
|
||||
# .bot
|
||||
"MatrixBot"
|
||||
]
|
||||
# Context variables
|
||||
from .context.vars.command import *
|
||||
from .context.vars.message import *
|
||||
from .context.vars.reaction import *
|
||||
from .context.vars.room_event import *
|
||||
512
src/mab/bot.py
512
src/mab/bot.py
@@ -1,512 +0,0 @@
|
||||
import asyncio
|
||||
import aiofiles
|
||||
import aioconsole
|
||||
import traceback
|
||||
import logging
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from html.parser import HTMLParser
|
||||
from urllib.parse import urlparse
|
||||
from typing import Any, Callable, Awaitable
|
||||
|
||||
from nio import AsyncClient, AsyncClientConfig, SyncResponse
|
||||
from nio import LoginResponse, LoginError, WhoamiResponse, WhoamiError
|
||||
|
||||
from nio import RoomSendResponse, RoomSendError
|
||||
|
||||
from nio import OlmUnverifiedDeviceError
|
||||
|
||||
from nio import MatrixInvitedRoom, InviteMemberEvent
|
||||
from nio import JoinResponse
|
||||
|
||||
import nio.events
|
||||
|
||||
from .types import *
|
||||
|
||||
|
||||
class MatrixBot:
|
||||
"""Asynchronous Matrix Bot Implementation.
|
||||
|
||||
Use objects of this class to build your bots. Manage the event loop
|
||||
by yourself.
|
||||
"""
|
||||
NEXT_BATCH_DUMP_PERIOD = 120.0
|
||||
MATRIX_SYNC_PERIOD = 5000
|
||||
|
||||
#
|
||||
# PRIVATE
|
||||
#
|
||||
@staticmethod
|
||||
def _validate_matrix_homeserver_url(url: str) -> None:
|
||||
"""Checks if `url` is a valid matrix homeserver URL.
|
||||
Raises an Exception if it is not.
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise RuntimeError(
|
||||
f"Scheme {parsed.scheme} is not a valid scheme for matrix homeserver URL"
|
||||
)
|
||||
if not parsed.netloc:
|
||||
raise RuntimeError(f"{url} is not a valid matrix homeserver URL")
|
||||
if parsed.path != "":
|
||||
raise RuntimeError(f"{url} must have empty path (remove `{parsed.path}` after the hostname)")
|
||||
|
||||
@staticmethod
|
||||
def _validate_matrix_username_localpart(localpart: str) -> None:
|
||||
"""Checks if `username` is a valid localpart of matrix username.
|
||||
Raises an Exception if it is not.
|
||||
"""
|
||||
pattern = r"^[a-z0-9._=\-]+$"
|
||||
if not bool(re.fullmatch(pattern, localpart)) or len(localpart) > 255:
|
||||
raise RuntimeError(f"{localpart} is not a valid matrix username localpart")
|
||||
|
||||
@staticmethod
|
||||
def _validate_storage_directory(path: Path) -> None:
|
||||
"""Checks if `path` is a valid storage directory and creates it.
|
||||
Raises an Exception if it is not.
|
||||
"""
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
if not path.is_dir():
|
||||
raise RuntimeError(f"Could not create directory {path}")
|
||||
|
||||
@staticmethod
|
||||
def _validate_bot_config(config: MatrixBotConfig) -> None:
|
||||
"""Checks if `config` has errors.
|
||||
Raises an Exception if it does.
|
||||
"""
|
||||
MatrixBot._validate_matrix_homeserver_url(config.matrix_homeserver_url)
|
||||
MatrixBot._validate_matrix_username_localpart(config.matrix_username_localpart)
|
||||
MatrixBot._validate_storage_directory(config.storage_directory)
|
||||
|
||||
@staticmethod
|
||||
def _build_client(config: MatrixBotConfig) -> AsyncClient:
|
||||
"""Builds `nio.AsyncClient` from `MatrixBotConfig`"""
|
||||
# create the config for the client
|
||||
client_config = AsyncClientConfig(
|
||||
store_name="nio_store_file",
|
||||
encryption_enabled=True,
|
||||
store_sync_tokens=False
|
||||
)
|
||||
# create the client
|
||||
client = AsyncClient(
|
||||
homeserver=config.matrix_homeserver_url,
|
||||
user=config.matrix_username_localpart,
|
||||
store_path=str(config.storage_directory),
|
||||
config=client_config
|
||||
)
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def _build_matrix_username(config: MatrixBotConfig) -> str:
|
||||
"""Builds full matrix username."""
|
||||
homeserver_name = urlparse(config.matrix_homeserver_url).hostname
|
||||
localpart = config.matrix_username_localpart
|
||||
return f"@{localpart}:{homeserver_name}"
|
||||
|
||||
@staticmethod
|
||||
def _check_and_remove_html(text_to_check: str) -> tuple[bool, str]:
|
||||
"""Checks if `text_to_check` is HTML and sanitizes it.
|
||||
|
||||
Returns:
|
||||
tuple[bool, str] where the first element is True if `text_to_check` contains
|
||||
valid HTML, and the second element is text without HTML (or just copy of
|
||||
`text_to_check` if it does not contain HTML)
|
||||
"""
|
||||
has_tags = False
|
||||
text_fragments = []
|
||||
class Extractor(HTMLParser):
|
||||
def handle_starttag(self, tag, attrs):
|
||||
nonlocal has_tags
|
||||
has_tags = True
|
||||
def handle_data(self, data):
|
||||
text_fragments.append(data)
|
||||
parser = Extractor(convert_charrefs=True)
|
||||
parser.feed(text_to_check)
|
||||
try:
|
||||
if has_tags:
|
||||
return (True, " ".join("".join(text_fragments).split()))
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return (False, text_to_check)
|
||||
|
||||
@staticmethod
|
||||
async def _wait_for_task_and_stop_event(payload_task: asyncio.Task, stop_wait_task: asyncio.Task, print_exc: bool = False) -> Any:
|
||||
"""Waits for `payload_task` to finish. Uses `stop_wait_task` to check if payload task
|
||||
should be cancelled. Returns value returned by `payload_task` task. Raises exception
|
||||
raised by `payload_task` task.
|
||||
|
||||
If `stop_wait_task` finishes, then `asyncio.CancelledError` is raised.
|
||||
"""
|
||||
try:
|
||||
done, _ = await asyncio.wait(
|
||||
[payload_task, stop_wait_task],
|
||||
return_when=asyncio.FIRST_COMPLETED
|
||||
)
|
||||
if stop_wait_task in done:
|
||||
payload_task.cancel()
|
||||
await payload_task
|
||||
raise asyncio.CancelledError()
|
||||
return payload_task.result()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
if print_exc:
|
||||
traceback.print_exc()
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
async def _default_password_callback() -> str:
|
||||
"""Gets password from `MATRIX_PASSWORD` envvar if it is set. Asks
|
||||
the user for the password otherwise."""
|
||||
if "MATRIX_PASSWORD" in os.environ:
|
||||
return os.environ["MATRIX_PASSWORD"]
|
||||
print("--- A password is required (btw you might use MATRIX_PASSWORD envvar) ---")
|
||||
return await aioconsole.ainput("Password: ")
|
||||
|
||||
@staticmethod
|
||||
async def _debug_event_callback(*args, **kwargs) -> None:
|
||||
"""Just prints types of arguments"""
|
||||
try:
|
||||
print(f"_debug_event_callback ({len(args)} args, {len(kwargs)} kwargs)")
|
||||
for a in args:
|
||||
print(f" - {type(a)}")
|
||||
for k in kwargs:
|
||||
print(f" * {k} = {kwargs[k]}")
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
async def _write_next_batch(self, next_batch: str) -> None:
|
||||
"""Writes `next_batch` value to disk."""
|
||||
path = self._config.storage_directory / "next_batch"
|
||||
async with aiofiles.open(path, "w") as f:
|
||||
await f.write(next_batch)
|
||||
self._logger.debug("next_batch value is written to the disk")
|
||||
|
||||
async def _read_next_batch(self) -> str | None:
|
||||
"""Reads `next_batch` value from disk. Returns None if file does not exist."""
|
||||
path = self._config.storage_directory / "next_batch"
|
||||
if not path.is_file():
|
||||
return None
|
||||
async with aiofiles.open(path, "r") as f:
|
||||
return (await f.read()).strip()
|
||||
|
||||
async def _write_session_data(self, *, access_token: str, device_id: str) -> None:
|
||||
"""Write session data to disk."""
|
||||
path = self._config.storage_directory / "session_data.json"
|
||||
data = {
|
||||
"access_token": access_token,
|
||||
"device_id": device_id
|
||||
}
|
||||
async with aiofiles.open(path, "w") as f:
|
||||
await f.write(json.dumps(data, indent=4))
|
||||
self._logger.debug("Session data is writter to the disk")
|
||||
|
||||
async def _read_session_data(self) -> dict[str, Any] | None:
|
||||
"""Read session data from disk."""
|
||||
path = self._config.storage_directory / "session_data.json"
|
||||
if not path.is_file():
|
||||
return None
|
||||
async with aiofiles.open(path, "r") as f:
|
||||
j = json.loads(await f.read())
|
||||
return j
|
||||
|
||||
#
|
||||
# CALLBACKS
|
||||
#
|
||||
async def _callback_sync(self, response: SyncResponse) -> None:
|
||||
"""This callback is called when AsyncClient syncs with the server"""
|
||||
current_time = time.time()
|
||||
delta_time = current_time - self._last_next_batch_dump
|
||||
self._last_next_batch = response.next_batch
|
||||
if delta_time >= self.NEXT_BATCH_DUMP_PERIOD:
|
||||
self._last_next_batch_dump = current_time
|
||||
try:
|
||||
await self._write_next_batch(self._last_next_batch)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
async def _callback_autojoin(self, room: MatrixInvitedRoom, event: InviteMemberEvent):
|
||||
try:
|
||||
# event.state_key must be our username
|
||||
if event.state_key != self._client.user_id:
|
||||
return
|
||||
# membership status must be invite
|
||||
if event.membership != "invite":
|
||||
return
|
||||
result = await self._client.join(room.room_id)
|
||||
if type(result) is JoinResponse:
|
||||
self._logger.info(f"Autojoined the room {room.room_id}")
|
||||
else:
|
||||
self._logger.error(f"Can't autojoin the room {room.room_id}")
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
|
||||
#
|
||||
# LIFECYCLE
|
||||
#
|
||||
def _setup_client_callbacks(self) -> None:
|
||||
"""Setup internal client callbacks"""
|
||||
self._client.add_response_callback(self._callback_sync, SyncResponse) # type: ignore
|
||||
|
||||
if self._config.auto_join_any_room_on_invite:
|
||||
self._client.add_event_callback(self._callback_autojoin, InviteMemberEvent) # type: ignore
|
||||
|
||||
async def _client_login_session_data(self, session_data: dict[str, Any]) -> None:
|
||||
"""Login using session data. Raises and exception on failure."""
|
||||
self._logger.debug("Using stored session data to log in")
|
||||
# build user id
|
||||
username = self._build_matrix_username(self._config)
|
||||
self._client.restore_login(
|
||||
user_id=username,
|
||||
**session_data
|
||||
)
|
||||
result = await self._client.whoami()
|
||||
if type(result) is WhoamiError:
|
||||
self._logger.error(f"Can't log in using stored session data: '{result.message}'")
|
||||
raise RuntimeError(result.message)
|
||||
elif type(result) is not WhoamiResponse:
|
||||
self._logger.error("Can't log in using stored session data, unknown error")
|
||||
raise RuntimeError("Unknown response for whoami request")
|
||||
self._logger.debug("Logged in using stored session data")
|
||||
|
||||
async def _client_login_password(self) -> None:
|
||||
"""Login using password and save result to disk on success.
|
||||
Raises an exception on failure.
|
||||
"""
|
||||
self._logger.debug("Using password to log in")
|
||||
# get the password
|
||||
password = await self._cb_password()
|
||||
result = await self._client.login(password=password)
|
||||
if type(result) is LoginResponse:
|
||||
self._logger.debug("Logged in using password")
|
||||
await self._write_session_data(
|
||||
access_token=result.access_token,
|
||||
device_id=result.device_id
|
||||
)
|
||||
elif type(result) is LoginError:
|
||||
self._logger.error(f"Can't log in using password: '{result.message}'")
|
||||
raise RuntimeError(result.message)
|
||||
else:
|
||||
self._logger.error(f"Can't log in using password, unknown error")
|
||||
raise RuntimeError("Unknown login result")
|
||||
|
||||
async def _client_login(self) -> None:
|
||||
"""This function logs in."""
|
||||
# check if we have session data stored on the disk
|
||||
session_data = await self._read_session_data()
|
||||
# session data is present, try to log in
|
||||
if session_data is not None:
|
||||
self._logger.debug("Some session data found on the disk")
|
||||
try:
|
||||
await self._client_login_session_data(session_data)
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
pass
|
||||
# no session data - login using password
|
||||
try:
|
||||
self._logger.debug("No session data found on the disk OR invalid data")
|
||||
await self._client_login_password()
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
pass
|
||||
# can't login
|
||||
self._logger.error("Can't log in using available methods")
|
||||
raise RuntimeError("All login methods have failed, can't continue")
|
||||
|
||||
async def _client_destroy(self) -> None:
|
||||
"""Gracefully destroys the client."""
|
||||
try:
|
||||
self._logger.debug("Closing the client")
|
||||
await self._client.close()
|
||||
if self._last_next_batch is not None:
|
||||
self._logger.debug("Saving next_batch")
|
||||
await self._write_next_batch(self._last_next_batch)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
async def _client_cancellable_sync_forever(self, *args, **kwargs) -> Any:
|
||||
"""Behaves exactly like AsyncClient.sync_forever, but supports task cancellation"""
|
||||
sync_forever_task = asyncio.create_task(
|
||||
self._client.sync_forever(*args, **kwargs)
|
||||
)
|
||||
try:
|
||||
return await sync_forever_task
|
||||
except asyncio.CancelledError:
|
||||
try:
|
||||
self._client.stop_sync_forever()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
sync_forever_task.cancel()
|
||||
await asyncio.gather(sync_forever_task, return_exceptions=True)
|
||||
raise
|
||||
|
||||
async def _background_coroutine(self) -> None:
|
||||
"""This function implements bot lifecycle."""
|
||||
# we should stop when this task stops
|
||||
self._logger.debug("_background_coroutine is started")
|
||||
stop_wait_task = asyncio.create_task(self._stop_event.wait()) # type: ignore
|
||||
# perform login
|
||||
login_task = asyncio.create_task(self._client_login())
|
||||
try:
|
||||
await self._wait_for_task_and_stop_event(login_task, stop_wait_task)
|
||||
except asyncio.CancelledError:
|
||||
self._logger.debug("Background task is cancelled during login")
|
||||
await self._client_destroy()
|
||||
return
|
||||
except:
|
||||
traceback.print_exc()
|
||||
self._logger.info("Succesfully logged in")
|
||||
# sync forever
|
||||
self._logger.info("Syncing forever")
|
||||
sync_task = asyncio.create_task(
|
||||
self._client_cancellable_sync_forever(
|
||||
timeout=self.MATRIX_SYNC_PERIOD,
|
||||
since=(await self._read_next_batch())
|
||||
)
|
||||
)
|
||||
try:
|
||||
await self._wait_for_task_and_stop_event(sync_task, stop_wait_task)
|
||||
except asyncio.CancelledError:
|
||||
self._logger.debug("Sync task is cancelled")
|
||||
await self._client_destroy()
|
||||
return
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
#
|
||||
# PUBLIC
|
||||
#
|
||||
def __init__(self, config: MatrixBotConfig) -> None:
|
||||
# check if config is valid
|
||||
self._validate_bot_config(config) # may raise an Exception
|
||||
# save the config
|
||||
self._config: MatrixBotConfig = config
|
||||
# create the logger
|
||||
self._logger = logging.getLogger(self._build_matrix_username(config))
|
||||
self._logger.setLevel(logging.DEBUG)
|
||||
# create the client
|
||||
self._client: AsyncClient = self._build_client(self._config)
|
||||
self._setup_client_callbacks()
|
||||
|
||||
# prepare some private data
|
||||
self._background_task: asyncio.Task | None = None
|
||||
self._last_next_batch_dump: float = 0.0
|
||||
self._last_next_batch: str | None = None
|
||||
self._cb_password = self._default_password_callback
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the bot.
|
||||
Starts the bot in background task. Raises an exception if there are
|
||||
problems (for example, the bot is already started). The bot will
|
||||
do everything to keep itself running, including restarts. Use
|
||||
`stop()` to stop the bot.
|
||||
"""
|
||||
if self._background_task is not None:
|
||||
raise RuntimeError("The bot is already started!")
|
||||
self._stop_event = asyncio.Event()
|
||||
self._background_task = asyncio.create_task(
|
||||
self._background_coroutine()
|
||||
)
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the bot and wait for the bot stop."""
|
||||
if self._background_task is None or self._stop_event is None:
|
||||
return
|
||||
self._stop_event.set()
|
||||
try:
|
||||
await self._background_task
|
||||
except:
|
||||
traceback.print_exc()
|
||||
self._stop_event = None
|
||||
self._background_task = None
|
||||
|
||||
def verify_all_known_devices(self) -> bool:
|
||||
"""Verifies all known devices.
|
||||
|
||||
Returns:
|
||||
True if there were unverified devices that are verified now.
|
||||
"""
|
||||
result = False
|
||||
for user_id in self._client.device_store.users:
|
||||
for device_id, olm_device in self._client.device_store[user_id].items():
|
||||
# can't trust ourselves
|
||||
if device_id == self._client.device_id and user_id == self._client.user_id:
|
||||
continue
|
||||
# they are already verified
|
||||
if olm_device.verified:
|
||||
continue
|
||||
# verify them
|
||||
self._client.verify_device(olm_device)
|
||||
result = True
|
||||
return result
|
||||
|
||||
def add_event_callback(self, callback: Callable[[Any], Awaitable[None]] | None, event_class: nio.events.Event) -> None:
|
||||
"""Added event callback for events of specified class.
|
||||
Use `None` instead of callback to print parameter types you need to use in your callback."""
|
||||
if callback is None:
|
||||
callback = self._debug_event_callback
|
||||
self._client.add_event_callback(callback, event_class) # type: ignore
|
||||
|
||||
def get_client(self) -> AsyncClient:
|
||||
"""Get AsyncClient in use"""
|
||||
return self._client
|
||||
|
||||
async def send_text_to_room(self, room_id: str, text: str, is_html: bool | None = None, **kwargs) -> str:
|
||||
"""Sends a text message to the room and handle HTML as specified.
|
||||
|
||||
Args:
|
||||
text - text to send
|
||||
is_html - True if text is HTML; False if text is not HTML; None if the value should be guessed
|
||||
kwargs - passed as `m.room.message` content keys
|
||||
|
||||
Returns:
|
||||
event_id of the message on success. Raises an exception on error.
|
||||
"""
|
||||
original_text = text
|
||||
# guess if text is HTML
|
||||
if is_html is None:
|
||||
is_html, text = self._check_and_remove_html(text)
|
||||
# text is HTML
|
||||
elif is_html:
|
||||
_, text = self._check_and_remove_html(text)
|
||||
# create `content` for `room_send()`
|
||||
content = {
|
||||
"msgtype": "m.text",
|
||||
"body": text,
|
||||
**kwargs
|
||||
}
|
||||
if is_html:
|
||||
content["format"] = "org.matrix.custom.html"
|
||||
content["formatted_body"] = original_text
|
||||
# try to send the message
|
||||
try:
|
||||
result = await self._client.room_send(
|
||||
room_id=room_id,
|
||||
message_type="m.room.message",
|
||||
content=content
|
||||
)
|
||||
except OlmUnverifiedDeviceError:
|
||||
if self._config.auto_verify_all_known_devices:
|
||||
if not self.verify_all_known_devices():
|
||||
raise
|
||||
return await self.send_text_to_room(room_id, original_text, is_html, **kwargs)
|
||||
else:
|
||||
raise
|
||||
# success
|
||||
if type(result) is RoomSendResponse:
|
||||
return result.event_id
|
||||
# error
|
||||
elif type(result) is RoomSendError:
|
||||
raise RuntimeError(result)
|
||||
# unknown error
|
||||
else:
|
||||
raise RuntimeError("Unknown error has occured", result)
|
||||
5
src/mab/bot/__init__.py
Normal file
5
src/mab/bot/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .bot import *
|
||||
|
||||
__all__ = [
|
||||
"MatrixBot"
|
||||
]
|
||||
240
src/mab/bot/_callbacks.py
Normal file
240
src/mab/bot/_callbacks.py
Normal file
@@ -0,0 +1,240 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import traceback
|
||||
from typing import Callable, Any, Coroutine, TYPE_CHECKING
|
||||
from dataclasses import dataclass
|
||||
|
||||
from nio import AsyncClient
|
||||
from nio import MatrixRoom
|
||||
from nio import MatrixInvitedRoom, InviteMemberEvent, JoinResponse
|
||||
from nio import RoomGetStateResponse, SyncResponse
|
||||
from nio.events.room_events import Event as RoomEvent
|
||||
|
||||
from ._database import _Database
|
||||
from ..types import MatrixBotConfig
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars, ContextVarsPopulator
|
||||
from ..filters.base import BaseEventFilter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .bot import MatrixBot
|
||||
|
||||
class Callbacks:
|
||||
"""
|
||||
This class implements user callbacks routing and some basic internal
|
||||
callbacks. You should use it to add callbacks to the bot.
|
||||
"""
|
||||
#
|
||||
# DATACLASSES
|
||||
#
|
||||
@dataclass
|
||||
class _FilterBasedCallback:
|
||||
"""Data structure that holds information about filter-based callback"""
|
||||
|
||||
filter: BaseEventFilter
|
||||
"""Filter to use for matching"""
|
||||
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None
|
||||
"""Callback that will be called if the filter matches"""
|
||||
|
||||
stop_matching: bool
|
||||
"""Whether to stop matching if the filter matches"""
|
||||
|
||||
#
|
||||
# PRIVATE
|
||||
#
|
||||
async def _callback_room_left(self, raw: Any) -> None:
|
||||
"""This callback check if SyncResponse contains info about leaving the
|
||||
room due to ban, kick or any other reason, and preforms some actions."""
|
||||
if not isinstance(raw, list):
|
||||
raw = [raw]
|
||||
for resp in raw:
|
||||
if not isinstance(resp, SyncResponse):
|
||||
continue
|
||||
for room_id in resp.rooms.leave:
|
||||
await self._db.join_timestamp_remove(room_id)
|
||||
|
||||
async def _get_room_join_timestamp(self, room_id: str) -> int | None:
|
||||
"""Gets the room join timestamp."""
|
||||
if self._client is None:
|
||||
raise RuntimeError("Callbacks were not set up")
|
||||
state = await self._client.room_get_state(room_id)
|
||||
if not isinstance(state, RoomGetStateResponse):
|
||||
return None
|
||||
timestamp = 0
|
||||
for event in state.events:
|
||||
# only m.room.member
|
||||
if event.get("type") != "m.room.member":
|
||||
continue
|
||||
# only describing our state
|
||||
if event.get("state_key") != self._client.user_id:
|
||||
continue
|
||||
# only describing our join state
|
||||
if event["content"].get("membership") != "join":
|
||||
continue
|
||||
if event.get("prev_content") and event["prev_content"].get("membership") not in ("invite", "leave"):
|
||||
continue
|
||||
origin_server_ts = event.get("origin_server_ts", 0)
|
||||
if origin_server_ts > timestamp:
|
||||
timestamp = origin_server_ts
|
||||
return timestamp or None
|
||||
|
||||
async def _callback_room_event_router(self,
|
||||
room: MatrixRoom,
|
||||
event: RoomEvent) -> None:
|
||||
"""
|
||||
This callback implements routing of filter-based event callbacks.
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("Callbacks were not set up")
|
||||
# update join time if needed
|
||||
joined_timestamp = await self._db.join_timestamp_get(room.room_id)
|
||||
if joined_timestamp is None:
|
||||
joined_timestamp = await self._get_room_join_timestamp(room.room_id)
|
||||
if joined_timestamp is not None:
|
||||
await self._db.join_timestamp_set(room.room_id, joined_timestamp)
|
||||
else:
|
||||
return
|
||||
# do not handle the event if it happened before we joined
|
||||
if event.server_timestamp < joined_timestamp:
|
||||
return
|
||||
# build the event context
|
||||
event_context = EventContext(
|
||||
room=room,
|
||||
event=event,
|
||||
bot=self._matrix_bot
|
||||
)
|
||||
event_vars = ContextVars()
|
||||
self._context_vars_populator.sync_populate(event_context, event_vars)
|
||||
await self._context_vars_populator.async_populate(event_context, event_vars)
|
||||
|
||||
# check all filters
|
||||
for callback_info in self._filters:
|
||||
if not isinstance(callback_info, self._FilterBasedCallback):
|
||||
continue
|
||||
local_event_vars = ContextVars()
|
||||
try:
|
||||
if not await callback_info.filter(event_context, local_event_vars):
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
continue
|
||||
try:
|
||||
# dump argument types
|
||||
if callback_info.callback is None:
|
||||
self._logger.critical(
|
||||
f"Filter {repr(callback_info.filter)} has no callback. "
|
||||
f"`room` type is `{type(event_context.room)}`. "
|
||||
f"`event` type is `{type(event_context.event)}`."
|
||||
)
|
||||
continue
|
||||
# create the coroutine
|
||||
cor = callback_info.callback(
|
||||
event_context,
|
||||
event_vars + local_event_vars
|
||||
)
|
||||
# multitasking
|
||||
if self._config.enable_multitasking_callbacks:
|
||||
t = asyncio.create_task(cor)
|
||||
t.add_done_callback(self._multitasking_set.discard)
|
||||
self._multitasking_set.add(t)
|
||||
# no multitasking
|
||||
else:
|
||||
await cor
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
if callback_info.stop_matching:
|
||||
break
|
||||
|
||||
async def _callback_autojoin(self,
|
||||
room: MatrixInvitedRoom,
|
||||
event: InviteMemberEvent) -> None:
|
||||
"""
|
||||
This callback implements automatic room joining.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("Callbacks were not set up")
|
||||
try:
|
||||
# event.state_key must be our username
|
||||
if event.state_key != self._client.user_id:
|
||||
return
|
||||
# membership status must be invite
|
||||
if event.membership != "invite":
|
||||
return
|
||||
result = await self._client.join(room.room_id)
|
||||
if type(result) is JoinResponse:
|
||||
self._logger.info(f"Autojoined the room {room.room_id}")
|
||||
else:
|
||||
self._logger.error(f"Can't autojoin the room {room.room_id}")
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
|
||||
async def _setup_internal_callbacks(self) -> None:
|
||||
"""
|
||||
Setup internal callbacks.
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("Callbacks were not set up")
|
||||
self._client.add_response_callback(
|
||||
self._callback_room_left, # type: ignore
|
||||
)
|
||||
# filter-based callback routing
|
||||
self._client.add_event_callback(
|
||||
self._callback_room_event_router, RoomEvent)
|
||||
# auto-join
|
||||
if self._config.auto_join_any_room_on_invite:
|
||||
self._client.add_event_callback(
|
||||
self._callback_autojoin, InviteMemberEvent) # type: ignore
|
||||
|
||||
#
|
||||
# PUBLIC
|
||||
#
|
||||
def __init__(self, db: _Database, matrix_bot: "MatrixBot"):
|
||||
self._logger = logging.getLogger("Callbacks")
|
||||
self._db = db
|
||||
self._matrix_bot = matrix_bot
|
||||
self._context_vars_populator = ContextVarsPopulator()
|
||||
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
self._filters: list = []
|
||||
self._multitasking_set: set[asyncio.Task] = set()
|
||||
|
||||
def add_room_event_callback(
|
||||
self,
|
||||
filter: BaseEventFilter,
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
|
||||
*,
|
||||
stop_matching: bool = True) -> None:
|
||||
"""
|
||||
Add filter-based callback.
|
||||
|
||||
Args:
|
||||
- filter - filter to use for the callback
|
||||
- callback - the callback that must be called if the filter matches
|
||||
- stop_matching - whether to stop matching if the filter matches
|
||||
"""
|
||||
callback_info = self._FilterBasedCallback(
|
||||
filter=filter,
|
||||
callback=callback,
|
||||
stop_matching=stop_matching
|
||||
)
|
||||
self._filters.append(callback_info)
|
||||
|
||||
|
||||
async def setup(self, config: MatrixBotConfig, client: AsyncClient) -> None:
|
||||
"""
|
||||
Setup the callbacks. Must be called by `ClientManager`.
|
||||
|
||||
This method must be called AFTER required callbacks were added by using
|
||||
`add_room_event_callback(...)`.
|
||||
"""
|
||||
self._config = config
|
||||
self._client = client
|
||||
await self._setup_internal_callbacks()
|
||||
|
||||
|
||||
140
src/mab/bot/_client_auth.py
Normal file
140
src/mab/bot/_client_auth.py
Normal file
@@ -0,0 +1,140 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
from ._database import _Database
|
||||
|
||||
from ..utils import Utils
|
||||
from ..types import MatrixBotConfig
|
||||
|
||||
from nio import AsyncClient
|
||||
from nio import WhoamiError, WhoamiResponse
|
||||
from nio import LoginError, LoginResponse
|
||||
|
||||
class ClientAuth:
|
||||
"""This class is used by to authenticate AsyncClient."""
|
||||
|
||||
#
|
||||
# PRIVATE
|
||||
#
|
||||
async def _default_password_callback(self) -> str:
|
||||
if self._config is None:
|
||||
raise RuntimeError("No config")
|
||||
if "MAB_PASSWORD" in os.environ:
|
||||
return os.environ["MAB_PASSWORD"]
|
||||
raise RuntimeError("Can't get password")
|
||||
|
||||
async def _login_using_session_data(self, client: AsyncClient) -> None:
|
||||
"""
|
||||
Login using session data from database.
|
||||
|
||||
Args:
|
||||
- client - client that needs to get logged in
|
||||
|
||||
Returns:
|
||||
- Does not return anything on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if self._full_matrix_username is None:
|
||||
raise RuntimeError("ClientAuth is not set up")
|
||||
self._logger.debug("Trying to log in using session data from disk...")
|
||||
access_token = await self._db.prop_get("access_token")
|
||||
device_id = await self._db.prop_get("device_id")
|
||||
if not isinstance(access_token, str) or not isinstance(device_id, str):
|
||||
self._logger.error("Can't read session data from database")
|
||||
raise RuntimeError("Can't read session data from database")
|
||||
client.restore_login(
|
||||
user_id=self._full_matrix_username,
|
||||
access_token=access_token,
|
||||
device_id=device_id
|
||||
)
|
||||
client.load_store()
|
||||
result = await client.whoami()
|
||||
if type(result) is WhoamiError:
|
||||
self._logger.error(
|
||||
f"Can't log in using stored session data: '{result.message}'"
|
||||
)
|
||||
raise RuntimeError(result.message)
|
||||
elif type(result) is not WhoamiResponse:
|
||||
self._logger.error(
|
||||
"Can't log in using stored session data, unknown error"
|
||||
)
|
||||
raise RuntimeError(
|
||||
"Unknown response for whoami request"
|
||||
)
|
||||
self._logger.debug("Logged in using stored session data")
|
||||
|
||||
async def _login_using_password(self, client: AsyncClient) -> None:
|
||||
"""
|
||||
Login using password.
|
||||
|
||||
Args:
|
||||
- client - client that needs to get logged in
|
||||
|
||||
Returns:
|
||||
- Does not return anything on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if self._full_matrix_username is None:
|
||||
raise RuntimeError("ClientAuth is not set up")
|
||||
self._logger.debug("Trying to log in using password")
|
||||
password = await self._default_password_callback()
|
||||
result = await client.login(password=password)
|
||||
if type(result) is LoginResponse:
|
||||
self._logger.debug("Logged in using password")
|
||||
await self._db.prop_set("access_token", result.access_token)
|
||||
await self._db.prop_set("device_id", result.device_id)
|
||||
elif type(result) is LoginError:
|
||||
self._logger.error(f"Can't log in using password: '{result.message}'")
|
||||
raise RuntimeError(result.message)
|
||||
else:
|
||||
self._logger.error(f"Can't log in using password, unknown error")
|
||||
raise RuntimeError("Unknown login result")
|
||||
|
||||
#
|
||||
# PUBLIC
|
||||
#
|
||||
def __init__(self, db: _Database, *, log_level = logging.INFO):
|
||||
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||
self._logger.setLevel(log_level)
|
||||
self._db = db
|
||||
self._full_matrix_username: str | None = None
|
||||
self._config: MatrixBotConfig | None = None
|
||||
|
||||
async def setup(self, config: MatrixBotConfig) -> None:
|
||||
"""
|
||||
Setup `ClientAuth` object using `config`.
|
||||
"""
|
||||
self._config = config
|
||||
self._full_matrix_username = Utils.build_full_matrix_username(config)
|
||||
self._logger.debug(f"Using full matrix username `{self._full_matrix_username}`")
|
||||
|
||||
async def login(self, client: AsyncClient) -> None:
|
||||
"""
|
||||
Login. Saves authorization data if it is not saved yet. Must be called
|
||||
by `ClientManager`.
|
||||
|
||||
Args:
|
||||
- client - client that needs to get logged in
|
||||
|
||||
Returns:
|
||||
- Does not return anything on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
# try session data
|
||||
try:
|
||||
await self._login_using_session_data(client)
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
pass
|
||||
# try password
|
||||
try:
|
||||
await self._login_using_password(client)
|
||||
return
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
pass
|
||||
# failed
|
||||
raise RuntimeError("Failed to login")
|
||||
250
src/mab/bot/_client_downloader.py
Normal file
250
src/mab/bot/_client_downloader.py
Normal file
@@ -0,0 +1,250 @@
|
||||
import asyncio
|
||||
import aiofiles
|
||||
import logging
|
||||
import os
|
||||
from typing import overload
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
from pathlib import Path
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import unpaddedbase64
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util import Counter
|
||||
|
||||
from nio import (
|
||||
AsyncClient,
|
||||
Event,
|
||||
DiskDownloadResponse,
|
||||
MemoryDownloadResponse
|
||||
)
|
||||
|
||||
from ..types import MatrixBotConfig
|
||||
from ..context import EventContext
|
||||
|
||||
class ClientDownloader:
|
||||
"""This class downloads files"""
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("ClientSender")
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
|
||||
async def setup(self,
|
||||
config: MatrixBotConfig,
|
||||
client: AsyncClient) -> None:
|
||||
"""
|
||||
Setup the downloader.
|
||||
|
||||
Args:
|
||||
- config - config to use
|
||||
- client - client to use
|
||||
"""
|
||||
self._config = config
|
||||
self._client = client
|
||||
|
||||
async def _decrypt_file(self,
|
||||
src: Path,
|
||||
dst: Path,
|
||||
key: str,
|
||||
iv: str,
|
||||
sha256: str) -> None:
|
||||
"""
|
||||
Decrypts `src` and saves it as `dst` asynchronously.
|
||||
|
||||
Args:
|
||||
- src - path to the source (encrypted) file
|
||||
- dst - path where the resulting (decrypted) file will be saved
|
||||
- key - key, from event["content"]["file"]["key"]["k"]
|
||||
- iv - initialization vector, from event["content"]["file"]["iv"]
|
||||
- sha256 - SHA-256 digest, from
|
||||
event["content"]["file"]["hashes"]["sha256"]
|
||||
|
||||
Returns:
|
||||
- Returns nothing on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
async with aiofiles.open(src, "rb") as reader:
|
||||
# check file hash
|
||||
expected = unpaddedbase64.decode_base64(sha256)
|
||||
digest = hashlib.sha256()
|
||||
while chunk := await reader.read(16 * 1024):
|
||||
digest.update(chunk)
|
||||
if not hmac.compare_digest(digest.digest(), expected):
|
||||
raise RuntimeError("SHA256 mismatch")
|
||||
await reader.seek(0)
|
||||
# decrypt
|
||||
decoded_key = unpaddedbase64.decode_base64(key)
|
||||
decoded_iv = unpaddedbase64.decode_base64(iv)
|
||||
cipher = AES.new(
|
||||
decoded_key,
|
||||
AES.MODE_CTR,
|
||||
counter=Counter.new(
|
||||
nbits=64,
|
||||
prefix=decoded_iv[:8],
|
||||
initial_value=int.from_bytes(decoded_iv[8:], "big")
|
||||
)
|
||||
)
|
||||
async with aiofiles.open(dst, "wb") as writer:
|
||||
while chunk := await reader.read(16 * 1024):
|
||||
await writer.write(cipher.decrypt(chunk))
|
||||
|
||||
async def _decrypt_bytes(self,
|
||||
data: bytes,
|
||||
key: str,
|
||||
iv: str,
|
||||
sha256: str) -> bytes:
|
||||
"""
|
||||
Decrypts `data`. It starts subthread that performs decryption.
|
||||
|
||||
Args:
|
||||
- data - data that needs to be decrypted
|
||||
- key - key, from event["content"]["file"]["key"]["k"]
|
||||
- iv - initialization vector, from event["content"]["file"]["iv"]
|
||||
- sha265 - SHA-256 digest, from
|
||||
event["content"]["file"]["hashes"]["sha256"]
|
||||
|
||||
Returns:
|
||||
- Returns decrypted data on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
cancel = threading.Event()
|
||||
# subfunction that will run in another thread
|
||||
def decrypt() -> bytes:
|
||||
chunk_size = 64 * 1024
|
||||
view = memoryview(data)
|
||||
expected = unpaddedbase64.decode_base64(sha256)
|
||||
digest = hashlib.sha256()
|
||||
for offset in range(0, len(view), chunk_size):
|
||||
if cancel.is_set():
|
||||
return b""
|
||||
digest.update(view[offset:offset + chunk_size])
|
||||
if not hmac.compare_digest(digest.digest(), expected):
|
||||
raise RuntimeError("SHA-256 mismatch")
|
||||
# prepare AES-CTR
|
||||
decoded_key = unpaddedbase64.decode_base64(key)
|
||||
decoded_iv = unpaddedbase64.decode_base64(iv)
|
||||
cipher = AES.new(
|
||||
decoded_key,
|
||||
AES.MODE_CTR,
|
||||
counter=Counter.new(
|
||||
nbits=64,
|
||||
prefix=decoded_iv[:8],
|
||||
initial_value=int.from_bytes(decoded_iv[8:], "big"),
|
||||
),
|
||||
)
|
||||
# decrypt
|
||||
result = bytearray()
|
||||
for offset in range(0, len(view), chunk_size):
|
||||
if cancel.is_set():
|
||||
return b""
|
||||
result.extend(
|
||||
cipher.decrypt(view[offset:offset + chunk_size])
|
||||
)
|
||||
return bytes(result)
|
||||
# decrypt in thread
|
||||
try:
|
||||
return await asyncio.to_thread(decrypt)
|
||||
except asyncio.CancelledError:
|
||||
cancel.set()
|
||||
raise
|
||||
|
||||
@overload
|
||||
async def file(self,
|
||||
source: EventContext | Event,
|
||||
*,
|
||||
path: str | Path) -> Path: ...
|
||||
|
||||
@overload
|
||||
async def file(self,
|
||||
source: EventContext | Event,
|
||||
*,
|
||||
path: None = None) -> bytes: ...
|
||||
|
||||
async def file(self,
|
||||
source: EventContext | Event,
|
||||
*,
|
||||
path: str | Path | None = None) -> Path | bytes:
|
||||
"""
|
||||
Download the file from the event. Automatically deciphers encrypted
|
||||
media.
|
||||
|
||||
Args:
|
||||
- source - event that has a file in its `content`
|
||||
- path - where to save the file to. Use `None` to store the file in
|
||||
memory. Use path to specify file download path.
|
||||
|
||||
Returns:
|
||||
- Returns `Path` to the file on success (if `path` isn't `None`)
|
||||
- Returns `bytes` of the file on success (if `path` is `None`)
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("ClientDownloader is not set up")
|
||||
# prepare the args
|
||||
if isinstance(source, EventContext):
|
||||
source = source.event
|
||||
content: dict = source.source["content"]
|
||||
f = content.get("file")
|
||||
# encypted
|
||||
if f:
|
||||
if not isinstance(f["url"], str):
|
||||
raise RuntimeError("`source` does not contain file URL")
|
||||
mxc = f["url"]
|
||||
if f["key"]["alg"].upper() != "A256CTR":
|
||||
raise NotImplementedError(
|
||||
f"Unsupported encryption algorithm `{f['key']['alg']}`"
|
||||
)
|
||||
key: str | None = f["key"]["k"]
|
||||
iv: str | None = f["iv"]
|
||||
sha256: str | None = f["hashes"]["sha256"]
|
||||
# not encrypted
|
||||
else:
|
||||
mxc = content["url"]
|
||||
key = None
|
||||
iv = None
|
||||
sha256 = None
|
||||
# prepare path
|
||||
if isinstance(path, str):
|
||||
path = Path(path)
|
||||
filename: str | None = \
|
||||
os.path.basename(path) if isinstance(path, Path) else None
|
||||
# download
|
||||
result = await self._client.download(
|
||||
mxc,
|
||||
filename=filename,
|
||||
save_to=path
|
||||
)
|
||||
# check the response
|
||||
if isinstance(result, DiskDownloadResponse):
|
||||
result = Path(result.body)
|
||||
elif isinstance(result, MemoryDownloadResponse):
|
||||
result = result.body
|
||||
else:
|
||||
raise RuntimeError(result)
|
||||
# decrypt if needed
|
||||
temp_path: Path | None = None
|
||||
try:
|
||||
if key is not None and iv is not None and sha256 is not None:
|
||||
# on disk
|
||||
if isinstance(result, Path):
|
||||
temp_path = result.with_name(
|
||||
f".{result.name}.{uuid4().hex}.tmp"
|
||||
)
|
||||
await self._decrypt_file(
|
||||
result, temp_path, key, iv, sha256
|
||||
)
|
||||
temp_path.replace(result)
|
||||
temp_path = None
|
||||
# in memory
|
||||
else:
|
||||
result = await self._decrypt_bytes(
|
||||
result, key, iv, sha256
|
||||
)
|
||||
finally:
|
||||
if isinstance(temp_path, Path) and isinstance(result, Path):
|
||||
result.unlink(missing_ok=True)
|
||||
temp_path.unlink(missing_ok=True)
|
||||
# return the result
|
||||
return result
|
||||
205
src/mab/bot/_client_manager.py
Normal file
205
src/mab/bot/_client_manager.py
Normal file
@@ -0,0 +1,205 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
import traceback
|
||||
from typing import Any
|
||||
|
||||
from nio import AsyncClient, AsyncClientConfig, SyncResponse
|
||||
from ..types import MatrixBotConfig
|
||||
|
||||
from ._database import _Database
|
||||
from ._client_auth import ClientAuth
|
||||
|
||||
class ClientManager:
|
||||
"""This class manages basic of `AsyncClient`."""
|
||||
|
||||
#
|
||||
# PRIVATE
|
||||
#
|
||||
async def _close_client(self) -> None:
|
||||
"""
|
||||
Closes the client correctly and saves data.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("The client does not exist")
|
||||
self._logger.debug("Closing the client...")
|
||||
await self._client.close()
|
||||
self._logger.debug("Dumping 'next_batch' value...")
|
||||
if self._last_next_batch is not None:
|
||||
await self._db.prop_set("next_batch", self._last_next_batch)
|
||||
|
||||
async def _cancellable_sync_forever(self, *args, **kwargs) -> Any:
|
||||
"""
|
||||
Behaves exactly like AsyncClient.sync_forever, but supports proper task
|
||||
cancellation.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("Client does not exist")
|
||||
task = asyncio.create_task(self._client.sync_forever(*args, **kwargs))
|
||||
try:
|
||||
return await task
|
||||
except asyncio.CancelledError:
|
||||
try:
|
||||
self._client.stop_sync_forever()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
raise
|
||||
|
||||
async def _background_coroutine(self) -> None:
|
||||
"""
|
||||
Coroutine that manages the `AsyncClient` in background. It supports
|
||||
cancellation and you should use it to stop the operation of the bot.
|
||||
"""
|
||||
# refuse to start without config
|
||||
if self._config is None:
|
||||
raise RuntimeError("Config is not set up")
|
||||
# refuse to start without client
|
||||
if self._client is None:
|
||||
raise RuntimeError("Client does not exist")
|
||||
# try to login
|
||||
self._logger.debug("Logging in...")
|
||||
try:
|
||||
await self._client_auth.login(self._client)
|
||||
self._logger.info(f"Logged in as {self._client.user_id}")
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
raise
|
||||
# sync forever
|
||||
self._logger.debug("Syncing forever...")
|
||||
await self._cancellable_sync_forever(
|
||||
timeout=self._config.client_sync_period_ms,
|
||||
since=(await self._db.prop_get("next_batch")),
|
||||
full_state=True
|
||||
)
|
||||
|
||||
async def _callback_sync(self, response: SyncResponse) -> None:
|
||||
"""
|
||||
This callback is called when AsyncClient syncs with the server
|
||||
"""
|
||||
if self._config is None:
|
||||
raise RuntimeError("ClientManager is not set up")
|
||||
# save last `next_batch`
|
||||
self._last_next_batch = response.next_batch
|
||||
# dump if needed
|
||||
current_time = time.time()
|
||||
delta_time = current_time - self._last_next_batch_write_time
|
||||
if delta_time >= self._config.client_next_batch_dump_period_s:
|
||||
try:
|
||||
await self._db.prop_set("next_batch", self._last_next_batch)
|
||||
self._last_next_batch_write_time = current_time
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
|
||||
async def _setup_callbacks(self, config: MatrixBotConfig) -> None:
|
||||
"""
|
||||
Setup callbacks.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("The client does not exist")
|
||||
self._client.add_response_callback(
|
||||
self._callback_sync, SyncResponse) # type: ignore
|
||||
|
||||
#
|
||||
# PUBLIC
|
||||
#
|
||||
def __init__(self, client_auth: ClientAuth, db: _Database, *, log_level = logging.INFO):
|
||||
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||
self._logger.setLevel(log_level)
|
||||
self._client_auth = client_auth
|
||||
self._db = db
|
||||
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
self._was_started_ever: bool = False
|
||||
self._was_built_ever: bool = False
|
||||
self._background_task: asyncio.Task | None = None
|
||||
self._last_next_batch_write_time: float = 0.0
|
||||
self._last_next_batch: str | None = None
|
||||
|
||||
async def setup(self, config: MatrixBotConfig) -> None:
|
||||
"""
|
||||
Build `AsyncClient` from `config`.
|
||||
|
||||
Returns:
|
||||
- Does not return anything, raises an exception on error.
|
||||
"""
|
||||
if self._was_built_ever:
|
||||
raise RuntimeError("The client was already built")
|
||||
client_config = AsyncClientConfig(
|
||||
store_name="nio_store_file",
|
||||
encryption_enabled=True,
|
||||
store_sync_tokens=False
|
||||
)
|
||||
self._client = AsyncClient(
|
||||
homeserver=config.matrix_homeserver_url,
|
||||
user=config.matrix_username_localpart,
|
||||
store_path=str(config.storage_directory),
|
||||
config=client_config
|
||||
)
|
||||
try:
|
||||
await self._setup_callbacks(config)
|
||||
except:
|
||||
self._client = None
|
||||
raise
|
||||
self._config = config
|
||||
self._was_built_ever = True
|
||||
|
||||
def get_client(self) -> AsyncClient:
|
||||
"""
|
||||
Get AsyncClient.
|
||||
|
||||
Returns:
|
||||
- `AsyncClient` you may use to access Matrix. Raises a RuntimeError
|
||||
if the client does not exist or is not operational.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("The client does not exist")
|
||||
return self._client
|
||||
|
||||
async def start(self) -> None:
|
||||
"""
|
||||
Start client operation in background. This method can be called
|
||||
succesfully only once for `ClientManager` object. Any subsequent calls
|
||||
will raise an exception.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("Client does not exist")
|
||||
if self._was_started_ever:
|
||||
raise RuntimeError("Client can't be started several times")
|
||||
self._background_task = asyncio.create_task(
|
||||
self._background_coroutine()
|
||||
)
|
||||
self._was_started_ever = True
|
||||
self._logger.debug("Bot background is started")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""
|
||||
Stop client operation in background. This method can be called only if
|
||||
the client was `start(...)`ed previously. This method will wait for the
|
||||
bot to completely stop.
|
||||
"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("Client does not exist")
|
||||
if self._background_task is None:
|
||||
if self._was_started_ever:
|
||||
raise RuntimeError("The bot was stopped previously")
|
||||
else:
|
||||
raise RuntimeError("The bot was never started")
|
||||
self._background_task.cancel()
|
||||
try:
|
||||
await asyncio.shield(self._background_task)
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
try:
|
||||
await asyncio.shield(self._close_client())
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
self._background_task = None
|
||||
self._logger.debug("Bot background task is stopped")
|
||||
190
src/mab/bot/_client_room_operations.py
Normal file
190
src/mab/bot/_client_room_operations.py
Normal file
@@ -0,0 +1,190 @@
|
||||
import logging
|
||||
from nio import (
|
||||
AsyncClient,
|
||||
Event,
|
||||
MatrixRoom,
|
||||
MatrixUser,
|
||||
RoomMember,
|
||||
|
||||
RoomVisibility,
|
||||
|
||||
RoomCreateResponse,
|
||||
RoomForgetResponse,
|
||||
RoomGetEventResponse,
|
||||
RoomLeaveResponse,
|
||||
JoinResponse,
|
||||
RoomInviteResponse,
|
||||
RoomKickResponse,
|
||||
RoomBanResponse,
|
||||
RoomUnbanResponse,
|
||||
JoinedMembersResponse
|
||||
)
|
||||
from ..utils import MatrixBotConfig
|
||||
|
||||
class ClientRoomOperations:
|
||||
"""This class works with rooms."""
|
||||
|
||||
@staticmethod
|
||||
def _room_id(room: MatrixRoom | str) -> str:
|
||||
"""Convert room to its ID if needed"""
|
||||
return room.room_id if isinstance(room, MatrixRoom) else room
|
||||
|
||||
@staticmethod
|
||||
def _user_id(user: MatrixUser | str) -> str:
|
||||
"""Convert user to its ID if needed"""
|
||||
return user.user_id if isinstance(user, MatrixUser) else user
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("ClientRoomOperations")
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
|
||||
async def setup(self,
|
||||
config: MatrixBotConfig,
|
||||
client: AsyncClient) -> None:
|
||||
"""Setup room operations.
|
||||
|
||||
Args:
|
||||
- config - config to use
|
||||
- client - client to use
|
||||
"""
|
||||
self._config = config
|
||||
self._client = client
|
||||
|
||||
async def create(self, *, visibility=RoomVisibility.private, alias: str | None = None, name: str | None = None, topic: str | None = None, federate: bool = False, is_direct: bool = False, invite_list: list[str] = []) -> str:
|
||||
"""Create a new room.
|
||||
|
||||
Args:
|
||||
- visibility - whether to publish the room to homeserver public
|
||||
room repository
|
||||
- alias - room alias to use (without homeserver and leading hashtag)
|
||||
- name - display name of the room to set
|
||||
- topic - topic to set
|
||||
- federate - whether to allow federation for the room
|
||||
- is_direct - whether the room is "direct"
|
||||
- invite_list - users to get invitation
|
||||
|
||||
Returns:
|
||||
- room id
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_create(
|
||||
visibility=visibility,
|
||||
alias=alias,
|
||||
name=name,
|
||||
topic=topic,
|
||||
federate=federate,
|
||||
is_direct=is_direct,
|
||||
invite=invite_list
|
||||
)
|
||||
if not isinstance(res, RoomCreateResponse):
|
||||
raise RuntimeError(res)
|
||||
return res.room_id
|
||||
|
||||
async def forget(self, room: MatrixRoom | str) -> None:
|
||||
"""Forget the room. The bot must not be a room member."""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_forget(self._room_id(room))
|
||||
if not isinstance(res, RoomForgetResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def event(self, room: MatrixRoom | str, event_id: str) -> Event:
|
||||
"""Get raw event information from matrix server (no cache used yet).
|
||||
|
||||
Args:
|
||||
- room - room where the event happened
|
||||
- event_id - ID of the event
|
||||
|
||||
Returns:
|
||||
- `nio.Event` on success
|
||||
- raises an exception on matrix error
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_get_event(
|
||||
self._room_id(room),
|
||||
event_id
|
||||
)
|
||||
if isinstance(res, RoomGetEventResponse):
|
||||
return res.event
|
||||
else:
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def leave(self, room: MatrixRoom | str) -> None:
|
||||
"""Leave the room (or reject the invite)."""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_leave(self._room_id(room))
|
||||
if not isinstance(res, RoomLeaveResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def join(self, room: MatrixRoom | str) -> None:
|
||||
"""Join the room we are invited to."""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.join(
|
||||
self._room_id(room)
|
||||
)
|
||||
if not isinstance(res, JoinResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def invite(self, room: MatrixRoom | str, user: MatrixUser | str) -> None:
|
||||
"""Invite the user to the room."""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_invite(
|
||||
self._room_id(room),
|
||||
self._user_id(user)
|
||||
)
|
||||
if not isinstance(res, RoomInviteResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def kick(self, room: MatrixRoom | str, user: MatrixUser | str, reason: str | None = None) -> None:
|
||||
"""Kick the user from the room. The user will be able to join the room
|
||||
again.
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_kick(
|
||||
self._room_id(room),
|
||||
self._user_id(user),
|
||||
reason
|
||||
)
|
||||
if not isinstance(res, RoomKickResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def ban(self, room: MatrixRoom | str, user: MatrixUser | str, reason: str | None = None) -> None:
|
||||
"""Ban the user from the room. The user will be unable to join until he
|
||||
is unbanned.
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_ban(
|
||||
self._room_id(room),
|
||||
self._user_id(user),
|
||||
reason
|
||||
)
|
||||
if not isinstance(res, RoomBanResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def unban(self, room: MatrixRoom | str, user: MatrixUser | str) -> None:
|
||||
"""Unban the user from the room."""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.room_unban(
|
||||
self._room_id(room),
|
||||
self._user_id(user)
|
||||
)
|
||||
if not isinstance(res, RoomUnbanResponse):
|
||||
raise RuntimeError(res)
|
||||
|
||||
async def members(self, room: MatrixRoom | str) -> list[RoomMember]:
|
||||
"""Get list of room members."""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientRoom is not set up")
|
||||
res = await self._client.joined_members(self._room_id(room))
|
||||
if not isinstance(res, JoinedMembersResponse):
|
||||
raise RuntimeError(res)
|
||||
return res.members
|
||||
506
src/mab/bot/_client_sender.py
Normal file
506
src/mab/bot/_client_sender.py
Normal file
@@ -0,0 +1,506 @@
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import logging
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
import traceback
|
||||
import os
|
||||
|
||||
import magic
|
||||
from PIL import Image
|
||||
from nio import AsyncClient, MatrixRoom, RoomSendResponse, RoomSendError
|
||||
from nio import OlmUnverifiedDeviceError
|
||||
|
||||
from ._client_uploader import ClientUploader
|
||||
from ..types import MatrixBotConfig, VideoFileProperties
|
||||
from ..utils import Utils
|
||||
|
||||
class ClientSender:
|
||||
"""This class sends messages"""
|
||||
#
|
||||
# PRIVATE
|
||||
#
|
||||
def _process_html_text(self, text: str, is_html: bool | None) -> dict:
|
||||
"""
|
||||
Processes `text` and `is_html` arguments of `send_*` functions and
|
||||
prepares `content` keys related to text data inside the message.
|
||||
|
||||
Args:
|
||||
- text - `text` as passed to the `send_*` function
|
||||
- is_html - `is_html` as passed to the `send_*` function
|
||||
|
||||
Returns:
|
||||
`dict` that contains keys required for the text message to be
|
||||
displayed correctly.
|
||||
"""
|
||||
# text w/ and w/o HTML
|
||||
text_w_html: str | None = None
|
||||
text_wo_html: str | None = None
|
||||
# check if HTML is present
|
||||
if is_html or is_html is None:
|
||||
# will be True if `text` contains HTML tags
|
||||
has_tags = False
|
||||
# text fragments without tags
|
||||
text_fragments = []
|
||||
# temporary extractor class
|
||||
class Extractor(HTMLParser):
|
||||
def handle_starttag(self, tag, attrs):
|
||||
nonlocal has_tags
|
||||
has_tags = True
|
||||
def handle_data(self, data):
|
||||
text_fragments.append(data)
|
||||
# parse
|
||||
parser = Extractor(convert_charrefs=True)
|
||||
try:
|
||||
parser.feed(text)
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
text_wo_html = text
|
||||
is_html = has_tags
|
||||
if is_html:
|
||||
text_wo_html = " ".join(text_fragments)
|
||||
text_w_html = text
|
||||
if not is_html:
|
||||
text_wo_html = text
|
||||
# return the content
|
||||
if text_w_html:
|
||||
return {
|
||||
"body": text_wo_html,
|
||||
"format": "org.matrix.custom.html",
|
||||
"formatted_body": text_w_html
|
||||
}
|
||||
else:
|
||||
return {
|
||||
"body": text_wo_html
|
||||
}
|
||||
|
||||
#
|
||||
# PUBLIC
|
||||
#
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger("ClientSender")
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
|
||||
async def setup(self,
|
||||
config: MatrixBotConfig,
|
||||
client: AsyncClient,
|
||||
uploader: ClientUploader) -> None:
|
||||
"""
|
||||
Setup the sender.
|
||||
|
||||
Args:
|
||||
- config - config to use
|
||||
- client - client to use
|
||||
- uploader - file uploaded to use
|
||||
"""
|
||||
self._config = config
|
||||
self._client = client
|
||||
self._uploader = uploader
|
||||
|
||||
async def content(self,
|
||||
room: MatrixRoom | str,
|
||||
content: dict,
|
||||
message_type: str = "m.room.message") -> RoomSendResponse:
|
||||
"""
|
||||
Send raw `content` JSON to `room`.
|
||||
|
||||
Args:
|
||||
- room - the room to send the content to
|
||||
- content - the content to send to the room
|
||||
|
||||
Returns:
|
||||
- `RoomSendResponse` returned by `AsyncClient.room_send`
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if self._client is None or self._config is None:
|
||||
raise RuntimeError("ClientSender is not set up")
|
||||
try:
|
||||
result = await self._client.room_send(
|
||||
room_id=room.room_id if isinstance(room, MatrixRoom) else room,
|
||||
message_type=message_type,
|
||||
content=content
|
||||
)
|
||||
except OlmUnverifiedDeviceError:
|
||||
if self._config.auto_verify_all_known_devices:
|
||||
if not Utils.verify_all_known_devices(self._client):
|
||||
raise
|
||||
return await self.content(room, content)
|
||||
else:
|
||||
raise
|
||||
if type(result) is RoomSendResponse:
|
||||
return result
|
||||
elif type(result) is RoomSendError:
|
||||
raise RuntimeError(result)
|
||||
else:
|
||||
raise RuntimeError("Unknown error has occured", result)
|
||||
|
||||
async def reaction(self, room: MatrixRoom | str, message_id: str, reaction: str) -> str:
|
||||
"""
|
||||
Add `reaction` to the message `message_id` in `room`.
|
||||
|
||||
Args:
|
||||
- room - the room of `message_id`
|
||||
- message_id - the message to add the `reaction` to
|
||||
- reaction - emoji of reaction
|
||||
|
||||
Returns:
|
||||
- `event_id` of added reaction on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
content = {
|
||||
"m.relates_to": {
|
||||
"event_id": message_id,
|
||||
"key": reaction,
|
||||
"rel_type": "m.annotation"
|
||||
}
|
||||
}
|
||||
return (await self.content(room, content, message_type="m.reaction")).event_id
|
||||
|
||||
async def text(self,
|
||||
room: MatrixRoom | str,
|
||||
text: str,
|
||||
*,
|
||||
is_html: bool | None = False) -> str:
|
||||
"""
|
||||
Send text message to `room`.
|
||||
|
||||
Args:
|
||||
- room - the room to send the text to
|
||||
- text - the text to send to the room
|
||||
- is_html - whether the text is HTML-formatted. Use `None` for auto
|
||||
|
||||
Returns:
|
||||
- `event_id` of sent message on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
text_data = self._process_html_text(text, is_html)
|
||||
content = {
|
||||
"msgtype": "m.text",
|
||||
**text_data
|
||||
}
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def image(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str, *,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = False,
|
||||
filename: str | None = None,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
"""
|
||||
Send the image to `room`. Please note that formatted text is displayed
|
||||
incorrectly in some clients as of September 8th, 2026
|
||||
|
||||
Args:
|
||||
- room - the room to send the text to
|
||||
- path - path to the image file
|
||||
- text - image caption to use (`None` to disable)
|
||||
- is_html - whether the text is HTML-formatted (`None` for auto)
|
||||
- filename - filename to use for the file (`None` for auto)
|
||||
- timeout - upload timeout in seconds (`None` to disable)
|
||||
|
||||
Returns:
|
||||
- `event_id` of sent message on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
# caption must not actually be empty
|
||||
if text is None or not text.strip():
|
||||
text = os.path.basename(path)
|
||||
is_html = False
|
||||
# check if the file is image
|
||||
mime_type: str = magic.from_file(path, mime=True)
|
||||
if not mime_type.startswith("image/"):
|
||||
raise RuntimeError(f"File {path} has non-image mime-type")
|
||||
# get image size
|
||||
with Image.open(path) as image:
|
||||
width, height = image.size
|
||||
# upload
|
||||
async with asyncio.timeout(timeout):
|
||||
upload_result = await self._uploader.upload_file(
|
||||
path, mime_type=mime_type, filename=filename)
|
||||
# prepare the content and send
|
||||
content = {
|
||||
"msgtype": "m.image",
|
||||
"filename": os.path.basename(path),
|
||||
**self._process_html_text(text, is_html),
|
||||
"file": {
|
||||
"url": upload_result.response.content_uri,
|
||||
"mimetype": mime_type,
|
||||
**upload_result.keys
|
||||
},
|
||||
"info": {
|
||||
"mimetype": mime_type,
|
||||
"size": upload_result.filesize,
|
||||
"w": width,
|
||||
"h": height
|
||||
}
|
||||
}
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def image_bytes(self,
|
||||
room: MatrixRoom | str,
|
||||
data: bytes,
|
||||
filename: str,
|
||||
*,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = False,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
"""
|
||||
Send the image to `room`. Please note that formatted text is displayed
|
||||
incorrectly in some clients as of September 8th, 2026
|
||||
|
||||
Args:
|
||||
- room - the room to send the text to
|
||||
- bytes - the image to send
|
||||
- filename - filename to use for the file
|
||||
- text - image caption to use (`None` to disable)
|
||||
- is_html - whether the text is HTML-formatted (`None` for auto)
|
||||
- timeout - upload timeout in seconds (`None` to disable)
|
||||
|
||||
Returns:
|
||||
- `event_id` of sent message on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
# caption must not actually be empty
|
||||
if text is None or not text.strip():
|
||||
text = filename
|
||||
is_html = False
|
||||
# check if the file is image
|
||||
mime_type: str = magic.from_buffer(data, mime=True)
|
||||
if not mime_type.startswith("image/"):
|
||||
raise RuntimeError(f"Data has non-image mime-type")
|
||||
# get image size
|
||||
buffer = BytesIO(data)
|
||||
with Image.open(buffer) as image:
|
||||
width, height = image.size
|
||||
buffer.seek(0)
|
||||
# upload
|
||||
async with asyncio.timeout(timeout):
|
||||
upload_result = await self._uploader.upload_using_provider(
|
||||
provider=buffer,
|
||||
mime_type=mime_type,
|
||||
filename=filename,
|
||||
filesize=len(data))
|
||||
# prepare the content and send
|
||||
content = {
|
||||
"msgtype": "m.image",
|
||||
"filename": filename,
|
||||
**self._process_html_text(text, is_html),
|
||||
"file": {
|
||||
"url": upload_result.response.content_uri,
|
||||
"mimetype": mime_type,
|
||||
**upload_result.keys
|
||||
},
|
||||
"info": {
|
||||
"mimetype": mime_type,
|
||||
"size": upload_result.filesize,
|
||||
"w": width,
|
||||
"h": height
|
||||
}
|
||||
}
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def video(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str,
|
||||
*,
|
||||
props: VideoFileProperties | None = None,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = False,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
"""
|
||||
Send the video to `room`. Please note that formatted text is displayed
|
||||
incorrectly in some clients as of September 8th, 2026. Unknown video
|
||||
properties will be automatically deduced as configured in
|
||||
`MatrixBotConfig`.
|
||||
|
||||
Args:
|
||||
- room - the room to send the text to
|
||||
- path - path to the video file
|
||||
- props - video properties (`None` for auto, if the feature is ON)
|
||||
- text - video caption to use (`None` to disable)
|
||||
- is_html - whether the text is HTML-formatted (`None` for auto)
|
||||
- timeout - upload timeout in seconds (`None` to disable)
|
||||
|
||||
Returns:
|
||||
- `event_id` of sent message on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if self._client is None or self._config is None:
|
||||
raise RuntimeError("ClientSender is not set up")
|
||||
# caption must not actually be empty
|
||||
if text is None or not text.strip():
|
||||
text = os.path.basename(path)
|
||||
is_html = False
|
||||
# check if the file is video
|
||||
mime_type: str = magic.from_file(path, mime=True)
|
||||
if not mime_type.startswith("video/"):
|
||||
raise RuntimeError(f"File {path} has non-video mime-type")
|
||||
# properties must not be empty
|
||||
if props is None:
|
||||
if not self._config.auto_ffprobe:
|
||||
raise RuntimeError(
|
||||
"No `props` are supplied and `auto_ffprobe` is disabled"
|
||||
)
|
||||
async with asyncio.timeout(30):
|
||||
props = await Utils.get_video_props_using_ffprobe(path)
|
||||
# autogenerate thumbnail if allowed to do so
|
||||
if not props.thumbnail and self._config.auto_ffmpeg:
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
props.thumbnail = await Utils.get_video_thumbnail(
|
||||
path,
|
||||
timestamp=props.duration_ms / 1000 / 2,
|
||||
max_size=400
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
async with asyncio.timeout(timeout):
|
||||
# upload the thumbnail if specified
|
||||
thumbnail_data = await self._uploader.upload_thumbnail(props.thumbnail)
|
||||
# upload
|
||||
upload_result = await self._uploader.upload_file(
|
||||
path,
|
||||
mime_type=mime_type
|
||||
)
|
||||
# prepare the content
|
||||
content = {
|
||||
"msgtype": "m.video",
|
||||
"filename": os.path.basename(path),
|
||||
**self._process_html_text(text, is_html),
|
||||
"file": {
|
||||
"url": upload_result.response.content_uri,
|
||||
"mimetype": mime_type,
|
||||
**upload_result.keys
|
||||
},
|
||||
"info": {
|
||||
"duration": props.duration_ms,
|
||||
"mimetype": mime_type,
|
||||
"size": upload_result.filesize,
|
||||
"w": props.width_px,
|
||||
"h": props.height_px,
|
||||
**thumbnail_data
|
||||
}
|
||||
}
|
||||
# send
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def file(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str,
|
||||
*,
|
||||
filename: str | None = None,
|
||||
mime_type: str | None = None,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = False,
|
||||
timeout: float | None = 60 * 60):
|
||||
"""
|
||||
Send the file to `room`. Please note that formatted text is displayed
|
||||
incorrectly in some clients as of September 8th, 2026.
|
||||
|
||||
Args:
|
||||
- room - the room to send the file to
|
||||
- path - path to the file
|
||||
- filename - filename to use for upload (`None` to use basename from
|
||||
`path`)
|
||||
- mime_type - mime type to use (`None` for autodetect using content
|
||||
of `path`)
|
||||
- text - caption to use (`None` to disable)
|
||||
- is_html - whether the text is HTML-formatted (`None` for auto)
|
||||
- timeout - upload timeout in seconds (`None` to disable)
|
||||
|
||||
Returns:
|
||||
- `event_id` of sent message on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if self._client is None or self._config is None:
|
||||
raise RuntimeError("ClientSender is not set up")
|
||||
# get filename if not set
|
||||
if not filename:
|
||||
filename = os.path.basename(path)
|
||||
# caption must not actually be empty
|
||||
if text is None or not text.strip():
|
||||
text = filename
|
||||
is_html = False
|
||||
# get the mime type if not specified
|
||||
if mime_type is None:
|
||||
mime_type = magic.from_file(path, mime=True)
|
||||
# upload
|
||||
async with asyncio.timeout(timeout):
|
||||
upload_result = await self._uploader.upload_file(
|
||||
path, mime_type=mime_type, filename=filename)
|
||||
# send
|
||||
content = {
|
||||
"msgtype": "m.file",
|
||||
"filename": filename,
|
||||
**self._process_html_text(text, is_html),
|
||||
"file": {
|
||||
"url": upload_result.response.content_uri,
|
||||
"mimetype": mime_type,
|
||||
**upload_result.keys
|
||||
},
|
||||
"info": {
|
||||
"mimetype": mime_type,
|
||||
"size": upload_result.filesize
|
||||
}
|
||||
}
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def file_bytes(self,
|
||||
room: MatrixRoom | str,
|
||||
data: bytes,
|
||||
filename: str,
|
||||
*,
|
||||
mime_type: str | None = None,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = False,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
"""
|
||||
Send the file to `room`.
|
||||
|
||||
Args:
|
||||
- room - the room to send the file to
|
||||
- data - the content of the file to send
|
||||
- filename - filename to use for the file
|
||||
- mime_type - mime type to use (`None` for autodetect using `data`
|
||||
content)
|
||||
- text - caption to use (`None` to disable)
|
||||
- is_html - whether the text is HTML-formatted (`None` for auto)
|
||||
- timeout - upload timeout in seconds (`None` to disable)
|
||||
|
||||
Returns:
|
||||
- `event_id` of sent message on success
|
||||
- Raises an exception on error
|
||||
"""
|
||||
# caption must not actually be empty
|
||||
if text is None or not text.strip():
|
||||
text = filename
|
||||
is_html = False
|
||||
# check if the file is image
|
||||
if not mime_type:
|
||||
mime_type = magic.from_buffer(data, mime=True)
|
||||
# upload
|
||||
buffer = BytesIO(data)
|
||||
async with asyncio.timeout(timeout):
|
||||
upload_result = await self._uploader.upload_using_provider(
|
||||
provider=buffer,
|
||||
mime_type=mime_type,
|
||||
filename=filename,
|
||||
filesize=len(data))
|
||||
# prepare the content and send
|
||||
content = {
|
||||
"msgtype": "m.file",
|
||||
"filename": filename,
|
||||
**self._process_html_text(text, is_html),
|
||||
"file": {
|
||||
"url": upload_result.response.content_uri,
|
||||
"mimetype": mime_type,
|
||||
**upload_result.keys
|
||||
},
|
||||
"info": {
|
||||
"mimetype": mime_type,
|
||||
"size": upload_result.filesize
|
||||
}
|
||||
}
|
||||
return (await self.content(room, content)).event_id
|
||||
187
src/mab/bot/_client_uploader.py
Normal file
187
src/mab/bot/_client_uploader.py
Normal file
@@ -0,0 +1,187 @@
|
||||
from typing import Any
|
||||
from pathlib import Path
|
||||
import io
|
||||
import os
|
||||
|
||||
import aiofiles
|
||||
import aiofiles.os
|
||||
import magic
|
||||
from PIL import Image
|
||||
|
||||
from nio import AsyncClient
|
||||
from nio import UploadError
|
||||
|
||||
from ._database import _Database
|
||||
from ..types import MatrixBotConfig, UploadResult
|
||||
|
||||
class ClientUploader:
|
||||
"""This class uploads files"""
|
||||
def __init__(self, db: _Database):
|
||||
self._db = db
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
|
||||
async def setup(self, config: MatrixBotConfig, client: AsyncClient) -> None:
|
||||
"""
|
||||
Setup the uploader.
|
||||
|
||||
Args:
|
||||
- config - config to take some settings from.
|
||||
"""
|
||||
self._config = config
|
||||
self._client = client
|
||||
|
||||
async def upload_using_provider(self,
|
||||
provider: Any,
|
||||
*,
|
||||
mime_type: str,
|
||||
filename: str,
|
||||
filesize: int) -> UploadResult:
|
||||
"""
|
||||
Upload data using provider (as defined in `AsyncClient.upload` docs).
|
||||
You better use `upload_file(...)`, `upload_bytes(...)`. Data is always
|
||||
encrypted.
|
||||
|
||||
Args:
|
||||
- provider - data provider (e.g. `aiofiles.open(...)`)
|
||||
- mime_type - mime-type of the data
|
||||
- filename - filename to declare for the file
|
||||
- filesize - size of the file
|
||||
|
||||
Returns:
|
||||
- `UploadResult` that contains all data you need on success
|
||||
- Raises an exception on failure
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("ClientUploader is not set up")
|
||||
response, keys = await self._client.upload(
|
||||
provider,
|
||||
content_type=mime_type,
|
||||
filename=filename,
|
||||
encrypt=True,
|
||||
monitor=None,
|
||||
filesize=filesize
|
||||
)
|
||||
if isinstance(response, UploadError):
|
||||
raise RuntimeError(f"Upload failed: {response.message}", response)
|
||||
return UploadResult(
|
||||
response=response,
|
||||
keys=keys, # type: ignore
|
||||
filename=filename,
|
||||
filesize=filesize
|
||||
)
|
||||
|
||||
async def upload_file(self,
|
||||
path: Path | str,
|
||||
*,
|
||||
mime_type: str | None = None,
|
||||
filename: str | None = None) -> UploadResult:
|
||||
"""
|
||||
Upload data from file. Data is always encrypted.
|
||||
|
||||
Args:
|
||||
- path - path to the file that needs to be uploaded
|
||||
- mime_type - mime-type to use for the file (`None` for auto)
|
||||
- filename - filename to use for the file (`None` for auto)
|
||||
"""
|
||||
if isinstance(path, str):
|
||||
path = Path(path)
|
||||
if not path.is_file():
|
||||
raise RuntimeError(f"{path} is not a file")
|
||||
if not filename:
|
||||
filename = os.path.basename(path)
|
||||
if not mime_type:
|
||||
mime_type = magic.from_file(path, mime=True)
|
||||
filesize = (await aiofiles.os.stat(path)).st_size
|
||||
async with aiofiles.open(path, "r+b") as f:
|
||||
return await self.upload_using_provider(
|
||||
f,
|
||||
mime_type=mime_type,
|
||||
filename=filename,
|
||||
filesize=filesize
|
||||
)
|
||||
|
||||
async def upload_bytes(self,
|
||||
data: bytes,
|
||||
*,
|
||||
filename: str,
|
||||
mime_type: str | None = None) -> UploadResult:
|
||||
"""
|
||||
Upload data. Data is always encrypted.
|
||||
|
||||
Args:
|
||||
- data - data that needs to be uploaded
|
||||
- filename - filename to use for the file
|
||||
- mime_type - mime-type to use for the file (`None` for auto)
|
||||
"""
|
||||
if not mime_type:
|
||||
mime_type = magic.from_buffer(data, mime=True)
|
||||
buffer = io.BytesIO(data)
|
||||
return await self.upload_using_provider(
|
||||
buffer,
|
||||
mime_type=mime_type,
|
||||
filename=filename,
|
||||
filesize=len(data)
|
||||
)
|
||||
|
||||
async def upload_thumbnail(self,
|
||||
thumbnail: Path | str | bytes | None) -> dict:
|
||||
"""
|
||||
Upload thumbnail and return fields required to use it for the video.
|
||||
|
||||
Args:
|
||||
- thumbnail - path to the thumbnail file or raw `bytes` of the
|
||||
image. You can actually pass `None`, empty dict will
|
||||
be returned in this case.
|
||||
|
||||
Returns:
|
||||
`dict` you should embed into your `content["info"]`
|
||||
"""
|
||||
if thumbnail is None:
|
||||
return {}
|
||||
# raw data
|
||||
raw_bytes_io: io.BytesIO | None = None
|
||||
if type(thumbnail) is bytes:
|
||||
thumb_mime = magic.from_buffer(thumbnail, mime=True)
|
||||
raw_bytes_io = io.BytesIO(thumbnail)
|
||||
# file path
|
||||
else:
|
||||
thumb_mime = magic.from_file(thumbnail, mime=True)
|
||||
# check if invalid MIME
|
||||
if not thumb_mime.startswith("image/"):
|
||||
raise RuntimeError(f"Thumbnail MIME is not image: `{thumb_mime}`")
|
||||
# get thumbnail size
|
||||
with Image.open(raw_bytes_io or thumbnail) as f:
|
||||
width, height = f.size
|
||||
# seek BytesIO to zero so we can reuse it
|
||||
if raw_bytes_io is not None:
|
||||
raw_bytes_io.seek(0)
|
||||
# upload
|
||||
if type(thumbnail) is bytes:
|
||||
thumb_size = len(thumbnail)
|
||||
upload_result = await self.upload_using_provider(
|
||||
raw_bytes_io,
|
||||
mime_type=thumb_mime,
|
||||
filename=f"preview.{thumb_mime.split("/")[-1]}",
|
||||
filesize=thumb_size
|
||||
)
|
||||
else:
|
||||
upload_result = await self.upload_file(
|
||||
thumbnail, # type: ignore
|
||||
mime_type=thumb_mime,
|
||||
filename=os.path.basename(str(thumbnail))
|
||||
)
|
||||
# return the result
|
||||
return {
|
||||
"thumbnail_file": {
|
||||
"url": upload_result.response.content_uri,
|
||||
"mimetype": thumb_mime,
|
||||
**upload_result.keys
|
||||
},
|
||||
"thumbnail_info": {
|
||||
"w": width,
|
||||
"h": height,
|
||||
"size": upload_result.filesize,
|
||||
"mimetype": thumb_mime
|
||||
}
|
||||
}
|
||||
165
src/mab/bot/_database.py
Normal file
165
src/mab/bot/_database.py
Normal file
@@ -0,0 +1,165 @@
|
||||
import sqlite3
|
||||
import aiosqlite
|
||||
import logging
|
||||
from typing import Any
|
||||
from pathlib import Path
|
||||
|
||||
from ..types import MatrixBotConfig
|
||||
|
||||
class _Database:
|
||||
"""Database interface"""
|
||||
|
||||
SCHEMA_VERSION = 3
|
||||
"""Version of the database schema"""
|
||||
|
||||
async def _create_tables(self) -> None:
|
||||
"""Create tables required for bot operation."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
STATEMENTS = (
|
||||
(
|
||||
"CREATE TABLE IF NOT EXISTS props("
|
||||
"name TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||
"value"
|
||||
")"
|
||||
),
|
||||
(
|
||||
"CREATE TABLE IF NOT EXISTS join_timestamps("
|
||||
"room_id TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||
"timestamp INTEGER"
|
||||
")"
|
||||
),
|
||||
(
|
||||
"CREATE TABLE IF NOT EXISTS user_kv_pairs("
|
||||
"key TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||
"value BLOB"
|
||||
")"
|
||||
)
|
||||
)
|
||||
self._logger.debug(f"Creating the tables")
|
||||
for statement in STATEMENTS:
|
||||
async with self._conn.execute(statement) as cursor:
|
||||
await cursor.fetchall()
|
||||
self._logger.debug(f"Tables are created")
|
||||
|
||||
def __init__(self, *, log_level = logging.INFO):
|
||||
"""Create database object."""
|
||||
self._conn: aiosqlite.Connection | None = None
|
||||
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||
self._logger.setLevel(log_level)
|
||||
|
||||
async def setup(self, config: MatrixBotConfig):
|
||||
"""Setup the database connection."""
|
||||
if self._conn is not None:
|
||||
raise RuntimeError("The connection already exists")
|
||||
# save config and create path to the database
|
||||
self._config = config
|
||||
db_path = self._config.storage_directory
|
||||
if not isinstance(db_path, Path):
|
||||
db_path = Path(db_path)
|
||||
db_path /= "database.sqlite"
|
||||
self._logger.debug(f"Database path is `{db_path}`")
|
||||
# connect to and setup database
|
||||
self._conn = await aiosqlite.connect(db_path, autocommit=True)
|
||||
self._conn.row_factory = sqlite3.Row
|
||||
self._logger.debug(f"Connected to the database")
|
||||
await self._create_tables()
|
||||
# get database schema version
|
||||
last_schema_version = await self.prop_get("schema_version") or self.SCHEMA_VERSION
|
||||
self._logger.debug(f"On-disk database schema version is `{last_schema_version}`")
|
||||
if not isinstance(last_schema_version, int):
|
||||
raise RuntimeError("Invalid last_schema_version type")
|
||||
# find version difference
|
||||
if self.SCHEMA_VERSION < last_schema_version:
|
||||
self._logger.critical(f"Database schema downgrade is not supported")
|
||||
raise RuntimeError("It is forbidden to downgrade `mab` database version")
|
||||
elif self.SCHEMA_VERSION > last_schema_version:
|
||||
self._logger.info(f"Database schema will be updated to `{self.SCHEMA_VERSION}`")
|
||||
# implement schema updating when needed
|
||||
# save current schema version
|
||||
await self.prop_set("schema_version", self.SCHEMA_VERSION)
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Close the database connection."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
self._logger.debug(f"Closing database connection")
|
||||
await self._conn.close()
|
||||
self._conn = None
|
||||
self._logger.debug(f"Database connection is closed")
|
||||
|
||||
async def prop_get(self, name: str) -> Any | None:
|
||||
"""Gets the value of the property `name` and returns it."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
async with self._conn.execute("SELECT value FROM props WHERE name=?",
|
||||
(name,)) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return row["value"]
|
||||
|
||||
async def prop_set(self, name: str, value: Any) -> None:
|
||||
"""Sets the value of the property `name` to `value`."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
async with self._conn.execute("REPLACE INTO props(name, value) VALUES(?, ?)",
|
||||
(name, value)) as cursor:
|
||||
await cursor.fetchall()
|
||||
self._logger.debug(f"Updated property `{name}`")
|
||||
|
||||
async def user_kv_get(self, key: str) -> bytes | None:
|
||||
"""Gets user key-value pair from the database. Returns None if it does
|
||||
not exist."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
async with self._conn.execute("SELECT value FROM user_kv_pairs WHERE key=?",
|
||||
(key,)) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return row["value"]
|
||||
|
||||
async def user_kv_set(self, key: str, value: bytes | None) -> bytes | None:
|
||||
"""Sets user key-value pair in the database. Use `None` to remove it.
|
||||
Returns `value`."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
if value is not None:
|
||||
async with self._conn.execute("REPLACE INTO user_kv_pairs(key, value) VALUES(?, ?)",
|
||||
(key, value)) as cursor:
|
||||
await cursor.fetchall()
|
||||
self._logger.debug(f"Updated user key-value `{key}`")
|
||||
else:
|
||||
async with self._conn.execute("DELETE FROM user_kv_pairs WHERE key=?",
|
||||
(key,)) as cursor:
|
||||
await cursor.fetchall()
|
||||
self._logger.debug(f"Removed user key-value `{key}`")
|
||||
return value
|
||||
|
||||
async def join_timestamp_get(self, room_id: str) -> int | None:
|
||||
"""Returns the server timestamp when the room was joined (or None)."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
async with self._conn.execute("SELECT timestamp FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor:
|
||||
row = await cursor.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return row["timestamp"]
|
||||
|
||||
async def join_timestamp_set(self, room_id: str, timestamp: int) -> None:
|
||||
"""Sets the server timestamp when the room was joined."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
async with self._conn.execute("REPLACE INTO join_timestamps(room_id, timestamp) VALUES(?, ?)",
|
||||
(room_id, timestamp)) as cursor:
|
||||
await cursor.fetchall()
|
||||
self._logger.debug(f"Updated join timestamp for room `{room_id}`")
|
||||
|
||||
async def join_timestamp_remove(self, room_id: str) -> None:
|
||||
"""Removes the server timestamp when the room was joined."""
|
||||
if self._conn is None:
|
||||
raise RuntimeError("No connection exists")
|
||||
async with self._conn.execute("DELETE FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor:
|
||||
await cursor.fetchall()
|
||||
self._logger.debug(f"Removed join timestamp for room `{room_id}`")
|
||||
84
src/mab/bot/_validation.py
Normal file
84
src/mab/bot/_validation.py
Normal file
@@ -0,0 +1,84 @@
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from ..types import MatrixBotConfig
|
||||
|
||||
class Validator:
|
||||
"""This class is used inside MatrixBot to validate data"""
|
||||
|
||||
def validate_matrix_homeserver_url(self, url: str) -> None:
|
||||
"""
|
||||
Check if `url` is a valid matrix homeserver URL.
|
||||
|
||||
Args:
|
||||
- url - URL to check (only format is checked)
|
||||
|
||||
Returns:
|
||||
- Does not return anything
|
||||
- Raises an exception on error
|
||||
"""
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise RuntimeError(
|
||||
f"Scheme {parsed.scheme} is not a valid scheme for matrix "
|
||||
"homeserver URL"
|
||||
)
|
||||
if not parsed.netloc:
|
||||
raise RuntimeError(
|
||||
f"{url} is not a valid matrix homeserver URL"
|
||||
)
|
||||
if parsed.path != "":
|
||||
raise RuntimeError(
|
||||
f"{url} must have empty path (remove `{parsed.path}` after the "
|
||||
"hostname)"
|
||||
)
|
||||
|
||||
def validate_matrix_username_localpart(self, localpart: str) -> None:
|
||||
"""
|
||||
Check if `localpart` is a valid localpart of matrix username.
|
||||
|
||||
Args:
|
||||
- localpart - localpart of matrix username
|
||||
|
||||
Returns:
|
||||
- Does not return anything
|
||||
- Raises an exception on error
|
||||
"""
|
||||
pattern = r"^[a-z0-9._=\-]+$"
|
||||
if not bool(re.fullmatch(pattern, localpart)) or len(localpart) > 255:
|
||||
raise RuntimeError(
|
||||
f"{localpart} is not a valid matrix username localpart"
|
||||
)
|
||||
|
||||
def ensure_directory_exists(self, path: Path | str) -> None:
|
||||
"""
|
||||
Ensure that `path` is an existing directory. Creates it if it does not
|
||||
exist. The entire directory tree is created if needed.
|
||||
|
||||
Args:
|
||||
- path - directory path
|
||||
|
||||
Returns:
|
||||
- Does not return anything
|
||||
- Raises an exception on error
|
||||
"""
|
||||
if isinstance(path, str):
|
||||
path = Path(path)
|
||||
if not path.is_dir():
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def validate_bot_config(self, config: MatrixBotConfig) -> None:
|
||||
"""
|
||||
Check if `config` is a valid MatrixBot config.
|
||||
|
||||
Args:
|
||||
- config - configuration to check
|
||||
|
||||
Returns:
|
||||
- Does not return anything
|
||||
- Raises an exception on error
|
||||
"""
|
||||
self.validate_matrix_homeserver_url(config.matrix_homeserver_url)
|
||||
self.validate_matrix_username_localpart(config.matrix_username_localpart)
|
||||
self.ensure_directory_exists(config.storage_directory)
|
||||
175
src/mab/bot/bot.py
Normal file
175
src/mab/bot/bot.py
Normal file
@@ -0,0 +1,175 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from typing import Callable, Coroutine, Any, overload
|
||||
|
||||
from nio import AsyncClient, MatrixRoom, Event
|
||||
|
||||
from ..filters.base import BaseEventFilter
|
||||
from ..types import *
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
from ._validation import Validator
|
||||
from ._database import _Database
|
||||
from ._client_auth import ClientAuth
|
||||
from ._client_room_operations import ClientRoomOperations
|
||||
from ._client_downloader import ClientDownloader
|
||||
from ._client_manager import ClientManager
|
||||
from ._client_uploader import ClientUploader
|
||||
from ._client_sender import ClientSender
|
||||
from ._callbacks import Callbacks
|
||||
|
||||
|
||||
class MatrixBot:
|
||||
"""
|
||||
Asynchronous Matrix Bot Implementation.
|
||||
"""
|
||||
|
||||
def __init__(self, config: MatrixBotConfig, *, log_level = logging.INFO) -> None:
|
||||
# create the logger
|
||||
self._logger = logging.getLogger(self.__class__.__name__)
|
||||
self._logger.setLevel(log_level)
|
||||
self._was_started = False
|
||||
# create classes that compose MatrixBot
|
||||
self._validator = Validator()
|
||||
self._database = _Database(log_level=log_level)
|
||||
self._client_auth = ClientAuth(self._database, log_level=log_level)
|
||||
self._client_manager = ClientManager(self._client_auth, self._database, log_level=log_level)
|
||||
self._client_uploader = ClientUploader(self._database)
|
||||
self._client_downloader = ClientDownloader()
|
||||
self._client_room_operations = ClientRoomOperations()
|
||||
self._client_sender = ClientSender()
|
||||
self._callbacks = Callbacks(self._database, self)
|
||||
# validate the config and save it
|
||||
try:
|
||||
self._validator.validate_bot_config(config)
|
||||
self._config: MatrixBotConfig = config
|
||||
except Exception as e:
|
||||
self._logger.error(f"Couldn't validate bot config: {e}")
|
||||
raise
|
||||
|
||||
def add_callback(self,
|
||||
filter: BaseEventFilter,
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
|
||||
*,
|
||||
stop_matching: bool = True) -> None:
|
||||
"""
|
||||
Add filter-based callback.
|
||||
|
||||
Args:
|
||||
- filter - filter to use for the callback
|
||||
- callback - the callback that must be called if the filter matches.
|
||||
Use `None` to log the type of the Event that will
|
||||
happen for specified filter.
|
||||
- stop_matching - whether to stop matching if the filter matches
|
||||
"""
|
||||
self._callbacks.add_room_event_callback(
|
||||
filter=filter,
|
||||
callback=callback,
|
||||
stop_matching=stop_matching
|
||||
)
|
||||
|
||||
async def start(self) -> None:
|
||||
"""
|
||||
Start client operation in background. This method can be called
|
||||
succesfully only once for `MatrixBot` object. Any subsequent calls
|
||||
will raise an exception.
|
||||
"""
|
||||
if self._was_started:
|
||||
raise RuntimeError("The bot was already started")
|
||||
self._was_started = True
|
||||
await self._client_manager.setup(self._config)
|
||||
await self._database.setup(self._config)
|
||||
await self._client_auth.setup(self._config)
|
||||
await self._client_uploader.setup(
|
||||
self._config,
|
||||
self._client_manager.get_client()
|
||||
)
|
||||
await self._client_downloader.setup(
|
||||
self._config,
|
||||
self._client_manager.get_client()
|
||||
)
|
||||
await self._client_room_operations.setup(
|
||||
self._config,
|
||||
self._client_manager.get_client()
|
||||
)
|
||||
await self._client_sender.setup(
|
||||
self._config,
|
||||
self._client_manager.get_client(),
|
||||
self._client_uploader
|
||||
)
|
||||
await self._callbacks.setup(
|
||||
self._config,
|
||||
self._client_manager.get_client()
|
||||
)
|
||||
await self._client_manager.start()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""
|
||||
Stop client operation in background. This method can be called only if
|
||||
the client was `start(...)`ed previously. This method will wait for the
|
||||
bot to completely stop.
|
||||
"""
|
||||
await self._client_manager.stop()
|
||||
await self._database.close()
|
||||
|
||||
async def run(self) -> None:
|
||||
"""
|
||||
Start bot operation in foreground. You may cancel task running this
|
||||
method to stop the bot.
|
||||
|
||||
Warning: calling `stop()` is not a supported way to stop the bot. You
|
||||
should cancel this task instead.
|
||||
"""
|
||||
await self.start()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
await self.stop()
|
||||
|
||||
async def save_value(self, key: str, value: bytes | None) -> bytes | None:
|
||||
"""Save key-value pair to the database. Save `None` to remove the key.
|
||||
Returns `value`.
|
||||
|
||||
Please use this feature for simple bots only. Prefer your own database
|
||||
for higher efficiency.
|
||||
"""
|
||||
return await self._database.user_kv_set(key, value)
|
||||
|
||||
async def load_value(self, key: str) -> bytes | None:
|
||||
"""Load key-value pair from the database. Returns `None` if the key
|
||||
does not exist.
|
||||
|
||||
Please use this feature for simple bots only. Prefer your own database
|
||||
for higher efficiency.
|
||||
"""
|
||||
return await self._database.user_kv_get(key)
|
||||
|
||||
@property
|
||||
def client(self) -> AsyncClient:
|
||||
"""
|
||||
Get AsyncClient.
|
||||
|
||||
Returns:
|
||||
- `AsyncClient` you may use to access Matrix. Raises a RuntimeError
|
||||
if the client does not exist or is not operational.
|
||||
"""
|
||||
return self._client_manager.get_client()
|
||||
|
||||
@property
|
||||
def send(self) -> ClientSender:
|
||||
"""Get ClientSender that you should use to send messages."""
|
||||
return self._client_sender
|
||||
|
||||
@property
|
||||
def download(self) -> ClientDownloader:
|
||||
"""Get ClientDownloader that you should use to download files."""
|
||||
return self._client_downloader
|
||||
|
||||
@property
|
||||
def rooms(self) -> ClientRoomOperations:
|
||||
"""Get ClientRoomOperations that you should use to do room-related
|
||||
actions.
|
||||
"""
|
||||
return self._client_room_operations
|
||||
18
src/mab/context/__init__.py
Normal file
18
src/mab/context/__init__.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from dataclasses import dataclass
|
||||
from nio import MatrixRoom, Event
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from ..bot import MatrixBot
|
||||
|
||||
@dataclass
|
||||
class EventContext:
|
||||
"""The class holding information about an event that happened in the room"""
|
||||
|
||||
room: MatrixRoom
|
||||
"""The room the event has happened in"""
|
||||
|
||||
event: Event
|
||||
"""The event that has happened in the room"""
|
||||
|
||||
bot: "MatrixBot"
|
||||
"""The bot that is the source of the event"""
|
||||
123
src/mab/context/vars/__init__.py
Normal file
123
src/mab/context/vars/__init__.py
Normal file
@@ -0,0 +1,123 @@
|
||||
from typing import Any
|
||||
import inspect
|
||||
import traceback
|
||||
import logging
|
||||
|
||||
from .. import EventContext
|
||||
|
||||
class ContextVarKey[T]:
|
||||
"""This class is used to allow type hinting for context variable keys."""
|
||||
def __init__(self, name: str) -> None:
|
||||
self._name = name
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ContextDataKey({repr(self._name)})"
|
||||
|
||||
class ContextVars:
|
||||
"""This class implements context variable storage."""
|
||||
|
||||
def _raw(self) -> dict[ContextVarKey, Any]:
|
||||
"""Get raw context data storage."""
|
||||
if not hasattr(self, "_datastore"):
|
||||
self._datastore: dict[ContextVarKey, Any] = {}
|
||||
return self._datastore
|
||||
|
||||
def __setitem__[T](self, key: ContextVarKey[T], value: T | None) -> None:
|
||||
"""Set a value inside the context data storage. `None` removes it"""
|
||||
if value is None:
|
||||
del self._raw()[key]
|
||||
else:
|
||||
self._raw()[key] = value
|
||||
|
||||
def __getitem__[T](self, key: ContextVarKey[T]) -> T:
|
||||
"""
|
||||
Get a value inside the context data storage.
|
||||
|
||||
Raises RuntimeError if the value is not present.
|
||||
"""
|
||||
if key not in self._raw():
|
||||
raise RuntimeError(f"Context does not contain {repr(key)}")
|
||||
return self._raw()[key]
|
||||
|
||||
def __contains__[T](self, key: ContextVarKey[T]) -> bool:
|
||||
"""Check if context data storage contains the value"""
|
||||
if key not in self._raw():
|
||||
return False
|
||||
return True
|
||||
|
||||
def __add__(self, another: "ContextVars") -> "ContextVars":
|
||||
res = ContextVars()
|
||||
res += self
|
||||
res += another
|
||||
return res
|
||||
|
||||
def __radd__(self, another: "ContextVars") -> "ContextVars":
|
||||
return self.__add__(another)
|
||||
|
||||
def __iadd__(self, another: "ContextVars") -> "ContextVars":
|
||||
theirs = another._raw()
|
||||
ours = self._raw()
|
||||
for k in theirs:
|
||||
ours[k] = theirs[k]
|
||||
return self
|
||||
|
||||
|
||||
class ContextVarsPopulator:
|
||||
"""This class populates ContextVars using builders decorated with
|
||||
`autobuilder`.
|
||||
"""
|
||||
_LOGGER = logging.getLogger("ContextVarsPopulator")
|
||||
_sync_builders = []
|
||||
_async_builders = []
|
||||
|
||||
@classmethod
|
||||
def autobuilder(cls, func):
|
||||
"""This method adds the function to the list of autobuilders. If the
|
||||
function can't be used as autobuilder then it will raise a TypeError.
|
||||
|
||||
Args:
|
||||
- func - function to add as an autobuilder
|
||||
"""
|
||||
if not inspect.isfunction(func):
|
||||
raise TypeError("Autobuilder must be a function")
|
||||
kinds = [p.kind for p in inspect.signature(func).parameters.values()]
|
||||
if len(kinds) != 2:
|
||||
raise TypeError("Autobuilder must take exactly 2 arguments")
|
||||
allowed_kinds = [
|
||||
inspect._ParameterKind.POSITIONAL_ONLY,
|
||||
inspect._ParameterKind.POSITIONAL_OR_KEYWORD
|
||||
]
|
||||
if not all((k in allowed_kinds) for k in kinds):
|
||||
raise TypeError("Autobuilder arguments must be positional")
|
||||
if inspect.iscoroutinefunction(func):
|
||||
cls._async_builders.append(func)
|
||||
else:
|
||||
cls._sync_builders.append(func)
|
||||
cls._LOGGER.debug(f"Added autobuilder function: {func}")
|
||||
return func
|
||||
|
||||
@classmethod
|
||||
def sync_populate(cls, context: EventContext, vars: ContextVars) -> None:
|
||||
"""Populate context variables using sync builders.
|
||||
|
||||
Args:
|
||||
- vars - ContextVars to set variables in
|
||||
"""
|
||||
for builder in cls._sync_builders:
|
||||
try:
|
||||
builder(context, vars)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
@classmethod
|
||||
async def async_populate(cls, context: EventContext, vars: ContextVars) -> None:
|
||||
"""Populate context variables using async builders.
|
||||
|
||||
Args:
|
||||
- vars - ContextVars to set variables in
|
||||
"""
|
||||
for builder in cls._async_builders:
|
||||
try:
|
||||
await builder(context, vars)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
2
src/mab/context/vars/command/__init__.py
Normal file
2
src/mab/context/vars/command/__init__.py
Normal file
@@ -0,0 +1,2 @@
|
||||
from .types import *
|
||||
from .keys import *
|
||||
6
src/mab/context/vars/command/keys.py
Normal file
6
src/mab/context/vars/command/keys.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from .types import *
|
||||
from .. import ContextVarKey
|
||||
|
||||
CTX_COMMAND = ContextVarKey[Command]("CTX_COMMAND")
|
||||
"""Variable that describes the command. It is set when the event was matched by
|
||||
`BodyCommandFilter`."""
|
||||
13
src/mab/context/vars/command/types.py
Normal file
13
src/mab/context/vars/command/types.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Command(BaseModel):
|
||||
"""This model defines the command detected by command filter."""
|
||||
|
||||
prefix: str
|
||||
"""The prefix of the command"""
|
||||
|
||||
verb: str
|
||||
"""The verb of the command"""
|
||||
|
||||
args: list[str]
|
||||
"""The list of arguments of the command"""
|
||||
3
src/mab/context/vars/message/__init__.py
Normal file
3
src/mab/context/vars/message/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .types import *
|
||||
from .keys import *
|
||||
from . import builders
|
||||
43
src/mab/context/vars/message/builders.py
Normal file
43
src/mab/context/vars/message/builders.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from ... import EventContext
|
||||
from .. import ContextVars, ContextVarsPopulator
|
||||
|
||||
from . import *
|
||||
|
||||
def _file_extractor_none(source: dict):
|
||||
"""File extractor for messages that contain no file."""
|
||||
return None
|
||||
|
||||
def _file_extractor_generic(source: dict):
|
||||
"""File extractor for generic msgtype"""
|
||||
content = source["content"]
|
||||
# we can continue only if either of them is present
|
||||
if ("file" not in content) == ("url" not in content):
|
||||
return None
|
||||
file = MessageFile()
|
||||
file.filename = content.get("filename") or content.get("body")
|
||||
info = content.get("info")
|
||||
if info:
|
||||
file.filesize = info.get("size")
|
||||
file.mimetype = info.get("mimetype")
|
||||
return file
|
||||
|
||||
def _get_file_extractor(source: dict):
|
||||
"""This function returns function that will generate MessageFile."""
|
||||
return {
|
||||
"m.image": _file_extractor_generic,
|
||||
"m.file": _file_extractor_generic,
|
||||
"m.audio": _file_extractor_generic,
|
||||
"m.video": _file_extractor_generic,
|
||||
}.get(source["content"]["msgtype"], _file_extractor_none)
|
||||
|
||||
|
||||
@ContextVarsPopulator.autobuilder
|
||||
def _build_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This builder creates a CTX_MESSAGE variable for any message."""
|
||||
source = ctx.event.source
|
||||
if source["type"] != "m.room.message":
|
||||
return
|
||||
content: dict = source["content"]
|
||||
msg = Message.model_validate(content)
|
||||
msg.file = _get_file_extractor(source)(source)
|
||||
vars[CTX_MESSAGE] = msg
|
||||
5
src/mab/context/vars/message/keys.py
Normal file
5
src/mab/context/vars/message/keys.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .types import *
|
||||
from .. import ContextVarKey
|
||||
|
||||
CTX_MESSAGE = ContextVarKey[Message]("CTX_MESSAGE")
|
||||
"""Variable that describes the message. It exists when the message exists."""
|
||||
54
src/mab/context/vars/message/types.py
Normal file
54
src/mab/context/vars/message/types.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from typing import Literal
|
||||
from pydantic import BaseModel, SkipValidation
|
||||
|
||||
class Message(BaseModel):
|
||||
"""This model describes message of any kind and is being used as base
|
||||
model for other types of message. Unknown message types are interpreted
|
||||
as this model only."""
|
||||
|
||||
msgtype: str
|
||||
"""It identifies the type of message being sent"""
|
||||
|
||||
body: str
|
||||
"""Unformatted (or fallback) body of the message"""
|
||||
|
||||
format: str | None = None
|
||||
"""Format of the formatted_body content"""
|
||||
|
||||
formatted_body: str | None = None
|
||||
"""Formatted body of the message, present if `format` is not None"""
|
||||
|
||||
file: SkipValidation[MessageFile | None] = None
|
||||
"""The file attached to the message."""
|
||||
|
||||
class MessageFile(BaseModel):
|
||||
"""This model describes a file attached to the message. Fields of this
|
||||
model should be used to get some basic info about the file and should not
|
||||
be used to download the file itself."""
|
||||
|
||||
filename: str | None = None
|
||||
"""The original filename of the uploaded file."""
|
||||
|
||||
filesize: int | None = None
|
||||
"""The size of the file in bytes."""
|
||||
|
||||
mimetype: str | None = None
|
||||
"""The mimetype of the file."""
|
||||
|
||||
thumbnail: MessageFileThumbnail | None = None
|
||||
"""The thumbnail of the file."""
|
||||
|
||||
class MessageFileThumbnail(BaseModel):
|
||||
"""This model describes the thumbnail of the file."""
|
||||
|
||||
width: int | None = None
|
||||
"""The width of the thumbnail."""
|
||||
|
||||
height: int | None = None
|
||||
"""The height of the thumbnail."""
|
||||
|
||||
mimetype: str | None = None
|
||||
"""The mimetype of the thumbnail."""
|
||||
|
||||
size: int | None = None
|
||||
"""The size of the thumbnail in bytes."""
|
||||
3
src/mab/context/vars/reaction/__init__.py
Normal file
3
src/mab/context/vars/reaction/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .types import *
|
||||
from .keys import *
|
||||
from . import builders
|
||||
18
src/mab/context/vars/reaction/builders.py
Normal file
18
src/mab/context/vars/reaction/builders.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from ... import EventContext
|
||||
from .. import ContextVars, ContextVarsPopulator
|
||||
|
||||
from . import *
|
||||
import json
|
||||
|
||||
@ContextVarsPopulator.autobuilder
|
||||
def _build_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This builder creates a CTX_MESSAGE variable for any message."""
|
||||
source = ctx.event.source
|
||||
if source.get("type") != "m.reaction":
|
||||
return
|
||||
res = Reaction(
|
||||
message_id=source["content"]["m.relates_to"]["event_id"],
|
||||
reaction=source["content"]["m.relates_to"]["key"],
|
||||
sender=source["sender"]
|
||||
)
|
||||
vars[CTX_REACTION] = res
|
||||
6
src/mab/context/vars/reaction/keys.py
Normal file
6
src/mab/context/vars/reaction/keys.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from .types import *
|
||||
from .. import ContextVarKey
|
||||
|
||||
CTX_REACTION = ContextVarKey[Reaction]("CTX_REACTION")
|
||||
"""Variable that describes the reaction. It exists when the event is a new
|
||||
reaction."""
|
||||
13
src/mab/context/vars/reaction/types.py
Normal file
13
src/mab/context/vars/reaction/types.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Reaction(BaseModel):
|
||||
"""A reaction to a message"""
|
||||
|
||||
message_id: str
|
||||
"""Event ID for the message this reaction is added to."""
|
||||
|
||||
reaction: str
|
||||
"""The reaction (emoji)."""
|
||||
|
||||
sender: str
|
||||
"""Fully qualified username of the reactor."""
|
||||
3
src/mab/context/vars/room_event/__init__.py
Normal file
3
src/mab/context/vars/room_event/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .types import *
|
||||
from .keys import *
|
||||
from . import builders
|
||||
17
src/mab/context/vars/room_event/builders.py
Normal file
17
src/mab/context/vars/room_event/builders.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from ... import EventContext
|
||||
from .. import ContextVars, ContextVarsPopulator
|
||||
|
||||
from . import *
|
||||
|
||||
@ContextVarsPopulator.autobuilder
|
||||
def _build_room_event(ctx: EventContext, vars: ContextVars) -> None:
|
||||
ev = ctx.event
|
||||
vars[CTX_ROOM_EVENT] = RoomEvent(
|
||||
source=ev.source,
|
||||
content=ev.source["content"],
|
||||
event_id=ev.event_id,
|
||||
origin_server_ts=ev.source["origin_server_ts"],
|
||||
room_id=ctx.room.room_id,
|
||||
sender=ev.sender,
|
||||
type=ev.source["type"]
|
||||
)
|
||||
5
src/mab/context/vars/room_event/keys.py
Normal file
5
src/mab/context/vars/room_event/keys.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .types import *
|
||||
from .. import ContextVarKey
|
||||
|
||||
CTX_ROOM_EVENT = ContextVarKey[RoomEvent]("CTX_ROOM_EVENT")
|
||||
"""Variable that describes the event that has happened in the room."""
|
||||
29
src/mab/context/vars/room_event/types.py
Normal file
29
src/mab/context/vars/room_event/types.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class RoomEvent(BaseModel):
|
||||
"""This model defines basic fields of the room event."""
|
||||
|
||||
source: dict
|
||||
"""`event.source` as returned by `matrix-nio`."""
|
||||
|
||||
content: dict
|
||||
"""Raw event content as returned by the matrix homeserver. You should
|
||||
validate it as it is not guranteed that the schema is valid."""
|
||||
|
||||
event_id: str
|
||||
"""The globally unique identifier for the event. It is completely opaque and
|
||||
is not intended to be human-readable."""
|
||||
|
||||
origin_server_ts: int
|
||||
"""Timestamp (in milliseconds since the unix epoch) on originating
|
||||
homeserver when this event was sent."""
|
||||
|
||||
room_id: str
|
||||
"""Opaque identifier of a room starting with excamation mark. They are not
|
||||
indended to be human-readable even if they contain readable domain."""
|
||||
|
||||
sender: str
|
||||
"""Fully-qualified ID of the user who sent the event."""
|
||||
|
||||
type: str
|
||||
"""The type of the event."""
|
||||
5
src/mab/filters/__init__.py
Normal file
5
src/mab/filters/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .base import EventTypeFilter
|
||||
|
||||
from .body import *
|
||||
from .message import *
|
||||
from .room import *
|
||||
160
src/mab/filters/base.py
Normal file
160
src/mab/filters/base.py
Normal file
@@ -0,0 +1,160 @@
|
||||
from abc import ABC
|
||||
import logging
|
||||
from typing import Type
|
||||
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
class BaseEventFilter(ABC):
|
||||
"""Base class for all message filters. Always returns True."""
|
||||
_logger = logging.Logger("EventFilter")
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
for a in kwargs:
|
||||
self._logger.critical(f"Unknown keyword argument for some filter is used: '{a}'={repr(kwargs[a])}")
|
||||
|
||||
# AND
|
||||
def __and__(self, other):
|
||||
if not isinstance(other, BaseEventFilter):
|
||||
raise TypeError(f"BaseEventFilter can't be ANDed against {type(other)}")
|
||||
return CompoundEventFilter(
|
||||
CompoundEventFilter.OPERATOR_AND,
|
||||
[self, other]
|
||||
)
|
||||
|
||||
def __rand__(self, other):
|
||||
return self.__and__(other)
|
||||
|
||||
# OR
|
||||
def __or__(self, other):
|
||||
if not isinstance(other, BaseEventFilter):
|
||||
raise TypeError(f"BaseEventFilter can't be ORed against {type(other)}")
|
||||
return CompoundEventFilter(
|
||||
CompoundEventFilter.OPERATOR_OR,
|
||||
[self, other]
|
||||
)
|
||||
|
||||
def __ror__(self, other):
|
||||
return self.__or__(other)
|
||||
|
||||
# XOR
|
||||
def __xor__(self, other):
|
||||
if not isinstance(other, BaseEventFilter):
|
||||
raise TypeError(f"BaseEventFilter can't be XORed against {type(other)}")
|
||||
return CompoundEventFilter(
|
||||
CompoundEventFilter.OPERATOR_XOR,
|
||||
[self, other]
|
||||
)
|
||||
|
||||
def __rxor__(self, other):
|
||||
return self.__xor__(other)
|
||||
|
||||
# INVERT
|
||||
def __invert__(self):
|
||||
return CompoundEventFilter(
|
||||
CompoundEventFilter.OPERATOR_INVERT,
|
||||
[self]
|
||||
)
|
||||
|
||||
# PAYLOAD
|
||||
def __repr__(self) -> str:
|
||||
"""
|
||||
This method may be redefined in derived classes to improve debugging
|
||||
experience.
|
||||
"""
|
||||
return str(self.__class__.__name__)
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
"""
|
||||
This method checks if the event from `ctx` matches filter-specific
|
||||
criteria. The filter may add variables to `vars`. If the callback will
|
||||
be called then these variables will be added to the final context
|
||||
variables. This function should return True if criteria is matched.
|
||||
False must be returned otherwise.
|
||||
|
||||
Args:
|
||||
- ctx - context to filter
|
||||
- vars - variables object that may be modified by the filter
|
||||
|
||||
Returns:
|
||||
- True if the context matches the criteria
|
||||
- False if the context does not match the criteria
|
||||
"""
|
||||
return True
|
||||
|
||||
class EventTypeFilter(BaseEventFilter):
|
||||
"""Event filter that checks if the event is an instance of some class."""
|
||||
def __init__(self, type: Type, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._type = type
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return isinstance(ctx.event, self._type)
|
||||
|
||||
class CompoundEventFilter(BaseEventFilter):
|
||||
"""Event filter that consists of multiple filters."""
|
||||
OPERATOR_AND = "and"
|
||||
OPERATOR_OR = "or"
|
||||
OPERATOR_XOR = "xor"
|
||||
OPERATOR_INVERT = "invert"
|
||||
|
||||
@staticmethod
|
||||
def _is_operator_valid(op: str) -> bool:
|
||||
"""Returns True if operator `op` is a valid operator"""
|
||||
return op in [
|
||||
CompoundEventFilter.OPERATOR_AND,
|
||||
CompoundEventFilter.OPERATOR_OR,
|
||||
CompoundEventFilter.OPERATOR_XOR,
|
||||
CompoundEventFilter.OPERATOR_INVERT
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _is_elements_count_valid(op: str, count: int) -> bool:
|
||||
"""Returns True if operator `op` may take `count` arguments"""
|
||||
return count in {
|
||||
CompoundEventFilter.OPERATOR_AND: [2],
|
||||
CompoundEventFilter.OPERATOR_OR: [2],
|
||||
CompoundEventFilter.OPERATOR_XOR: [2],
|
||||
CompoundEventFilter.OPERATOR_INVERT: [1],
|
||||
}[op]
|
||||
|
||||
def __init__(self, operator: str, arguments: list[BaseEventFilter], **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if not self._is_operator_valid(operator):
|
||||
raise RuntimeError(f"Invalid operator `{operator}`")
|
||||
if not self._is_elements_count_valid(operator, len(arguments)):
|
||||
raise RuntimeError(f"Operator `{operator}` does not take `{len(arguments)}` arguments")
|
||||
self._operator = operator
|
||||
self._arguments = list(arguments)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
expression = "False"
|
||||
reprs = [repr(a) for a in self._arguments]
|
||||
if self._operator == CompoundEventFilter.OPERATOR_AND:
|
||||
expression = " & ".join(reprs)
|
||||
elif self._operator == CompoundEventFilter.OPERATOR_OR:
|
||||
expression = " | ".join(reprs)
|
||||
elif self._operator == CompoundEventFilter.OPERATOR_XOR:
|
||||
expression = " ^ ".join(reprs)
|
||||
elif self._operator == CompoundEventFilter.OPERATOR_INVERT:
|
||||
expression = f"~{reprs[0]}"
|
||||
return f"({expression})"
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
evaluated = [await arg(ctx, vars) for arg in self._arguments]
|
||||
if self._operator == self.OPERATOR_AND:
|
||||
return all(evaluated)
|
||||
elif self._operator == self.OPERATOR_OR:
|
||||
return any(evaluated)
|
||||
elif self._operator == self.OPERATOR_XOR:
|
||||
result = evaluated[0]
|
||||
for v in evaluated[1:]:
|
||||
result ^= v
|
||||
return result
|
||||
elif self._operator == self.OPERATOR_INVERT:
|
||||
return not evaluated[0]
|
||||
return False
|
||||
197
src/mab/filters/body.py
Normal file
197
src/mab/filters/body.py
Normal file
@@ -0,0 +1,197 @@
|
||||
import re
|
||||
import traceback
|
||||
from .message import NewMessageFilter
|
||||
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
from ..context.vars.command import CTX_COMMAND, Command
|
||||
|
||||
class BodyExistsFilter(NewMessageFilter):
|
||||
"""
|
||||
This filter returns True if all conditions are met:
|
||||
1. `event` has attribute `body`
|
||||
2. `event.body` is an instance of `str`
|
||||
3. `event.body.strip()` evaluates to True
|
||||
|
||||
If `event.body` value equals to filename (if it is present, of course) then
|
||||
this filter will return False by default. You may disable
|
||||
`ignore_filename_in_body` to disable this feature.
|
||||
|
||||
This filter will match any message that has `body` in it, including images,
|
||||
videos, files, etc.
|
||||
"""
|
||||
def __init__(self, *, ignore_filename_in_body: bool = True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self._ignore_filename_in_body = ignore_filename_in_body
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
if not hasattr(ctx.event, "body"):
|
||||
return False
|
||||
if not isinstance(ctx.event.body, str): # type: ignore
|
||||
return False
|
||||
if not ctx.event.body.strip(): # type: ignore
|
||||
return False
|
||||
if self._ignore_filename_in_body:
|
||||
content = ctx.event.source["content"]
|
||||
if "filename" in content and content["filename"] == ctx.event.body: # type: ignore
|
||||
return False
|
||||
return True
|
||||
|
||||
class BodyContainsFilter(BodyExistsFilter):
|
||||
"""
|
||||
This filter returns True if `event.body` contains `needle` substring (or any
|
||||
of neddle from the list). `event.body` will be converted to lower case if
|
||||
`any_case` is True.
|
||||
|
||||
`needle` list is stored by reference so you can dynamically edit behavior of
|
||||
this filter.
|
||||
|
||||
Please note that only `event.body` is converted to lower case if `any_case`
|
||||
is True. That means you must ensure that `needle` is lower case. The filter
|
||||
will never match otherwise.
|
||||
"""
|
||||
def __init__(self, needle: str | list[str], *, any_case: bool = True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if type(needle) is str:
|
||||
needle = [needle]
|
||||
self._any_case = any_case
|
||||
self._needle = needle
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
body = ctx.event.body.lower() if self._any_case else ctx.event.body # type: ignore
|
||||
for n in self._needle:
|
||||
if n in body:
|
||||
return True
|
||||
return False
|
||||
|
||||
class BodyStartsWithFilter(BodyExistsFilter):
|
||||
"""
|
||||
This filter returns True if `event.body` starts with `substring` (or any of
|
||||
substrings from the list). The check will be case insensetive if `any_case`
|
||||
is True.
|
||||
|
||||
`substring` list is stored by reference so you can dynamically edit behavior
|
||||
of this filter.
|
||||
|
||||
Please note that only `event.body` is converted to lower case if `any_case`
|
||||
is True. That means you must ensure that `needle` is lower case. The filter
|
||||
will never match otherwise.
|
||||
"""
|
||||
def __init__(self, substring: str | list[str], *, any_case: bool = True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if type(substring) is str:
|
||||
substring = [substring]
|
||||
self._any_case = any_case
|
||||
self._substring = substring
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
body = ctx.event.body.lower() if self._any_case else ctx.event.body # type: ignore
|
||||
for s in self._substring:
|
||||
if body.startswith(s):
|
||||
return True
|
||||
return False
|
||||
|
||||
class BodyEndsWithFilter(BodyExistsFilter):
|
||||
"""
|
||||
This filter returns True if `event.body` ends with `substring` (or any of
|
||||
substrings from the list). The check will be case insensetive if `any_case`
|
||||
is True.
|
||||
|
||||
`substring` list is stored by reference so you can dynamically edit behavior
|
||||
of this filter.
|
||||
|
||||
Please note that only `event.body` is converted to lower case if `any_case`
|
||||
is True. That means you must ensure that `needle` is lower case. The filter
|
||||
will never match otherwise.
|
||||
"""
|
||||
def __init__(self, substring: str | list[str], *, any_case: bool = True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if type(substring) is str:
|
||||
substring = [substring]
|
||||
self._any_case = any_case
|
||||
self._substring = substring
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
body = ctx.event.body.lower() if self._any_case else ctx.event.body # type: ignore
|
||||
for s in self._substring:
|
||||
if body.endswith(s):
|
||||
return True
|
||||
return False
|
||||
|
||||
class BodyCommandFilter(BodyExistsFilter):
|
||||
"""
|
||||
This filter returns True if all conditions are met:
|
||||
1. `event.body` contains at least `min_args + 1` words after split()
|
||||
2. `event.body` contains at most `max_args + 1` words after split()
|
||||
3. First element of splitted `event.body` starts with `prefix`
|
||||
4. First element of splitted `event.body` (after lstripping `prefix`) starts
|
||||
with any of strings in `verbs` list
|
||||
|
||||
`verbs` list is stored by reference so you can dynamically edit behavior of
|
||||
this filter.
|
||||
|
||||
Please note that prefix is checked case sensetively. However, event.body is
|
||||
converted to lower case when `verbs` matching is performed. So you must
|
||||
store all verbs in lower case. This filter will not match any verbs that
|
||||
use mixed case of upper case.
|
||||
|
||||
This filter sets CTX_COMMAND context variable if it returns True.
|
||||
"""
|
||||
def __init__(self, verbs: str | list[str], min_args: int = 0, max_args: int | None = None, prefix: str = "!", **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if type(verbs) is str:
|
||||
verbs = [verbs]
|
||||
self._verbs = verbs
|
||||
self._min_args = min_args
|
||||
self._max_args = max_args
|
||||
self._prefix = prefix
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
parts = [p.strip() for p in ctx.event.body.split() if p.strip()] # type: ignore
|
||||
args_count = len(parts) - 1
|
||||
if args_count < self._min_args:
|
||||
return False
|
||||
if self._max_args is not None and args_count > self._max_args:
|
||||
return False
|
||||
if not parts[0].startswith(self._prefix):
|
||||
return False
|
||||
cmd = parts[0][len(self._prefix):].lower()
|
||||
for verb in self._verbs:
|
||||
if cmd == verb:
|
||||
vars[CTX_COMMAND] = Command(
|
||||
prefix=self._prefix,
|
||||
verb=cmd,
|
||||
args=parts[1:]
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
class BodyRegexFilter(BodyExistsFilter):
|
||||
"""
|
||||
This filter returns True if the `event.body` passes the regex.
|
||||
"""
|
||||
def __init__(self, regex: re.Pattern | str, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if isinstance(regex, str):
|
||||
regex = re.compile(regex)
|
||||
self._regex = regex
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
try:
|
||||
return self._regex.match(ctx.event.body) is not None # type: ignore
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
return False
|
||||
160
src/mab/filters/message.py
Normal file
160
src/mab/filters/message.py
Normal file
@@ -0,0 +1,160 @@
|
||||
import traceback
|
||||
from .base import BaseEventFilter, EventTypeFilter
|
||||
from ..types import MessageType
|
||||
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
from nio import RedactionEvent, ReactionEvent
|
||||
|
||||
class MessageTypeFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter should be used to match specific message types (text-only,
|
||||
images, videos, files, etc) based on `event.source["content"]["msgtype"]`
|
||||
value.
|
||||
|
||||
`types` list is copied so you can't modify behavior of this filter
|
||||
dynamically.
|
||||
"""
|
||||
def __init__(self, types: list[MessageType | str] | MessageType | str, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if not isinstance(types, list):
|
||||
types = [types]
|
||||
self._types: list[str] = []
|
||||
for t in types:
|
||||
self._types.append(t.value if isinstance(t, MessageType) else t)
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
if "msgtype" not in ctx.event.source["content"]:
|
||||
return False
|
||||
msgtype = ctx.event.source["content"]["msgtype"]
|
||||
return msgtype in self._types
|
||||
|
||||
class NewMessageFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter returns True if the event is a new message. Most filters are
|
||||
derived from this base class because it ignores events about edited
|
||||
messages.
|
||||
"""
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return "m.new_content" not in ctx.event.source["content"]
|
||||
|
||||
class EditedMessageFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter returns True if the event is an edited message. You may use this
|
||||
filter to create callbacks that are called if the message gets edited.
|
||||
"""
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return "m.new_content" in ctx.event.source["content"]
|
||||
|
||||
class RedactedMessageFilter(EventTypeFilter):
|
||||
"""
|
||||
This filter returns True if the event is a RedactionEvent.
|
||||
"""
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(RedactionEvent, **kwargs)
|
||||
raise NotImplementedError()
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
raise NotImplementedError()
|
||||
|
||||
class SenderIsFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter returns True if `event.sender` is any of specified senders.
|
||||
`event.sender` is converted to lower case if `any_case` is True (default).
|
||||
Supplied sender list is NEVER converted to lower case, so it is your duty to
|
||||
use lower case if `any_case` is True.
|
||||
|
||||
`senders` list is stored by reference so you can modify behavior of this
|
||||
filter dynamically.
|
||||
"""
|
||||
def __init__(self, sender: list[str] | str, *, any_case: bool = True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if isinstance(sender, str):
|
||||
sender = [sender]
|
||||
self._sender = sender
|
||||
self._any_case = any_case
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
sender = ctx.event.sender.lower() if self._any_case else ctx.event.sender
|
||||
for s in self._sender:
|
||||
if sender == s:
|
||||
return True
|
||||
return False
|
||||
|
||||
class SenderIsBotFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter returns True if `event.sender` is the client that has received
|
||||
the event. You may use this filter to set callbacks for messages sent by
|
||||
other users by using the following syntax:
|
||||
```py
|
||||
~SenderIsBotFilter()
|
||||
```
|
||||
"""
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return ctx.bot.client.user_id == ctx.event.sender
|
||||
|
||||
class MessageHasFileFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter returns True if the message contains file that can be
|
||||
downloaded.
|
||||
"""
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
content: dict | None = ctx.event.source.get("content")
|
||||
if content is None:
|
||||
return False
|
||||
# `file` if encrypted, `url` if not encrypted
|
||||
if "file" not in content and "url" not in content:
|
||||
return False
|
||||
return True
|
||||
|
||||
class MessageReactionFilter(EventTypeFilter):
|
||||
"""
|
||||
This filter returns True if the event is a new reaction added to the
|
||||
message. Additionals checks are supported if you pass `sender` and
|
||||
`reaction` when initializing the filter. They are checked case-sensetively
|
||||
and stored by reference so you may modify behavior of this filter
|
||||
dynamically.
|
||||
"""
|
||||
def __init__(self, *, sender: list[str] | str = [], reaction: list[str] | str = [], **kwargs):
|
||||
super().__init__(ReactionEvent, **kwargs)
|
||||
if isinstance(sender, str):
|
||||
sender = [sender]
|
||||
if isinstance(reaction, str):
|
||||
reaction = [reaction]
|
||||
self._sender = sender
|
||||
self._reaction = reaction
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
sender = ctx.event.sender
|
||||
if self._sender and sender not in self._sender:
|
||||
return False
|
||||
if self._reaction and ctx.event.key not in self._reaction: # type: ignore
|
||||
return False
|
||||
return True
|
||||
19
src/mab/filters/room.py
Normal file
19
src/mab/filters/room.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from .base import BaseEventFilter
|
||||
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
class RoomEncryptedFilter(BaseEventFilter):
|
||||
"""
|
||||
This filter returns True if the room is encrypted.
|
||||
"""
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
try:
|
||||
return ctx.room.encrypted
|
||||
except:
|
||||
return False
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
from pathlib import Path
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
from nio import UploadResponse
|
||||
|
||||
@dataclass
|
||||
class MatrixBotConfig:
|
||||
@@ -13,11 +16,70 @@ class MatrixBotConfig:
|
||||
matrix_username_localpart: str
|
||||
"""Localpart of matrix username (without homeserver), for example: `valid-username`"""
|
||||
|
||||
storage_directory: Path
|
||||
storage_directory: Path | str
|
||||
"""Path to the storage directory (will be created if needed)"""
|
||||
|
||||
auto_verify_all_known_devices: bool = True
|
||||
"""Enable automatic verification of all known devices on related errors"""
|
||||
|
||||
auto_join_any_room_on_invite: bool = True
|
||||
"""Enable automatic join for invites (implemented by automatically adding internal callback on bot creation)"""
|
||||
"""Enable automatic join for invites (implemented by automatically adding internal callback on bot creation)"""
|
||||
|
||||
auto_ffprobe: bool = True
|
||||
"""Enable automatic `ffprobe` execution to get some media properties"""
|
||||
|
||||
auto_ffmpeg: bool = True
|
||||
"""Enabled automatic `ffmpeg` execution to generate some media (e.g. thumbnails)"""
|
||||
|
||||
client_sync_period_ms: int = 5000
|
||||
"""Sync period for `nio.AsyncClient` in milliseconds"""
|
||||
|
||||
client_next_batch_dump_period_s: float = 120.0
|
||||
"""`next_batch` value dumping period in seconds"""
|
||||
|
||||
enable_multitasking_callbacks: bool = True
|
||||
"""Filter-based callbacks will be started each in separate task so that
|
||||
long callback execution will not prevent other callbacks from executting
|
||||
"""
|
||||
|
||||
@dataclass
|
||||
class VideoFileProperties:
|
||||
"""Properties of the video for sending"""
|
||||
|
||||
width_px: int
|
||||
"""Width in pixels"""
|
||||
|
||||
height_px: int
|
||||
"""Height in pixels"""
|
||||
|
||||
duration_ms: int
|
||||
"""Duration in milliseconds"""
|
||||
|
||||
thumbnail: Path | str | bytes | None = None
|
||||
"""Path to the thumbnail or the raw JPEG thumbnail data"""
|
||||
|
||||
@dataclass
|
||||
class UploadResult:
|
||||
"""Result of data upload"""
|
||||
|
||||
response: UploadResponse
|
||||
"""Response, as returned by `AsyncClient.upload(...)`"""
|
||||
|
||||
keys: dict
|
||||
"""Encryptions keys, as returned by `AsyncClient.upload(...)`"""
|
||||
|
||||
filename: str
|
||||
"""Name of the uploaded file"""
|
||||
|
||||
filesize: int
|
||||
"""Size of uploaded file"""
|
||||
|
||||
class MessageType(Enum):
|
||||
TEXT = "m.text"
|
||||
EMOTE = "m.emote"
|
||||
NOTICE = "m.notice"
|
||||
IMAGE = "m.image"
|
||||
FILE = "m.file"
|
||||
AUDIO = "m.audio"
|
||||
LOCATION = "m.location"
|
||||
VIDEO = "m.video"
|
||||
|
||||
133
src/mab/utils.py
Normal file
133
src/mab/utils.py
Normal file
@@ -0,0 +1,133 @@
|
||||
"""Utility things"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from nio import AsyncClient
|
||||
|
||||
from .types import *
|
||||
|
||||
class Utils:
|
||||
@staticmethod
|
||||
async def get_video_props_using_ffprobe(path: Path | str) -> VideoFileProperties:
|
||||
"""Returns video properties for file at `path`.
|
||||
|
||||
Consider using `asyncio.timeout` to prevent deadlocking.
|
||||
"""
|
||||
# prepare arguments for ffprobe
|
||||
args = [
|
||||
"ffprobe",
|
||||
"-v", "error",
|
||||
"-select_streams", "v:0",
|
||||
"-show_entries", "stream=width,height:format=duration",
|
||||
"-of", "json",
|
||||
str(path)
|
||||
]
|
||||
# start the process
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
# communicate `stdout` and `stderr`
|
||||
try:
|
||||
stdout, stderr = await proc.communicate()
|
||||
except asyncio.CancelledError:
|
||||
if proc.returncode is None:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
raise
|
||||
# error
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"`ffprobe` exits with code {proc.returncode}: {stderr.decode(errors="replace")}")
|
||||
# success
|
||||
result = json.loads(stdout)
|
||||
return VideoFileProperties(
|
||||
width_px=int(result["streams"][0]["width"]),
|
||||
height_px=int(result["streams"][0]["height"]),
|
||||
duration_ms=int(float(result["format"]["duration"]) * 1000)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def get_video_thumbnail(path: Path | str, *, timestamp: float = 0, max_size: int = 300) -> bytes:
|
||||
"""Generates video thumbnail for file at `path`.
|
||||
|
||||
Args:
|
||||
- path - path to the video
|
||||
- timestamp - timestamp to use as the thumbnail
|
||||
- max_size - max width/height
|
||||
|
||||
Returns:
|
||||
Raw bytes of JPEG thumbnail
|
||||
"""
|
||||
# prepare arguments for ffmpeg
|
||||
args = [
|
||||
"ffmpeg",
|
||||
"-v", "error",
|
||||
"-ss", "%.2f" % timestamp,
|
||||
"-i", str(path),
|
||||
"-map", "0:v:0",
|
||||
"-vf",
|
||||
(
|
||||
f"scale='min(iw,{max_size})':'min(ih,{max_size})':"
|
||||
"force_original_aspect_ratio=decrease"
|
||||
),
|
||||
"-frames:v", "1",
|
||||
"-q:v", "3",
|
||||
"-f", "image2pipe",
|
||||
"-vcodec", "mjpeg",
|
||||
"pipe:1"
|
||||
]
|
||||
# start the process
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*args,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
# communicate `stdout` and `stderr`
|
||||
try:
|
||||
stdout, stderr = await proc.communicate()
|
||||
except asyncio.CancelledError:
|
||||
if proc.returncode is None:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
raise
|
||||
# error
|
||||
if proc.returncode != 0 or not stdout:
|
||||
raise RuntimeError(f"`ffmpeg` exits with code {proc.returncode}: {stderr.decode(errors="replace")}", args)
|
||||
# success
|
||||
return stdout
|
||||
|
||||
@staticmethod
|
||||
def build_full_matrix_username(config: MatrixBotConfig) -> str:
|
||||
"""Build complete matrix username using data from MatrixBotConfig."""
|
||||
homeserver_name = urlparse(config.matrix_homeserver_url).hostname
|
||||
localpart = config.matrix_username_localpart
|
||||
return f"@{localpart}:{homeserver_name}"
|
||||
|
||||
@staticmethod
|
||||
def verify_all_known_devices(client: AsyncClient) -> bool:
|
||||
"""
|
||||
Verify all known devices.
|
||||
|
||||
Args:
|
||||
- client - client to verify all known devices for
|
||||
|
||||
Returns:
|
||||
- True if there were unverified devices that are verified now
|
||||
"""
|
||||
result = False
|
||||
for user_id in client.device_store.users:
|
||||
for device_id, olm_device in client.device_store[user_id].items():
|
||||
# can't trust ourselves
|
||||
if device_id == client.device_id and user_id == client.user_id:
|
||||
continue
|
||||
# they are already verified
|
||||
if olm_device.verified:
|
||||
continue
|
||||
# verify them
|
||||
client.verify_device(olm_device)
|
||||
result = True
|
||||
return result
|
||||
Reference in New Issue
Block a user