Compare commits
15 Commits
v0.5.0
...
d758bdedac
| Author | SHA1 | Date | |
|---|---|---|---|
| d758bdedac | |||
| b5210359b1 | |||
| ada7af9dd6 | |||
| d5367ebc6b | |||
| eacb0c0d25 | |||
| 33efd5e104 | |||
| 17031500e9 | |||
| afcd3f53f4 | |||
| b22e7b4903 | |||
| 2867582c01 | |||
| 16b849ebd8 | |||
| 35bd68516a | |||
| 86257a70e3 | |||
| 43b5d8e3a6 | |||
| 0e9b621895 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -6,3 +6,4 @@ dist/
|
||||
*.egg-info/
|
||||
*.swp
|
||||
*.swo
|
||||
*.tmp
|
||||
12
README.md
12
README.md
@@ -4,11 +4,17 @@
|
||||
develop **very** simple Matrix bots. It does not aim to be the best library out
|
||||
there, but it aims to be convenient and usable for relatively serious projects.
|
||||
|
||||
>[!NOTE]
|
||||
> Latest *"stable"* version is `v0.6.1`. Next version tag will be set when the
|
||||
> library will become more usable and more stable. Upcoming version is `v0.7.0`.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
The library supports the following features:
|
||||
- **Completely `asyncio` based**
|
||||
- **Filter-based callback system**
|
||||
- **Downloading and transparently decrypting files**
|
||||
- **Sending files**
|
||||
- **Sending images**
|
||||
- **Sending videos with automatic thumbnail generation (requires `ffmpeg`)**
|
||||
|
||||
@@ -17,17 +23,17 @@ The library supports the following features:
|
||||
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 version of the library:
|
||||
install the latest stable version of the library:
|
||||
|
||||
```bash
|
||||
apt install libmagic1-dev libolm-dev
|
||||
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.5.0
|
||||
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.6.1
|
||||
```
|
||||
|
||||
`libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
|
||||
is needed for E2EE to work.
|
||||
|
||||
Please inspect [`examples/image_gen_bot.py`](examples/image_gen_bot.py),
|
||||
Please inspect [`examples/image_bot.py`](examples/image_bot.py),
|
||||
[`examples/echo_bot.py`](examples/echo_bot.py) or open [`examples/`](examples/)
|
||||
directory to find usage examples. Examples require that you set
|
||||
`MATRIX_HOMESERVER` and `MATRIX_USERNAME` environment variables. Examples create
|
||||
|
||||
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
|
||||
@@ -16,7 +16,7 @@ from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_help_command(ctx: EventContext) -> None:
|
||||
async def on_help_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!help"""
|
||||
HELP_MESSAGE = (
|
||||
"<strong>Here is the list of the commands:</strong><br>"
|
||||
@@ -29,69 +29,69 @@ async def on_help_command(ctx: EventContext) -> None:
|
||||
"<li><code>!args arg1 [arg2] ... [arg5]</code> - command that takes 1..5 arguments</li>"
|
||||
"</ul>"
|
||||
)
|
||||
await ctx.bot.send_text(ctx.room, HELP_MESSAGE)
|
||||
await ctx.bot.send.text(ctx.room, HELP_MESSAGE)
|
||||
|
||||
async def on_time_command(ctx: EventContext) -> None:
|
||||
async def on_time_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!time"""
|
||||
await ctx.bot.send_text(
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
f"Current UNIX timestamp is <strong>{int(time.time())}</strong>"
|
||||
)
|
||||
|
||||
async def on_raise_command(ctx: EventContext) -> None:
|
||||
async def on_raise_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!raise"""
|
||||
await ctx.bot.send_text(
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"<strong>Executing <code>raise RuntimeError()</code>...</strong>"
|
||||
)
|
||||
raise RuntimeError()
|
||||
|
||||
async def on_assert_command(ctx: EventContext) -> None:
|
||||
async def on_assert_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!assert"""
|
||||
await ctx.bot.send_text(
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"<strong>Executing <code>assert False</code>...</strong>"
|
||||
)
|
||||
assert False
|
||||
|
||||
async def on_mul_command(ctx: EventContext) -> None:
|
||||
async def on_mul_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!mul"""
|
||||
try:
|
||||
numbers = [float(v) for v in ctx[CTX_CMD_ARGS]]
|
||||
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)
|
||||
await ctx.bot.send.text(ctx.room, response)
|
||||
except Exception as e:
|
||||
await ctx.bot.send_text(ctx.room, f"Could not process the command: {e}")
|
||||
await ctx.bot.send.text(ctx.room, f"Could not process the command: {e}")
|
||||
|
||||
async def on_args_command(ctx: EventContext) -> None:
|
||||
async def on_args_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""!args"""
|
||||
try:
|
||||
response = (
|
||||
f"Prefix: <code>{ctx[CTX_CMD_PREFIX]}</code><br>"
|
||||
f"Verb: <code>{ctx[CTX_CMD_VERB]}</code><br>"
|
||||
f"Arguments: <code>{len(ctx[CTX_CMD_ARGS])}</code><br>"
|
||||
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 ctx[CTX_CMD_ARGS]:
|
||||
for arg in vars[CTX_COMMAND].args:
|
||||
response += f"<li><code>{html.escape(arg)}</code></li>"
|
||||
response += "</ol>"
|
||||
await ctx.bot.send_text(
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
response
|
||||
)
|
||||
except:
|
||||
await ctx.bot.send_text(
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
f"Could not process the command: {traceback.format_exc()}"
|
||||
)
|
||||
|
||||
async def invalid_usage(ctx: EventContext) -> None:
|
||||
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>")
|
||||
await ctx.bot.send.text(ctx.room, "Use <code>!help</code>")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
|
||||
@@ -13,9 +13,9 @@ from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_text_message(ctx: EventContext) -> None:
|
||||
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, ctx[CTX_BODY])
|
||||
await ctx.bot.send.text(ctx.room, vars[CTX_MESSAGE].body)
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
|
||||
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["MATRIX_HOMESERVER"],
|
||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
||||
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())
|
||||
@@ -9,23 +9,24 @@ the bot.
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import os
|
||||
import time
|
||||
import logging
|
||||
import random
|
||||
from PIL import Image
|
||||
from PIL import Image, ImageFilter
|
||||
|
||||
from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_gen_command(data: EventContext) -> None:
|
||||
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(v) for v in data[CTX_CMD_ARGS]]
|
||||
r, g, b = [float(f) for f in vars[CTX_COMMAND].args]
|
||||
except:
|
||||
await data.bot.send_text(data.room, "Invalid arguments")
|
||||
await ctx.bot.send.text(ctx.room, "Invalid arguments")
|
||||
return
|
||||
await data.bot.send_text(data.room, "Generating the noise...")
|
||||
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):
|
||||
@@ -43,13 +44,40 @@ async def on_gen_command(data: EventContext) -> None:
|
||||
buf.seek(0)
|
||||
buf = buf.read()
|
||||
# send
|
||||
await data.bot.send_image_bytes(data.room, buf, "noise.png")
|
||||
await ctx.bot.send.image_bytes(ctx.room, buf, "noise.png")
|
||||
|
||||
async def on_wrong_message(data: EventContext) -> None:
|
||||
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 data.bot.send_text(
|
||||
data.room,
|
||||
"Text me something like <code>!gen 0.1 0.7 1.0</code>"
|
||||
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"
|
||||
)
|
||||
|
||||
async def main() -> None:
|
||||
@@ -77,11 +105,17 @@ async def main() -> None:
|
||||
~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. do NOT match the command filter
|
||||
# 2. are new messages (not edits)
|
||||
bot.add_callback(
|
||||
~SenderIsBotFilter() & ~command_filter,
|
||||
~SenderIsBotFilter() & BodyExistsFilter() & NewMessageFilter(),
|
||||
on_wrong_message
|
||||
)
|
||||
|
||||
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, is_html=False)
|
||||
|
||||
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["MATRIX_HOMESERVER"],
|
||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
||||
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(),
|
||||
on_help_message
|
||||
)
|
||||
|
||||
# run until Ctrl+C
|
||||
try:
|
||||
await bot.run()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "mab"
|
||||
version = "0.5.0"
|
||||
version = "0.7.0"
|
||||
authors = [
|
||||
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
|
||||
]
|
||||
|
||||
@@ -1,53 +1,15 @@
|
||||
from . import bot
|
||||
from . import types
|
||||
|
||||
from .types import MatrixBotConfig, MessageType
|
||||
from .context import *
|
||||
|
||||
# Bot and its config types
|
||||
from .bot import MatrixBot
|
||||
from .types import MatrixBotConfig
|
||||
|
||||
from .filters.base import *
|
||||
from .filters.message import *
|
||||
from .filters.body import *
|
||||
# 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",
|
||||
"MessageType",
|
||||
|
||||
# .context
|
||||
"EventContext",
|
||||
"CTX_BODY",
|
||||
"CTX_MESSAGE_TYPE",
|
||||
"CTX_SENDER",
|
||||
"CTX_CMD_PREFIX",
|
||||
"CTX_CMD_VERB",
|
||||
"CTX_CMD_ARGS",
|
||||
|
||||
# .bot
|
||||
"MatrixBot",
|
||||
|
||||
# .filters.base
|
||||
"BaseEventFilter",
|
||||
"EventTypeFilter",
|
||||
|
||||
# .filters.body
|
||||
"BodyExistsFilter",
|
||||
"BodyContainsFilter",
|
||||
"BodyStartsWithFilter",
|
||||
"BodyEndsWithFilter",
|
||||
"BodyCommandFilter",
|
||||
"BodyRegexFilter",
|
||||
|
||||
# .filters.message
|
||||
"MessageTypeFilter",
|
||||
"NewMessageFilter",
|
||||
"EditedMessageFilter",
|
||||
"RedactedMessageFilter",
|
||||
"SenderIsFilter",
|
||||
"SenderIsBotFilter",
|
||||
]
|
||||
# Context variables
|
||||
from .context.vars.command import *
|
||||
from .context.vars.message import *
|
||||
from .context.vars.room_event import *
|
||||
@@ -12,6 +12,7 @@ from nio.events.room_events import Event as RoomEvent
|
||||
from ._storage import Storage
|
||||
from ..types import MatrixBotConfig
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars, ContextVarsPopulator
|
||||
from ..filters.base import BaseEventFilter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -32,7 +33,7 @@ class Callbacks:
|
||||
filter: BaseEventFilter
|
||||
"""Filter to use for matching"""
|
||||
|
||||
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None
|
||||
"""Callback that will be called if the filter matches"""
|
||||
|
||||
stop_matching: bool
|
||||
@@ -49,16 +50,23 @@ class Callbacks:
|
||||
"""
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("Callbacks were not set up")
|
||||
# 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
|
||||
event_data = EventContext(
|
||||
room=room,
|
||||
event=event,
|
||||
bot=self._matrix_bot
|
||||
)
|
||||
local_event_vars = ContextVars()
|
||||
try:
|
||||
if not await callback_info.filter(event_data):
|
||||
if not await callback_info.filter(event_context, local_event_vars):
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
@@ -70,12 +78,15 @@ class Callbacks:
|
||||
if callback_info.callback is None:
|
||||
self._logger.critical(
|
||||
f"Filter {repr(callback_info.filter)} has no callback. "
|
||||
f"`room` type is `{type(event_data.room)}`. "
|
||||
f"`event` type is `{type(event_data.event)}`."
|
||||
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_data)
|
||||
cor = callback_info.callback(
|
||||
event_context,
|
||||
event_vars + local_event_vars
|
||||
)
|
||||
# multitasking
|
||||
if self._config.enable_multitasking_callbacks:
|
||||
t = asyncio.create_task(cor)
|
||||
@@ -135,6 +146,7 @@ class Callbacks:
|
||||
self._logger = logging.getLogger("Callbacks")
|
||||
self._storage = storage
|
||||
self._matrix_bot = matrix_bot
|
||||
self._context_vars_populator = ContextVarsPopulator()
|
||||
|
||||
self._config: MatrixBotConfig | None = None
|
||||
self._client: AsyncClient | None = None
|
||||
@@ -144,7 +156,7 @@ class Callbacks:
|
||||
def add_room_event_callback(
|
||||
self,
|
||||
filter: BaseEventFilter,
|
||||
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None,
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
|
||||
*,
|
||||
stop_matching: bool = True) -> None:
|
||||
"""
|
||||
|
||||
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
|
||||
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
|
||||
@@ -98,9 +98,9 @@ class ClientSender:
|
||||
self._client = client
|
||||
self._uploader = uploader
|
||||
|
||||
async def send_content(self,
|
||||
room: MatrixRoom | str,
|
||||
content: dict) -> RoomSendResponse:
|
||||
async def content(self,
|
||||
room: MatrixRoom | str,
|
||||
content: dict) -> RoomSendResponse:
|
||||
"""
|
||||
Send raw `content` JSON to `room`.
|
||||
|
||||
@@ -124,7 +124,7 @@ class ClientSender:
|
||||
if self._config.auto_verify_all_known_devices:
|
||||
if not Utils.verify_all_known_devices(self._client):
|
||||
raise
|
||||
return await self.send_content(room, content)
|
||||
return await self.content(room, content)
|
||||
else:
|
||||
raise
|
||||
if type(result) is RoomSendResponse:
|
||||
@@ -134,11 +134,11 @@ class ClientSender:
|
||||
else:
|
||||
raise RuntimeError("Unknown error has occured", result)
|
||||
|
||||
async def send_text(self,
|
||||
room: MatrixRoom | str,
|
||||
text: str,
|
||||
*,
|
||||
is_html: bool | None = None) -> str:
|
||||
async def text(self,
|
||||
room: MatrixRoom | str,
|
||||
text: str,
|
||||
*,
|
||||
is_html: bool | None = None) -> str:
|
||||
"""
|
||||
Send text message to `room`.
|
||||
|
||||
@@ -156,15 +156,15 @@ class ClientSender:
|
||||
"msgtype": "m.text",
|
||||
**text_data
|
||||
}
|
||||
return (await self.send_content(room, content)).event_id
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def send_image(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str, *,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
filename: str | None = None,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
async def image(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str, *,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
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
|
||||
@@ -213,16 +213,16 @@ class ClientSender:
|
||||
"h": height
|
||||
}
|
||||
}
|
||||
return (await self.send_content(room, content)).event_id
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def send_image_bytes(self,
|
||||
room: MatrixRoom | str,
|
||||
data: bytes,
|
||||
filename: str,
|
||||
*,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
async def image_bytes(self,
|
||||
room: MatrixRoom | str,
|
||||
data: bytes,
|
||||
filename: str,
|
||||
*,
|
||||
text: str | None = None,
|
||||
is_html: bool | 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
|
||||
@@ -276,16 +276,16 @@ class ClientSender:
|
||||
"h": height
|
||||
}
|
||||
}
|
||||
return (await self.send_content(room, content)).event_id
|
||||
return (await self.content(room, content)).event_id
|
||||
|
||||
async def send_video(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str,
|
||||
*,
|
||||
props: VideoFileProperties | None = None,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
timeout: float | None = 60 * 60) -> str:
|
||||
async def video(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str,
|
||||
*,
|
||||
props: VideoFileProperties | None = None,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
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
|
||||
@@ -361,4 +361,123 @@ class ClientSender:
|
||||
}
|
||||
}
|
||||
# send
|
||||
return (await self.send_content(room, content)).event_id
|
||||
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 = None,
|
||||
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 = None,
|
||||
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
|
||||
@@ -1,17 +1,20 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from typing import Callable, Coroutine, Any
|
||||
from typing import Callable, Coroutine, Any, overload
|
||||
|
||||
from nio import AsyncClient, MatrixRoom
|
||||
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 ._storage import Storage
|
||||
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
|
||||
@@ -33,6 +36,8 @@ class MatrixBot:
|
||||
self._client_auth = ClientAuth(self._storage)
|
||||
self._client_manager = ClientManager(self._client_auth, self._storage)
|
||||
self._client_uploader = ClientUploader(self._storage)
|
||||
self._client_downloader = ClientDownloader()
|
||||
self._client_room_operations = ClientRoomOperations()
|
||||
self._client_sender = ClientSender()
|
||||
self._callbacks = Callbacks(self._storage, self)
|
||||
# validate the config and save it
|
||||
@@ -45,7 +50,7 @@ class MatrixBot:
|
||||
|
||||
def add_callback(self,
|
||||
filter: BaseEventFilter,
|
||||
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None,
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
|
||||
*,
|
||||
stop_matching: bool = True) -> None:
|
||||
"""
|
||||
@@ -80,6 +85,14 @@ class MatrixBot:
|
||||
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(),
|
||||
@@ -113,7 +126,8 @@ class MatrixBot:
|
||||
finally:
|
||||
await self.stop()
|
||||
|
||||
def get_client(self) -> AsyncClient:
|
||||
@property
|
||||
def client(self) -> AsyncClient:
|
||||
"""
|
||||
Get AsyncClient.
|
||||
|
||||
@@ -123,125 +137,19 @@ class MatrixBot:
|
||||
"""
|
||||
return self._client_manager.get_client()
|
||||
|
||||
async def send_text(self,
|
||||
room: MatrixRoom | str,
|
||||
text: str,
|
||||
*,
|
||||
is_html: bool | None = None) -> str:
|
||||
@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.
|
||||
"""
|
||||
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
|
||||
"""
|
||||
return await self._client_sender.send_text(
|
||||
room=room,
|
||||
text=text,
|
||||
is_html=is_html
|
||||
)
|
||||
|
||||
async def send_image(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str, *,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
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
|
||||
"""
|
||||
return await self._client_sender.send_image(
|
||||
room=room,
|
||||
path=path,
|
||||
text=text,
|
||||
is_html=is_html,
|
||||
filename=filename,
|
||||
timeout=timeout
|
||||
)
|
||||
|
||||
async def send_image_bytes(self,
|
||||
room: MatrixRoom | str,
|
||||
data: bytes,
|
||||
filename: str,
|
||||
*,
|
||||
text: str | None = None,
|
||||
is_html: bool | 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
|
||||
- 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
|
||||
"""
|
||||
return await self._client_sender.send_image_bytes(
|
||||
room=room,
|
||||
data=data,
|
||||
filename=filename,
|
||||
text=text,
|
||||
is_html=is_html,
|
||||
timeout=timeout
|
||||
)
|
||||
|
||||
async def send_video(self,
|
||||
room: MatrixRoom | str,
|
||||
path: Path | str,
|
||||
*,
|
||||
props: VideoFileProperties | None = None,
|
||||
text: str | None = None,
|
||||
is_html: bool | None = None,
|
||||
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
|
||||
"""
|
||||
return await self._client_sender.send_video(
|
||||
room=room,
|
||||
path=path,
|
||||
props=props,
|
||||
text=text,
|
||||
is_html=is_html,
|
||||
timeout=timeout
|
||||
)
|
||||
return self._client_room_operations
|
||||
@@ -1,79 +0,0 @@
|
||||
"""This module implements logic for event context"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from .types import ContextDataKey, MessageType
|
||||
|
||||
from nio import MatrixRoom, Event
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .bot import MatrixBot
|
||||
|
||||
#
|
||||
# Possible context variables
|
||||
#
|
||||
CTX_BODY = ContextDataKey[str]("CTX_BODY")
|
||||
"""Value of `event.body`"""
|
||||
|
||||
CTX_MESSAGE_TYPE = ContextDataKey[MessageType]("CTX_MESSAGE_TYPE")
|
||||
"""Value of `msgtype` for the event"""
|
||||
|
||||
CTX_SENDER = ContextDataKey[str]("CTX_SENDER")
|
||||
"""Value of `event.sender`"""
|
||||
|
||||
CTX_CMD_PREFIX = ContextDataKey[str]("CTX_CMD_PREFIX")
|
||||
"""Command prefix that was used when matching"""
|
||||
|
||||
CTX_CMD_VERB = ContextDataKey[str]("CTX_CMD_VERB")
|
||||
"""The verb that was used to execute the command"""
|
||||
|
||||
CTX_CMD_ARGS = ContextDataKey[list[str]]("CTX_CMD_ARGS")
|
||||
"""Arguments that were passed with the command"""
|
||||
|
||||
CTX_ROOM_ENCRYPTED = ContextDataKey[bool]("CTX_ROOM_ENCRYPTED")
|
||||
"""True if the room is encrypted"""
|
||||
|
||||
|
||||
#
|
||||
# EventContext implementation
|
||||
#
|
||||
@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"""
|
||||
|
||||
def __setitem__[T](self, key: ContextDataKey[T], value: T | None) -> None:
|
||||
"""Set a value inside the context data storage. `None` removes it"""
|
||||
if not hasattr(self, "_datastore"):
|
||||
self._datastore: dict[ContextDataKey, Any] = {}
|
||||
if value is None:
|
||||
del self._datastore[key]
|
||||
else:
|
||||
self._datastore[key] = value
|
||||
|
||||
def __getitem__[T](self, key: ContextDataKey[T]) -> T:
|
||||
"""
|
||||
Get a value inside the context data storage.
|
||||
|
||||
Raises RuntimeError if the value is not present.
|
||||
"""
|
||||
if not hasattr(self, "_datastore") or key not in self._datastore:
|
||||
raise RuntimeError(f"Context does not contain {repr(key)}")
|
||||
return self._datastore[key]
|
||||
|
||||
def __contains__[T](self, key: ContextDataKey[T]) -> bool:
|
||||
"""Check if context data storage contains the value"""
|
||||
if not hasattr(self, "_datastore"):
|
||||
return False
|
||||
if key not in self._datastore:
|
||||
return False
|
||||
return True
|
||||
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/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 *
|
||||
@@ -1,14 +1,12 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from abc import ABC
|
||||
import logging
|
||||
from typing import Any, Type
|
||||
|
||||
from nio import AsyncClient
|
||||
from nio import MatrixRoom, Event
|
||||
from typing import Type
|
||||
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
class BaseEventFilter(ABC):
|
||||
"""Base class for all message filters"""
|
||||
"""Base class for all message filters. Always returns True."""
|
||||
_logger = logging.Logger("EventFilter")
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
@@ -66,37 +64,37 @@ class BaseEventFilter(ABC):
|
||||
"""
|
||||
return str(self.__class__.__name__)
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
"""
|
||||
This abstract method must be redefined in derived classes so that the
|
||||
filter operates according to its description. This method must not raise
|
||||
exceptions. In case of exception it should log it using `self._logger`
|
||||
and return False
|
||||
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:
|
||||
- context - event context; your derived classes may add variables
|
||||
to it (see `message.MessageTypeFilter` implementation
|
||||
for reference)
|
||||
- ctx - context to filter
|
||||
- vars - variables object that may be modified by the filter
|
||||
|
||||
Returns:
|
||||
- True if the event satisfies this filter
|
||||
- False if the event does not satisfy this filter
|
||||
- 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"""
|
||||
"""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, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return isinstance(context.event, self._type)
|
||||
return isinstance(ctx.event, self._type)
|
||||
|
||||
class CompoundEventFilter(BaseEventFilter):
|
||||
"""Event filter that consists of multiple filters"""
|
||||
"""Event filter that consists of multiple filters."""
|
||||
OPERATOR_AND = "and"
|
||||
OPERATOR_OR = "or"
|
||||
OPERATOR_XOR = "xor"
|
||||
@@ -144,10 +142,10 @@ class CompoundEventFilter(BaseEventFilter):
|
||||
expression = f"~{reprs[0]}"
|
||||
return f"({expression})"
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
evaluated = [await arg(context) for arg in self._arguments]
|
||||
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:
|
||||
|
||||
@@ -1,54 +1,43 @@
|
||||
import re
|
||||
import traceback
|
||||
from .message import NewMessageFilter
|
||||
from ..context import EventContext
|
||||
from ..context import (
|
||||
CTX_BODY,
|
||||
CTX_CMD_PREFIX,
|
||||
CTX_CMD_VERB,
|
||||
CTX_CMD_ARGS
|
||||
)
|
||||
|
||||
from nio import AsyncClient
|
||||
from nio import MatrixRoom, Event
|
||||
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 instance of `str`
|
||||
2. `event.body` is an instance of `str`
|
||||
3. `event.body.strip()` evaluates to True
|
||||
|
||||
If this filter matches, you can access `event.body` and it stores
|
||||
unformatted text of the message.
|
||||
|
||||
If `event.body` value equals to `event.source["content"]["filename"]` (if it
|
||||
is present, of course) then this filter will not match it by default. You
|
||||
may disable `ignore_filename_in_body` to disable this feature.
|
||||
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.
|
||||
|
||||
This filter sets `CTX_BODY` context variable.
|
||||
"""
|
||||
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, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
if not hasattr(context.event, "body"):
|
||||
if not hasattr(ctx.event, "body"):
|
||||
return False
|
||||
if not isinstance(context.event.body, str): # type: ignore
|
||||
if not isinstance(ctx.event.body, str): # type: ignore
|
||||
return False
|
||||
if not context.event.body.strip(): # type: ignore
|
||||
if not ctx.event.body.strip(): # type: ignore
|
||||
return False
|
||||
if self._ignore_filename_in_body:
|
||||
content = context.event.source["content"]
|
||||
if "filename" in content and content["filename"] == context.event.body: # type: ignore
|
||||
content = ctx.event.source["content"]
|
||||
if "filename" in content and content["filename"] == ctx.event.body: # type: ignore
|
||||
return False
|
||||
context[CTX_BODY] = context.event.body # type: ignore
|
||||
return True
|
||||
|
||||
class BodyContainsFilter(BodyExistsFilter):
|
||||
@@ -71,10 +60,10 @@ class BodyContainsFilter(BodyExistsFilter):
|
||||
self._any_case = any_case
|
||||
self._needle = needle
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
body = context.event.body.lower() if self._any_case else context.event.body # type: ignore
|
||||
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
|
||||
@@ -100,10 +89,10 @@ class BodyStartsWithFilter(BodyExistsFilter):
|
||||
self._any_case = any_case
|
||||
self._substring = substring
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
body = context.event.body.lower() if self._any_case else context.event.body # type: ignore
|
||||
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
|
||||
@@ -129,10 +118,10 @@ class BodyEndsWithFilter(BodyExistsFilter):
|
||||
self._any_case = any_case
|
||||
self._substring = substring
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
body = context.event.body.lower() if self._any_case else context.event.body # type: ignore
|
||||
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
|
||||
@@ -155,10 +144,7 @@ class BodyCommandFilter(BodyExistsFilter):
|
||||
store all verbs in lower case. This filter will not match any verbs that
|
||||
use mixed case of upper case.
|
||||
|
||||
This filter sets the following context variables:
|
||||
- `CTX_CMD_PREFIX` - prefix that was used
|
||||
- `CTX_CMD_VERB` - verb that was used
|
||||
- `CTX_CMD_ARGS` - arguments that were passed
|
||||
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)
|
||||
@@ -169,10 +155,10 @@ class BodyCommandFilter(BodyExistsFilter):
|
||||
self._max_args = max_args
|
||||
self._prefix = prefix
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
parts = [p.strip() for p in context.event.body.split() if p.strip()] # type: ignore
|
||||
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
|
||||
@@ -183,9 +169,11 @@ class BodyCommandFilter(BodyExistsFilter):
|
||||
cmd = parts[0][len(self._prefix):].lower()
|
||||
for verb in self._verbs:
|
||||
if cmd == verb:
|
||||
context[CTX_CMD_PREFIX] = self._prefix
|
||||
context[CTX_CMD_VERB] = verb
|
||||
context[CTX_CMD_ARGS] = parts[1:]
|
||||
vars[CTX_COMMAND] = Command(
|
||||
prefix=self._prefix,
|
||||
verb=cmd,
|
||||
args=parts[1:]
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -199,11 +187,11 @@ class BodyRegexFilter(BodyExistsFilter):
|
||||
regex = re.compile(regex)
|
||||
self._regex = regex
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
try:
|
||||
return self._regex.match(context.event.body) is not None # type: ignore
|
||||
return self._regex.match(ctx.event.body) is not None # type: ignore
|
||||
except:
|
||||
self._logger.error(traceback.format_exc())
|
||||
return False
|
||||
@@ -1,10 +1,9 @@
|
||||
import traceback
|
||||
from .base import BaseEventFilter, EventTypeFilter
|
||||
from ..types import MessageType
|
||||
from ..context import EventContext, CTX_MESSAGE_TYPE, CTX_SENDER
|
||||
|
||||
from nio import AsyncClient
|
||||
from nio import MatrixRoom, Event
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
from nio import RedactionEvent
|
||||
|
||||
@@ -14,27 +13,24 @@ class MessageTypeFilter(BaseEventFilter):
|
||||
images, videos, files, etc) based on `event.source["content"]["msgtype"]`
|
||||
value.
|
||||
|
||||
`types` list is stored by reference so you may modify the behavior of this
|
||||
filter dynamically.
|
||||
|
||||
This filter sets `CTX_MESSAGE_TYPE` variable in the context.
|
||||
`types` list is copied so you can't modify behavior of this filter
|
||||
dynamically.
|
||||
"""
|
||||
def __init__(self, types: list[MessageType] | MessageType, **kwargs):
|
||||
def __init__(self, types: list[MessageType | str] | MessageType | str, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if isinstance(types, MessageType):
|
||||
if not isinstance(types, list):
|
||||
types = [types]
|
||||
self._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, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
if "msgtype" not in context.event.source["content"]:
|
||||
if "msgtype" not in ctx.event.source["content"]:
|
||||
return False
|
||||
msgtype = context.event.source["content"]["msgtype"]
|
||||
if not msgtype in [t.value for t in self._types]:
|
||||
return False
|
||||
context[CTX_MESSAGE_TYPE] = MessageType(msgtype)
|
||||
return True
|
||||
msgtype = ctx.event.source["content"]["msgtype"]
|
||||
return msgtype in self._types
|
||||
|
||||
class NewMessageFilter(BaseEventFilter):
|
||||
"""
|
||||
@@ -45,10 +41,10 @@ class NewMessageFilter(BaseEventFilter):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return "m.new_content" not in context.event.source["content"]
|
||||
return "m.new_content" not in ctx.event.source["content"]
|
||||
|
||||
class EditedMessageFilter(BaseEventFilter):
|
||||
"""
|
||||
@@ -58,10 +54,10 @@ class EditedMessageFilter(BaseEventFilter):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return "m.new_content" in context.event.source["content"]
|
||||
return "m.new_content" in ctx.event.source["content"]
|
||||
|
||||
class RedactedMessageFilter(EventTypeFilter):
|
||||
"""
|
||||
@@ -71,7 +67,7 @@ class RedactedMessageFilter(EventTypeFilter):
|
||||
super().__init__(RedactionEvent, **kwargs)
|
||||
raise NotImplementedError()
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
raise NotImplementedError()
|
||||
|
||||
class SenderIsFilter(BaseEventFilter):
|
||||
@@ -83,8 +79,6 @@ class SenderIsFilter(BaseEventFilter):
|
||||
|
||||
`senders` list is stored by reference so you can modify behavior of this
|
||||
filter dynamically.
|
||||
|
||||
This filter sets `CTX_SENDER` variable in the context.
|
||||
"""
|
||||
def __init__(self, sender: list[str] | str, *, any_case: bool = True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
@@ -93,13 +87,12 @@ class SenderIsFilter(BaseEventFilter):
|
||||
self._sender = sender
|
||||
self._any_case = any_case
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
sender = context.event.sender.lower() if self._any_case else context.event.sender
|
||||
sender = ctx.event.sender.lower() if self._any_case else ctx.event.sender
|
||||
for s in self._sender:
|
||||
if sender == s:
|
||||
context[CTX_SENDER] = sender
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -115,7 +108,26 @@ class SenderIsBotFilter(BaseEventFilter):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
return context.bot.get_client().user_id == context.event.sender
|
||||
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
|
||||
@@ -1,6 +1,7 @@
|
||||
from .base import BaseEventFilter
|
||||
|
||||
from ..context import EventContext, CTX_ROOM_ENCRYPTED
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
class RoomEncryptedFilter(BaseEventFilter):
|
||||
"""
|
||||
@@ -9,11 +10,10 @@ class RoomEncryptedFilter(BaseEventFilter):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
async def __call__(self, context: EventContext) -> bool:
|
||||
if not await super().__call__(context):
|
||||
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||
if not await super().__call__(ctx, vars):
|
||||
return False
|
||||
try:
|
||||
context[CTX_ROOM_ENCRYPTED] = context.room.encrypted
|
||||
return context.room.encrypted
|
||||
return ctx.room.encrypted
|
||||
except:
|
||||
return False
|
||||
@@ -86,20 +86,3 @@ class MessageType(Enum):
|
||||
AUDIO = "m.audio"
|
||||
LOCATION = "m.location"
|
||||
VIDEO = "m.video"
|
||||
|
||||
class ContextDataKey[T]:
|
||||
"""
|
||||
Instances of this class represent a single possible data key that can be
|
||||
stored inside EventContext.
|
||||
"""
|
||||
def __init__(self, name: str) -> None:
|
||||
"""
|
||||
Initialize a ContextDataKey
|
||||
|
||||
Args:
|
||||
- name - name that will be used internally
|
||||
"""
|
||||
self._name = name
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"ContextDataKey[{type(T)}]({repr(self._name)})"
|
||||
Reference in New Issue
Block a user