Compare commits
10 Commits
d758bdedac
...
v0.7.1
| Author | SHA1 | Date | |
|---|---|---|---|
| b99b2fa9bf | |||
| 86b1c6c142 | |||
| d442aa7322 | |||
| 2ace008068 | |||
| 3b929a1d88 | |||
| cbbafb7778 | |||
| eab2e8acb8 | |||
| 05a286b57a | |||
| 4b4c434bd8 | |||
| b7a471659d |
151
README.md
151
README.md
@@ -4,10 +4,6 @@
|
|||||||
develop **very** simple Matrix bots. It does not aim to be the best library out
|
develop **very** simple Matrix bots. It does not aim to be the best library out
|
||||||
there, but it aims to be convenient and usable for relatively serious projects.
|
there, but it aims to be convenient and usable for relatively serious projects.
|
||||||
|
|
||||||
>[!NOTE]
|
|
||||||
> Latest *"stable"* version is `v0.6.1`. Next version tag will be set when the
|
|
||||||
> library will become more usable and more stable. Upcoming version is `v0.7.0`.
|
|
||||||
|
|
||||||
## ✨ Features
|
## ✨ Features
|
||||||
|
|
||||||
The library supports the following features:
|
The library supports the following features:
|
||||||
@@ -27,77 +23,114 @@ install the latest stable version of the library:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
apt install libmagic1-dev libolm-dev
|
apt install libmagic1-dev libolm-dev
|
||||||
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.6.1
|
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.7.1
|
||||||
```
|
```
|
||||||
|
|
||||||
`libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
|
`libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
|
||||||
is needed for E2EE to work.
|
is needed for E2EE to work.
|
||||||
|
|
||||||
Please inspect [`examples/image_bot.py`](examples/image_bot.py),
|
Please refer to [examples](examples/) for some basic bots. Examples are the best
|
||||||
[`examples/echo_bot.py`](examples/echo_bot.py) or open [`examples/`](examples/)
|
introduction to this library. They are tested manually on each tagged commit.
|
||||||
directory to find usage examples. Examples require that you set
|
You need to set `MAB_SERVER`, `MAB_USER` and `MAB_PASSWORD` environment
|
||||||
`MATRIX_HOMESERVER` and `MATRIX_USERNAME` environment variables. Examples create
|
variables to pass server, username and password to the example.
|
||||||
`session_storage` directory in working directory.
|
|
||||||
|
| Variable | Example value |
|
||||||
|
|----------------|------------------------------|
|
||||||
|
| `MAB_SERVER` | `https://matrix.example.org` |
|
||||||
|
| `MAB_USER` | `localusername` |
|
||||||
|
| `MAB_PASSWORD` | `1337--w4-w1ll-r0ck-y0u!` |
|
||||||
|
|
||||||
## 🚀 Usage
|
## 🚀 Usage
|
||||||
|
|
||||||
If you use `mab`, your application will *most likely* be using **callbacks** to
|
The architecture of `mab` is quite primitive. You define your callback
|
||||||
react to user actions. `mab` uses filter-based callback system to avoid exposing
|
functions, you register them and you start the bot. When an event of interest
|
||||||
raw `nio-matrix` event objects.
|
happens your callback functions get called. That's it. However, some spices are
|
||||||
|
poured in to enhance the development experience a little bit.
|
||||||
|
|
||||||
This is the workflow you will most likely follow:
|
First of all, most encryption things are done transparently and automatically.
|
||||||
1. **Define the callback as `async` function that take 1 argument of type
|
The most important thing that is not provided by `matrix-nio` is automatic
|
||||||
`EventContext`.** For example, this callback would print the caption of the
|
**asynchronous** decryption of the files you download. You don't need to worry
|
||||||
message:
|
about it **at all** when you use `mab`.
|
||||||
```python
|
|
||||||
from mab import *
|
|
||||||
|
|
||||||
async def on_media_with_body(ctx: EventContext):
|
You need to create `MatrixBot` object to create a bot. This is the common way
|
||||||
"""To be called when a message with image/video and caption is received."""
|
of creating a bot:
|
||||||
print(ctx[CTX_BODY])
|
```python
|
||||||
```
|
import asyncio
|
||||||
2. **Define the conditions your callback must be called on.** For example, you
|
from mab import *
|
||||||
may want your callback to be called when `the sender is not the bot` and
|
|
||||||
`the message contains textual body` and (`the message is an image` or
|
|
||||||
`the message is a video`).
|
|
||||||
3. **Define the conditions as `filters`.** Most of them are pretty
|
|
||||||
straightforward. For example, if you want to use the conditions from above:
|
|
||||||
```python
|
|
||||||
from mab import *
|
|
||||||
|
|
||||||
filters = (
|
# Run until Ctrl+C
|
||||||
~SenderIsBotFilter()
|
async def main():
|
||||||
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO])
|
# Create the config for the bot object
|
||||||
& BodyExistsFilter()
|
bot_config = MatrixBotConfig(
|
||||||
)
|
matrix_homeserver_url="https://matrix.example.org",
|
||||||
```
|
matrix_username_localpart="username-here",
|
||||||
4. **Add the callback to your `MatrixBot` instance.** For example, if you would
|
storage_directory="session_storage"
|
||||||
have used everything from above, then your code would look something like
|
)
|
||||||
this:
|
# Create the bot itself
|
||||||
```python
|
bot = MatrixBot(bot_config)
|
||||||
from mab import *
|
# Add callbacks (use `None` instead of callback name to print debug info)
|
||||||
|
bot.add_callback(~SenderIsBotFilter(), None)
|
||||||
|
# Run until Ctrl+C
|
||||||
|
await bot.run()
|
||||||
|
|
||||||
# let's assume you create your MatrixBot as `bot` variable here
|
asyncio.run(main())
|
||||||
|
```
|
||||||
|
|
||||||
async def on_media_with_body(ctx: EventContext):
|
To reduce amount of `if`s in your code, **filters** concept is introduced. When
|
||||||
"""To be called when a message with image/video and caption is received."""
|
you add a callback to the instance of the bot, you also provide a filter object.
|
||||||
print(ctx[CTX_BODY])
|
Filters are created like that:
|
||||||
|
```python
|
||||||
|
# Filter that is True for new message
|
||||||
|
new_message = NewMessageFilter()
|
||||||
|
|
||||||
filters = (
|
# Filter that is True for message sent not by the user we are logged in as
|
||||||
~SenderIsBotFilter()
|
sent_by_user = ~SenderIsBotFilter()
|
||||||
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO])
|
|
||||||
& BodyExistsFilter()
|
|
||||||
)
|
|
||||||
bot.add_callback(filters, on_media_with_body)
|
|
||||||
|
|
||||||
...
|
# Filter that is True for users in `admins_list`
|
||||||
```
|
admins_list = [
|
||||||
|
"@server-admin:matrix.example.org",
|
||||||
|
"@bot-admin:matrix.example.org"
|
||||||
|
]
|
||||||
|
sent_by_admin = SenderIsFilter(admins_list)
|
||||||
|
|
||||||
Filters support bitwise operators to implement complex matching logic. Some
|
# Filter that is True for messages that have file attached to them
|
||||||
filters set context variables which can be accessed by
|
has_file = MessageHasFileFilter()
|
||||||
`context[CTX_KEY_NAME]`-like syntax. Possible variables are defined in
|
|
||||||
[this file](src/mab/context.py). Filters are implemented in
|
# Filter that is True for messages with nonempty body
|
||||||
[files of this directory](src/mab/filters/).
|
has_body = BodyExistsFilter()
|
||||||
|
```
|
||||||
|
|
||||||
|
In fact, you can't create usable bot with just these filters. You need to
|
||||||
|
combine them in different ways. So all filters support bitwise logical
|
||||||
|
operators on them. For example, if you'd like to create a filter for a callback
|
||||||
|
that must be called each time a different user adds a reaction to some message,
|
||||||
|
you'd write something like that:
|
||||||
|
```python
|
||||||
|
# Define the list of admins
|
||||||
|
admin_list = [
|
||||||
|
"@admin-ivan:matrix.example.org",
|
||||||
|
"@admin-vladimir:matrix.example.org"
|
||||||
|
]
|
||||||
|
# Define the filter
|
||||||
|
the_filter = (
|
||||||
|
MessageReactionFilter()
|
||||||
|
& ~SenderIsBotFilter()
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
The concept of **Context Variables** is introduced to avoid the usage of
|
||||||
|
*somewhat* complex `matrix-nio` objects. Context variables are key-value pairs
|
||||||
|
passed to your event callbacks. Think of them as *environment variables* passed
|
||||||
|
to programs.
|
||||||
|
|
||||||
|
**Here's an example of simple event callback implementation**
|
||||||
|
```python
|
||||||
|
async def simple_callback(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
|
await ctx.bot.send.text(
|
||||||
|
ctx.room,
|
||||||
|
f"You have said `{vars[CTX_MESSAGE].body}`!"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
## 🏷️ Versioning
|
## 🏷️ Versioning
|
||||||
|
|
||||||
|
|||||||
@@ -6,13 +6,9 @@ def check_environment() -> None:
|
|||||||
This function checks if required environment variables are set. It prints
|
This function checks if required environment variables are set. It prints
|
||||||
problem resolution guide and exits using `sys.exit(1)` on problem.
|
problem resolution guide and exits using `sys.exit(1)` on problem.
|
||||||
"""
|
"""
|
||||||
if "MATRIX_HOMESERVER" not in os.environ:
|
if "MAB_SERVER" not in os.environ:
|
||||||
print("Please set `MATRIX_HOMESERVER` environment variable!")
|
print("Please set `MAB_SERVER` environment variable!")
|
||||||
print("P.S. use something like this in your shell:")
|
|
||||||
print(" export MATRIX_HOMESERVER=\"https://matrix.server.net\"")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if "MATRIX_USERNAME" not in os.environ:
|
if "MAB_USER" not in os.environ:
|
||||||
print("Please set `MATRIX_USERNAME` environment variable!")
|
print("Please set `MAB_USER` environment variable!")
|
||||||
print("P.S. use something like this in your shell:")
|
|
||||||
print(" export MATRIX_USERNAME=\"megakiller228\"")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -29,20 +29,26 @@ async def on_help_command(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
"<li><code>!args arg1 [arg2] ... [arg5]</code> - command that takes 1..5 arguments</li>"
|
"<li><code>!args arg1 [arg2] ... [arg5]</code> - command that takes 1..5 arguments</li>"
|
||||||
"</ul>"
|
"</ul>"
|
||||||
)
|
)
|
||||||
await ctx.bot.send.text(ctx.room, HELP_MESSAGE)
|
await ctx.bot.send.text(
|
||||||
|
ctx.room,
|
||||||
|
HELP_MESSAGE,
|
||||||
|
is_html=True
|
||||||
|
)
|
||||||
|
|
||||||
async def on_time_command(ctx: EventContext, vars: ContextVars) -> None:
|
async def on_time_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""!time"""
|
"""!time"""
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
f"Current UNIX timestamp is <strong>{int(time.time())}</strong>"
|
f"Current UNIX timestamp is <strong>{int(time.time())}</strong>",
|
||||||
|
is_html=True
|
||||||
)
|
)
|
||||||
|
|
||||||
async def on_raise_command(ctx: EventContext, vars: ContextVars) -> None:
|
async def on_raise_command(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""!raise"""
|
"""!raise"""
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
"<strong>Executing <code>raise RuntimeError()</code>...</strong>"
|
"<strong>Executing <code>raise RuntimeError()</code>...</strong>",
|
||||||
|
is_html=True
|
||||||
)
|
)
|
||||||
raise RuntimeError()
|
raise RuntimeError()
|
||||||
|
|
||||||
@@ -50,7 +56,8 @@ async def on_assert_command(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
"""!assert"""
|
"""!assert"""
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
"<strong>Executing <code>assert False</code>...</strong>"
|
"<strong>Executing <code>assert False</code>...</strong>",
|
||||||
|
is_html=True
|
||||||
)
|
)
|
||||||
assert False
|
assert False
|
||||||
|
|
||||||
@@ -63,7 +70,11 @@ async def on_mul_command(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
v *= n
|
v *= n
|
||||||
response = " * ".join(html.escape("%.2f" % n) for n in numbers)
|
response = " * ".join(html.escape("%.2f" % n) for n in numbers)
|
||||||
response += f" = <strong>{html.escape(str(v))}<strong>"
|
response += f" = <strong>{html.escape(str(v))}<strong>"
|
||||||
await ctx.bot.send.text(ctx.room, response)
|
await ctx.bot.send.text(
|
||||||
|
ctx.room,
|
||||||
|
response,
|
||||||
|
is_html=True
|
||||||
|
)
|
||||||
except Exception as e:
|
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}")
|
||||||
|
|
||||||
@@ -81,7 +92,8 @@ async def on_args_command(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
response += "</ol>"
|
response += "</ol>"
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
response
|
response,
|
||||||
|
is_html=True
|
||||||
)
|
)
|
||||||
except:
|
except:
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
@@ -91,7 +103,10 @@ async def on_args_command(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
|
|
||||||
async def invalid_usage(ctx: EventContext, vars: ContextVars) -> None:
|
async def invalid_usage(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""This callback is called when the bot used incorrectly."""
|
"""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>",
|
||||||
|
is_html=True)
|
||||||
|
|
||||||
|
|
||||||
async def main() -> None:
|
async def main() -> None:
|
||||||
@@ -101,8 +116,8 @@ async def main() -> None:
|
|||||||
check_environment()
|
check_environment()
|
||||||
|
|
||||||
config = MatrixBotConfig(
|
config = MatrixBotConfig(
|
||||||
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"],
|
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
matrix_username_localpart=os.environ["MAB_USER"],
|
||||||
storage_directory="session_storage"
|
storage_directory="session_storage"
|
||||||
)
|
)
|
||||||
bot = MatrixBot(config)
|
bot = MatrixBot(config)
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ async def main() -> None:
|
|||||||
check_environment()
|
check_environment()
|
||||||
|
|
||||||
config = MatrixBotConfig(
|
config = MatrixBotConfig(
|
||||||
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"],
|
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
matrix_username_localpart=os.environ["MAB_USER"],
|
||||||
storage_directory="session_storage"
|
storage_directory="session_storage"
|
||||||
)
|
)
|
||||||
bot = MatrixBot(config)
|
bot = MatrixBot(config)
|
||||||
|
|||||||
@@ -80,8 +80,8 @@ async def main() -> None:
|
|||||||
check_environment()
|
check_environment()
|
||||||
|
|
||||||
config = MatrixBotConfig(
|
config = MatrixBotConfig(
|
||||||
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"],
|
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
matrix_username_localpart=os.environ["MAB_USER"],
|
||||||
storage_directory="session_storage"
|
storage_directory="session_storage"
|
||||||
)
|
)
|
||||||
bot = MatrixBot(config)
|
bot = MatrixBot(config)
|
||||||
|
|||||||
@@ -77,7 +77,8 @@ async def on_wrong_message(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
"""This callback is called when a wrong message is received."""
|
"""This callback is called when a wrong message is received."""
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
"Text me something like <code>!gen 0.1 0.7 1.0</code> or send an image to blur"
|
"Text me something like <code>!gen 0.1 0.7 1.0</code> or send an image to blur",
|
||||||
|
is_html=True
|
||||||
)
|
)
|
||||||
|
|
||||||
async def main() -> None:
|
async def main() -> None:
|
||||||
@@ -87,8 +88,8 @@ async def main() -> None:
|
|||||||
check_environment()
|
check_environment()
|
||||||
|
|
||||||
config = MatrixBotConfig(
|
config = MatrixBotConfig(
|
||||||
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"],
|
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
matrix_username_localpart=os.environ["MAB_USER"],
|
||||||
storage_directory="session_storage"
|
storage_directory="session_storage"
|
||||||
)
|
)
|
||||||
bot = MatrixBot(config)
|
bot = MatrixBot(config)
|
||||||
|
|||||||
81
examples/reaction_bot.py
Normal file
81
examples/reaction_bot.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
"""
|
||||||
|
This example implements Matrix bot that works with reactions.
|
||||||
|
|
||||||
|
It uses environment variables to specify authorization data. Use Ctrl+C to stop
|
||||||
|
the bot.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from mab import *
|
||||||
|
|
||||||
|
from _environment import check_environment
|
||||||
|
|
||||||
|
async def bump_count(bot: MatrixBot) -> int:
|
||||||
|
"""Bump count of reactions processed and return new value. Uses bot's
|
||||||
|
database for storage."""
|
||||||
|
val = await bot.load_value("reactions_processed")
|
||||||
|
val = 0 if val is None else int.from_bytes(val)
|
||||||
|
val += 1
|
||||||
|
await bot.save_value("reactions_processed", val.to_bytes(8))
|
||||||
|
return val
|
||||||
|
|
||||||
|
async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
|
"""This callback is called when a specific reaction is added."""
|
||||||
|
sender = vars[CTX_REACTION].sender
|
||||||
|
reaction = vars[CTX_REACTION].reaction
|
||||||
|
count = await bump_count(ctx.bot)
|
||||||
|
response = f"(Specific reaction) {sender}: {reaction}. Total reactions processed: {count}"
|
||||||
|
await ctx.bot.send.text(
|
||||||
|
ctx.room,
|
||||||
|
response
|
||||||
|
)
|
||||||
|
|
||||||
|
async def on_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
|
"""This callback is called when a reaction is added."""
|
||||||
|
sender = vars[CTX_REACTION].sender
|
||||||
|
reaction = vars[CTX_REACTION].reaction
|
||||||
|
count = await bump_count(ctx.bot)
|
||||||
|
response = f"(Generic reaction) {sender}: {reaction}. Total reactions processed: {count}"
|
||||||
|
await ctx.bot.send.text(
|
||||||
|
ctx.room,
|
||||||
|
response
|
||||||
|
)
|
||||||
|
|
||||||
|
async def on_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
|
"""This callback is called when a message is received."""
|
||||||
|
await bump_count(ctx.bot)
|
||||||
|
await ctx.bot.send.reaction(ctx.room, vars[CTX_ROOM_EVENT].event_id, "👀")
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
"""Application entry point"""
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||||
|
check_environment()
|
||||||
|
|
||||||
|
config = MatrixBotConfig(
|
||||||
|
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||||
|
matrix_username_localpart=os.environ["MAB_USER"],
|
||||||
|
storage_directory="session_storage"
|
||||||
|
)
|
||||||
|
bot = MatrixBot(config)
|
||||||
|
bot.add_callback(
|
||||||
|
~SenderIsBotFilter() & MessageReactionFilter(reaction=["❤️", "👍"]),
|
||||||
|
on_specific_reaction)
|
||||||
|
bot.add_callback(
|
||||||
|
~SenderIsBotFilter() & MessageReactionFilter(),
|
||||||
|
on_reaction)
|
||||||
|
bot.add_callback(
|
||||||
|
~SenderIsBotFilter() & NewMessageFilter(),
|
||||||
|
on_message)
|
||||||
|
|
||||||
|
# run until Ctrl+C
|
||||||
|
try:
|
||||||
|
await bot.run()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
@@ -30,7 +30,7 @@ async def on_help_message(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
"\n!unban <room_id> <user_id> - unban 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"
|
"\n!members <room_id> - get list of room members"
|
||||||
)
|
)
|
||||||
await ctx.bot.send.text(ctx.room, RESPONSE, is_html=False)
|
await ctx.bot.send.text(ctx.room, RESPONSE)
|
||||||
|
|
||||||
async def on_cmd_create(ctx: EventContext, vars: ContextVars) -> None:
|
async def on_cmd_create(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""!create"""
|
"""!create"""
|
||||||
@@ -137,8 +137,8 @@ async def main() -> None:
|
|||||||
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
|
||||||
check_environment()
|
check_environment()
|
||||||
config = MatrixBotConfig(
|
config = MatrixBotConfig(
|
||||||
matrix_homeserver_url=os.environ["MATRIX_HOMESERVER"],
|
matrix_homeserver_url=os.environ["MAB_SERVER"],
|
||||||
matrix_username_localpart=os.environ["MATRIX_USERNAME"],
|
matrix_username_localpart=os.environ["MAB_USER"],
|
||||||
storage_directory="session_storage"
|
storage_directory="session_storage"
|
||||||
)
|
)
|
||||||
bot = MatrixBot(config)
|
bot = MatrixBot(config)
|
||||||
@@ -226,7 +226,7 @@ async def main() -> None:
|
|||||||
)
|
)
|
||||||
#
|
#
|
||||||
bot.add_callback(
|
bot.add_callback(
|
||||||
~SenderIsBotFilter() & NewMessageFilter(),
|
~SenderIsBotFilter() & NewMessageFilter() & BodyExistsFilter(),
|
||||||
on_help_message
|
on_help_message
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -4,51 +4,23 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "mab"
|
name = "mab"
|
||||||
version = "0.7.0"
|
version = "0.7.1"
|
||||||
authors = [
|
authors = [
|
||||||
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
|
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
|
||||||
]
|
]
|
||||||
description = "Very simple async matrix bot library"
|
description = "Very simple async matrix bot library"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12"
|
requires-python = ">=3.13"
|
||||||
classifiers = [
|
classifiers = [
|
||||||
"Programming Language :: Python :: 3",
|
"Programming Language :: Python :: 3",
|
||||||
"Operating System :: OS Independent",
|
"Operating System :: OS Independent",
|
||||||
]
|
]
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aioconsole==0.8.2",
|
"matrix-nio[e2e]==0.26.0",
|
||||||
"aiofiles==25.1.0",
|
"aiosqlite==0.22.1",
|
||||||
"aiohappyeyeballs==2.7.1",
|
|
||||||
"aiohttp==3.14.3",
|
|
||||||
"aiohttp_socks==0.12.0",
|
|
||||||
"aiosignal==1.4.0",
|
|
||||||
"atomicwrites==1.4.1",
|
|
||||||
"attrs==26.1.0",
|
|
||||||
"build==1.5.0",
|
|
||||||
"cachetools==7.1.7",
|
|
||||||
"frozenlist==1.8.0",
|
|
||||||
"h11==0.16.0",
|
|
||||||
"h2==4.4.1",
|
|
||||||
"hpack==4.2.0",
|
|
||||||
"hyperframe==6.1.0",
|
|
||||||
"idna==3.19",
|
|
||||||
"jsonschema==4.26.0",
|
|
||||||
"jsonschema-specifications==2025.9.1",
|
|
||||||
"matrix-nio==0.26.0",
|
|
||||||
"multidict==6.7.1",
|
|
||||||
"packaging==26.3",
|
|
||||||
"peewee==3.19.0",
|
|
||||||
"propcache==0.5.2",
|
|
||||||
"pycryptodome==3.23.0",
|
|
||||||
"pyproject_hooks==1.2.0",
|
|
||||||
"python-socks==3.0.0",
|
|
||||||
"referencing==0.37.0",
|
|
||||||
"rpds-py==2026.6.3",
|
|
||||||
"unpaddedbase64==2.1.0",
|
|
||||||
"vodozemac==0.10.0",
|
|
||||||
"yarl==1.24.5",
|
|
||||||
"python-magic==0.4.27",
|
"python-magic==0.4.27",
|
||||||
"pillow==12.3.0"
|
"pillow==12.3.0",
|
||||||
|
"pydantic==2.14.4"
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ from .context.vars import ContextVars
|
|||||||
# Context variables
|
# Context variables
|
||||||
from .context.vars.command import *
|
from .context.vars.command import *
|
||||||
from .context.vars.message import *
|
from .context.vars.message import *
|
||||||
|
from .context.vars.reaction import *
|
||||||
from .context.vars.room_event import *
|
from .context.vars.room_event import *
|
||||||
@@ -7,9 +7,10 @@ from dataclasses import dataclass
|
|||||||
from nio import AsyncClient
|
from nio import AsyncClient
|
||||||
from nio import MatrixRoom
|
from nio import MatrixRoom
|
||||||
from nio import MatrixInvitedRoom, InviteMemberEvent, JoinResponse
|
from nio import MatrixInvitedRoom, InviteMemberEvent, JoinResponse
|
||||||
|
from nio import RoomGetStateResponse, SyncResponse
|
||||||
from nio.events.room_events import Event as RoomEvent
|
from nio.events.room_events import Event as RoomEvent
|
||||||
|
|
||||||
from ._storage import Storage
|
from ._database import _Database
|
||||||
from ..types import MatrixBotConfig
|
from ..types import MatrixBotConfig
|
||||||
from ..context import EventContext
|
from ..context import EventContext
|
||||||
from ..context.vars import ContextVars, ContextVarsPopulator
|
from ..context.vars import ContextVars, ContextVarsPopulator
|
||||||
@@ -42,6 +43,42 @@ class Callbacks:
|
|||||||
#
|
#
|
||||||
# PRIVATE
|
# PRIVATE
|
||||||
#
|
#
|
||||||
|
async def _callback_room_left(self, raw: Any) -> None:
|
||||||
|
"""This callback check if SyncResponse contains info about leaving the
|
||||||
|
room due to ban, kick or any other reason, and preforms some actions."""
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
raw = [raw]
|
||||||
|
for resp in raw:
|
||||||
|
if not isinstance(resp, SyncResponse):
|
||||||
|
continue
|
||||||
|
for room_id in resp.rooms.leave:
|
||||||
|
await self._db.join_timestamp_remove(room_id)
|
||||||
|
|
||||||
|
async def _get_room_join_timestamp(self, room_id: str) -> int | None:
|
||||||
|
"""Gets the room join timestamp."""
|
||||||
|
if self._client is None:
|
||||||
|
raise RuntimeError("Callbacks were not set up")
|
||||||
|
state = await self._client.room_get_state(room_id)
|
||||||
|
if not isinstance(state, RoomGetStateResponse):
|
||||||
|
return None
|
||||||
|
timestamp = 0
|
||||||
|
for event in state.events:
|
||||||
|
# only m.room.member
|
||||||
|
if event.get("type") != "m.room.member":
|
||||||
|
continue
|
||||||
|
# only describing our state
|
||||||
|
if event.get("state_key") != self._client.user_id:
|
||||||
|
continue
|
||||||
|
# only describing our join state
|
||||||
|
if event["content"].get("membership") != "join":
|
||||||
|
continue
|
||||||
|
if event.get("prev_content") and event["prev_content"].get("membership") not in ("invite", "leave"):
|
||||||
|
continue
|
||||||
|
origin_server_ts = event.get("origin_server_ts", 0)
|
||||||
|
if origin_server_ts > timestamp:
|
||||||
|
timestamp = origin_server_ts
|
||||||
|
return timestamp or None
|
||||||
|
|
||||||
async def _callback_room_event_router(self,
|
async def _callback_room_event_router(self,
|
||||||
room: MatrixRoom,
|
room: MatrixRoom,
|
||||||
event: RoomEvent) -> None:
|
event: RoomEvent) -> None:
|
||||||
@@ -50,6 +87,17 @@ class Callbacks:
|
|||||||
"""
|
"""
|
||||||
if self._config is None or self._client is None:
|
if self._config is None or self._client is None:
|
||||||
raise RuntimeError("Callbacks were not set up")
|
raise RuntimeError("Callbacks were not set up")
|
||||||
|
# update join time if needed
|
||||||
|
joined_timestamp = await self._db.join_timestamp_get(room.room_id)
|
||||||
|
if joined_timestamp is None:
|
||||||
|
joined_timestamp = await self._get_room_join_timestamp(room.room_id)
|
||||||
|
if joined_timestamp is not None:
|
||||||
|
await self._db.join_timestamp_set(room.room_id, joined_timestamp)
|
||||||
|
else:
|
||||||
|
return
|
||||||
|
# do not handle the event if it happened before we joined
|
||||||
|
if event.server_timestamp < joined_timestamp:
|
||||||
|
return
|
||||||
# build the event context
|
# build the event context
|
||||||
event_context = EventContext(
|
event_context = EventContext(
|
||||||
room=room,
|
room=room,
|
||||||
@@ -131,6 +179,9 @@ class Callbacks:
|
|||||||
"""
|
"""
|
||||||
if self._config is None or self._client is None:
|
if self._config is None or self._client is None:
|
||||||
raise RuntimeError("Callbacks were not set up")
|
raise RuntimeError("Callbacks were not set up")
|
||||||
|
self._client.add_response_callback(
|
||||||
|
self._callback_room_left, # type: ignore
|
||||||
|
)
|
||||||
# filter-based callback routing
|
# filter-based callback routing
|
||||||
self._client.add_event_callback(
|
self._client.add_event_callback(
|
||||||
self._callback_room_event_router, RoomEvent)
|
self._callback_room_event_router, RoomEvent)
|
||||||
@@ -142,9 +193,9 @@ class Callbacks:
|
|||||||
#
|
#
|
||||||
# PUBLIC
|
# PUBLIC
|
||||||
#
|
#
|
||||||
def __init__(self, storage: Storage, matrix_bot: "MatrixBot"):
|
def __init__(self, db: _Database, matrix_bot: "MatrixBot"):
|
||||||
self._logger = logging.getLogger("Callbacks")
|
self._logger = logging.getLogger("Callbacks")
|
||||||
self._storage = storage
|
self._db = db
|
||||||
self._matrix_bot = matrix_bot
|
self._matrix_bot = matrix_bot
|
||||||
self._context_vars_populator = ContextVarsPopulator()
|
self._context_vars_populator = ContextVarsPopulator()
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import aioconsole
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from ._storage import Storage
|
from ._database import _Database
|
||||||
|
|
||||||
from ..utils import Utils
|
from ..utils import Utils
|
||||||
from ..types import MatrixBotConfig
|
from ..types import MatrixBotConfig
|
||||||
@@ -20,15 +19,13 @@ class ClientAuth:
|
|||||||
async def _default_password_callback(self) -> str:
|
async def _default_password_callback(self) -> str:
|
||||||
if self._config is None:
|
if self._config is None:
|
||||||
raise RuntimeError("No config")
|
raise RuntimeError("No config")
|
||||||
if "MATRIX_PASSWORD" in os.environ:
|
if "MAB_PASSWORD" in os.environ:
|
||||||
return os.environ["MATRIX_PASSWORD"]
|
return os.environ["MAB_PASSWORD"]
|
||||||
if self._config.allow_ainput_password:
|
|
||||||
return await aioconsole.ainput("Matrix password: ")
|
|
||||||
raise RuntimeError("Can't get password")
|
raise RuntimeError("Can't get password")
|
||||||
|
|
||||||
async def _login_using_session_data(self, client: AsyncClient) -> None:
|
async def _login_using_session_data(self, client: AsyncClient) -> None:
|
||||||
"""
|
"""
|
||||||
Login using session data from `Storage`.
|
Login using session data from database.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- client - client that needs to get logged in
|
- client - client that needs to get logged in
|
||||||
@@ -39,15 +36,16 @@ class ClientAuth:
|
|||||||
"""
|
"""
|
||||||
if self._full_matrix_username is None:
|
if self._full_matrix_username is None:
|
||||||
raise RuntimeError("ClientAuth is not set up")
|
raise RuntimeError("ClientAuth is not set up")
|
||||||
self._logger.info("Trying to log in using session data from disk...")
|
self._logger.debug("Trying to log in using session data from disk...")
|
||||||
session_data = await self._storage.read_session_data()
|
access_token = await self._db.prop_get("access_token")
|
||||||
if session_data is None:
|
device_id = await self._db.prop_get("device_id")
|
||||||
self._logger.error("Can't read session data from disk")
|
if not isinstance(access_token, str) or not isinstance(device_id, str):
|
||||||
raise RuntimeError("Can't read session data from disk")
|
self._logger.error("Can't read session data from database")
|
||||||
|
raise RuntimeError("Can't read session data from database")
|
||||||
client.restore_login(
|
client.restore_login(
|
||||||
user_id=self._full_matrix_username,
|
user_id=self._full_matrix_username,
|
||||||
access_token=session_data["access_token"],
|
access_token=access_token,
|
||||||
device_id=session_data["device_id"]
|
device_id=device_id
|
||||||
)
|
)
|
||||||
client.load_store()
|
client.load_store()
|
||||||
result = await client.whoami()
|
result = await client.whoami()
|
||||||
@@ -63,7 +61,7 @@ class ClientAuth:
|
|||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"Unknown response for whoami request"
|
"Unknown response for whoami request"
|
||||||
)
|
)
|
||||||
self._logger.info("Logged in using stored session data")
|
self._logger.debug("Logged in using stored session data")
|
||||||
|
|
||||||
async def _login_using_password(self, client: AsyncClient) -> None:
|
async def _login_using_password(self, client: AsyncClient) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -78,15 +76,13 @@ class ClientAuth:
|
|||||||
"""
|
"""
|
||||||
if self._full_matrix_username is None:
|
if self._full_matrix_username is None:
|
||||||
raise RuntimeError("ClientAuth is not set up")
|
raise RuntimeError("ClientAuth is not set up")
|
||||||
self._logger.info("Trying to log in using password")
|
self._logger.debug("Trying to log in using password")
|
||||||
password = await self._default_password_callback()
|
password = await self._default_password_callback()
|
||||||
result = await client.login(password=password)
|
result = await client.login(password=password)
|
||||||
if type(result) is LoginResponse:
|
if type(result) is LoginResponse:
|
||||||
self._logger.info("Logged in using password")
|
self._logger.debug("Logged in using password")
|
||||||
await self._storage.write_session_data(
|
await self._db.prop_set("access_token", result.access_token)
|
||||||
access_token=result.access_token,
|
await self._db.prop_set("device_id", result.device_id)
|
||||||
device_id=result.device_id
|
|
||||||
)
|
|
||||||
elif type(result) is LoginError:
|
elif type(result) is LoginError:
|
||||||
self._logger.error(f"Can't log in using password: '{result.message}'")
|
self._logger.error(f"Can't log in using password: '{result.message}'")
|
||||||
raise RuntimeError(result.message)
|
raise RuntimeError(result.message)
|
||||||
@@ -97,9 +93,10 @@ class ClientAuth:
|
|||||||
#
|
#
|
||||||
# PUBLIC
|
# PUBLIC
|
||||||
#
|
#
|
||||||
def __init__(self, storage: Storage):
|
def __init__(self, db: _Database, *, log_level = logging.INFO):
|
||||||
self._logger = logging.getLogger("ClientAuth")
|
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||||
self._storage = storage
|
self._logger.setLevel(log_level)
|
||||||
|
self._db = db
|
||||||
self._full_matrix_username: str | None = None
|
self._full_matrix_username: str | None = None
|
||||||
self._config: MatrixBotConfig | None = None
|
self._config: MatrixBotConfig | None = None
|
||||||
|
|
||||||
@@ -109,6 +106,7 @@ class ClientAuth:
|
|||||||
"""
|
"""
|
||||||
self._config = config
|
self._config = config
|
||||||
self._full_matrix_username = Utils.build_full_matrix_username(config)
|
self._full_matrix_username = Utils.build_full_matrix_username(config)
|
||||||
|
self._logger.debug(f"Using full matrix username `{self._full_matrix_username}`")
|
||||||
|
|
||||||
async def login(self, client: AsyncClient) -> None:
|
async def login(self, client: AsyncClient) -> None:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from typing import Any
|
|||||||
from nio import AsyncClient, AsyncClientConfig, SyncResponse
|
from nio import AsyncClient, AsyncClientConfig, SyncResponse
|
||||||
from ..types import MatrixBotConfig
|
from ..types import MatrixBotConfig
|
||||||
|
|
||||||
from ._storage import Storage
|
from ._database import _Database
|
||||||
from ._client_auth import ClientAuth
|
from ._client_auth import ClientAuth
|
||||||
|
|
||||||
class ClientManager:
|
class ClientManager:
|
||||||
@@ -26,7 +26,7 @@ class ClientManager:
|
|||||||
await self._client.close()
|
await self._client.close()
|
||||||
self._logger.debug("Dumping 'next_batch' value...")
|
self._logger.debug("Dumping 'next_batch' value...")
|
||||||
if self._last_next_batch is not None:
|
if self._last_next_batch is not None:
|
||||||
await self._storage.write_next_batch(self._last_next_batch)
|
await self._db.prop_set("next_batch", self._last_next_batch)
|
||||||
|
|
||||||
async def _cancellable_sync_forever(self, *args, **kwargs) -> Any:
|
async def _cancellable_sync_forever(self, *args, **kwargs) -> Any:
|
||||||
"""
|
"""
|
||||||
@@ -60,7 +60,7 @@ class ClientManager:
|
|||||||
if self._client is None:
|
if self._client is None:
|
||||||
raise RuntimeError("Client does not exist")
|
raise RuntimeError("Client does not exist")
|
||||||
# try to login
|
# try to login
|
||||||
self._logger.info("Logging in...")
|
self._logger.debug("Logging in...")
|
||||||
try:
|
try:
|
||||||
await self._client_auth.login(self._client)
|
await self._client_auth.login(self._client)
|
||||||
self._logger.info(f"Logged in as {self._client.user_id}")
|
self._logger.info(f"Logged in as {self._client.user_id}")
|
||||||
@@ -70,10 +70,10 @@ class ClientManager:
|
|||||||
self._logger.error(traceback.format_exc())
|
self._logger.error(traceback.format_exc())
|
||||||
raise
|
raise
|
||||||
# sync forever
|
# sync forever
|
||||||
self._logger.info("Syncing forever...")
|
self._logger.debug("Syncing forever...")
|
||||||
await self._cancellable_sync_forever(
|
await self._cancellable_sync_forever(
|
||||||
timeout=self._config.client_sync_period_ms,
|
timeout=self._config.client_sync_period_ms,
|
||||||
since=(await self._storage.read_next_batch()),
|
since=(await self._db.prop_get("next_batch")),
|
||||||
full_state=True
|
full_state=True
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ class ClientManager:
|
|||||||
delta_time = current_time - self._last_next_batch_write_time
|
delta_time = current_time - self._last_next_batch_write_time
|
||||||
if delta_time >= self._config.client_next_batch_dump_period_s:
|
if delta_time >= self._config.client_next_batch_dump_period_s:
|
||||||
try:
|
try:
|
||||||
await self._storage.write_next_batch(self._last_next_batch)
|
await self._db.prop_set("next_batch", self._last_next_batch)
|
||||||
self._last_next_batch_write_time = current_time
|
self._last_next_batch_write_time = current_time
|
||||||
except:
|
except:
|
||||||
self._logger.error(traceback.format_exc())
|
self._logger.error(traceback.format_exc())
|
||||||
@@ -107,10 +107,11 @@ class ClientManager:
|
|||||||
#
|
#
|
||||||
# PUBLIC
|
# PUBLIC
|
||||||
#
|
#
|
||||||
def __init__(self, client_auth: ClientAuth, storage: Storage):
|
def __init__(self, client_auth: ClientAuth, db: _Database, *, log_level = logging.INFO):
|
||||||
self._logger = logging.getLogger("ClientManager")
|
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
self._client_auth = client_auth
|
self._client_auth = client_auth
|
||||||
self._storage = storage
|
self._db = db
|
||||||
|
|
||||||
self._config: MatrixBotConfig | None = None
|
self._config: MatrixBotConfig | None = None
|
||||||
self._client: AsyncClient | None = None
|
self._client: AsyncClient | None = None
|
||||||
@@ -174,7 +175,7 @@ class ClientManager:
|
|||||||
self._background_coroutine()
|
self._background_coroutine()
|
||||||
)
|
)
|
||||||
self._was_started_ever = True
|
self._was_started_ever = True
|
||||||
self._logger.info("Bot background is started")
|
self._logger.debug("Bot background is started")
|
||||||
|
|
||||||
async def stop(self) -> None:
|
async def stop(self) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -201,4 +202,4 @@ class ClientManager:
|
|||||||
except:
|
except:
|
||||||
self._logger.error(traceback.format_exc())
|
self._logger.error(traceback.format_exc())
|
||||||
self._background_task = None
|
self._background_task = None
|
||||||
self._logger.info("Bot background task is stopped")
|
self._logger.debug("Bot background task is stopped")
|
||||||
@@ -100,7 +100,8 @@ class ClientSender:
|
|||||||
|
|
||||||
async def content(self,
|
async def content(self,
|
||||||
room: MatrixRoom | str,
|
room: MatrixRoom | str,
|
||||||
content: dict) -> RoomSendResponse:
|
content: dict,
|
||||||
|
message_type: str = "m.room.message") -> RoomSendResponse:
|
||||||
"""
|
"""
|
||||||
Send raw `content` JSON to `room`.
|
Send raw `content` JSON to `room`.
|
||||||
|
|
||||||
@@ -117,7 +118,7 @@ class ClientSender:
|
|||||||
try:
|
try:
|
||||||
result = await self._client.room_send(
|
result = await self._client.room_send(
|
||||||
room_id=room.room_id if isinstance(room, MatrixRoom) else room,
|
room_id=room.room_id if isinstance(room, MatrixRoom) else room,
|
||||||
message_type="m.room.message",
|
message_type=message_type,
|
||||||
content=content
|
content=content
|
||||||
)
|
)
|
||||||
except OlmUnverifiedDeviceError:
|
except OlmUnverifiedDeviceError:
|
||||||
@@ -134,11 +135,33 @@ class ClientSender:
|
|||||||
else:
|
else:
|
||||||
raise RuntimeError("Unknown error has occured", result)
|
raise RuntimeError("Unknown error has occured", result)
|
||||||
|
|
||||||
|
async def reaction(self, room: MatrixRoom | str, message_id: str, reaction: str) -> str:
|
||||||
|
"""
|
||||||
|
Add `reaction` to the message `message_id` in `room`.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
- room - the room of `message_id`
|
||||||
|
- message_id - the message to add the `reaction` to
|
||||||
|
- reaction - emoji of reaction
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
- `event_id` of added reaction on success
|
||||||
|
- Raises an exception on error
|
||||||
|
"""
|
||||||
|
content = {
|
||||||
|
"m.relates_to": {
|
||||||
|
"event_id": message_id,
|
||||||
|
"key": reaction,
|
||||||
|
"rel_type": "m.annotation"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (await self.content(room, content, message_type="m.reaction")).event_id
|
||||||
|
|
||||||
async def text(self,
|
async def text(self,
|
||||||
room: MatrixRoom | str,
|
room: MatrixRoom | str,
|
||||||
text: str,
|
text: str,
|
||||||
*,
|
*,
|
||||||
is_html: bool | None = None) -> str:
|
is_html: bool | None = False) -> str:
|
||||||
"""
|
"""
|
||||||
Send text message to `room`.
|
Send text message to `room`.
|
||||||
|
|
||||||
@@ -162,7 +185,7 @@ class ClientSender:
|
|||||||
room: MatrixRoom | str,
|
room: MatrixRoom | str,
|
||||||
path: Path | str, *,
|
path: Path | str, *,
|
||||||
text: str | None = None,
|
text: str | None = None,
|
||||||
is_html: bool | None = None,
|
is_html: bool | None = False,
|
||||||
filename: str | None = None,
|
filename: str | None = None,
|
||||||
timeout: float | None = 60 * 60) -> str:
|
timeout: float | None = 60 * 60) -> str:
|
||||||
"""
|
"""
|
||||||
@@ -221,7 +244,7 @@ class ClientSender:
|
|||||||
filename: str,
|
filename: str,
|
||||||
*,
|
*,
|
||||||
text: str | None = None,
|
text: str | None = None,
|
||||||
is_html: bool | None = None,
|
is_html: bool | None = False,
|
||||||
timeout: float | None = 60 * 60) -> str:
|
timeout: float | None = 60 * 60) -> str:
|
||||||
"""
|
"""
|
||||||
Send the image to `room`. Please note that formatted text is displayed
|
Send the image to `room`. Please note that formatted text is displayed
|
||||||
@@ -284,7 +307,7 @@ class ClientSender:
|
|||||||
*,
|
*,
|
||||||
props: VideoFileProperties | None = None,
|
props: VideoFileProperties | None = None,
|
||||||
text: str | None = None,
|
text: str | None = None,
|
||||||
is_html: bool | None = None,
|
is_html: bool | None = False,
|
||||||
timeout: float | None = 60 * 60) -> str:
|
timeout: float | None = 60 * 60) -> str:
|
||||||
"""
|
"""
|
||||||
Send the video to `room`. Please note that formatted text is displayed
|
Send the video to `room`. Please note that formatted text is displayed
|
||||||
@@ -370,7 +393,7 @@ class ClientSender:
|
|||||||
filename: str | None = None,
|
filename: str | None = None,
|
||||||
mime_type: str | None = None,
|
mime_type: str | None = None,
|
||||||
text: str | None = None,
|
text: str | None = None,
|
||||||
is_html: bool | None = None,
|
is_html: bool | None = False,
|
||||||
timeout: float | None = 60 * 60):
|
timeout: float | None = 60 * 60):
|
||||||
"""
|
"""
|
||||||
Send the file to `room`. Please note that formatted text is displayed
|
Send the file to `room`. Please note that formatted text is displayed
|
||||||
@@ -431,7 +454,7 @@ class ClientSender:
|
|||||||
*,
|
*,
|
||||||
mime_type: str | None = None,
|
mime_type: str | None = None,
|
||||||
text: str | None = None,
|
text: str | None = None,
|
||||||
is_html: bool | None = None,
|
is_html: bool | None = False,
|
||||||
timeout: float | None = 60 * 60) -> str:
|
timeout: float | None = 60 * 60) -> str:
|
||||||
"""
|
"""
|
||||||
Send the file to `room`.
|
Send the file to `room`.
|
||||||
|
|||||||
@@ -11,13 +11,13 @@ from PIL import Image
|
|||||||
from nio import AsyncClient
|
from nio import AsyncClient
|
||||||
from nio import UploadError
|
from nio import UploadError
|
||||||
|
|
||||||
from ._storage import Storage
|
from ._database import _Database
|
||||||
from ..types import MatrixBotConfig, UploadResult
|
from ..types import MatrixBotConfig, UploadResult
|
||||||
|
|
||||||
class ClientUploader:
|
class ClientUploader:
|
||||||
"""This class uploads files"""
|
"""This class uploads files"""
|
||||||
def __init__(self, storage: Storage):
|
def __init__(self, db: _Database):
|
||||||
self._storage = storage
|
self._db = db
|
||||||
self._config: MatrixBotConfig | None = None
|
self._config: MatrixBotConfig | None = None
|
||||||
self._client: AsyncClient | None = None
|
self._client: AsyncClient | None = None
|
||||||
|
|
||||||
|
|||||||
165
src/mab/bot/_database.py
Normal file
165
src/mab/bot/_database.py
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
import sqlite3
|
||||||
|
import aiosqlite
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from ..types import MatrixBotConfig
|
||||||
|
|
||||||
|
class _Database:
|
||||||
|
"""Database interface"""
|
||||||
|
|
||||||
|
SCHEMA_VERSION = 3
|
||||||
|
"""Version of the database schema"""
|
||||||
|
|
||||||
|
async def _create_tables(self) -> None:
|
||||||
|
"""Create tables required for bot operation."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
STATEMENTS = (
|
||||||
|
(
|
||||||
|
"CREATE TABLE IF NOT EXISTS props("
|
||||||
|
"name TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||||
|
"value"
|
||||||
|
")"
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"CREATE TABLE IF NOT EXISTS join_timestamps("
|
||||||
|
"room_id TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||||
|
"timestamp INTEGER"
|
||||||
|
")"
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"CREATE TABLE IF NOT EXISTS user_kv_pairs("
|
||||||
|
"key TEXT UNIQUE ON CONFLICT REPLACE,"
|
||||||
|
"value BLOB"
|
||||||
|
")"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._logger.debug(f"Creating the tables")
|
||||||
|
for statement in STATEMENTS:
|
||||||
|
async with self._conn.execute(statement) as cursor:
|
||||||
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Tables are created")
|
||||||
|
|
||||||
|
def __init__(self, *, log_level = logging.INFO):
|
||||||
|
"""Create database object."""
|
||||||
|
self._conn: aiosqlite.Connection | None = None
|
||||||
|
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
|
|
||||||
|
async def setup(self, config: MatrixBotConfig):
|
||||||
|
"""Setup the database connection."""
|
||||||
|
if self._conn is not None:
|
||||||
|
raise RuntimeError("The connection already exists")
|
||||||
|
# save config and create path to the database
|
||||||
|
self._config = config
|
||||||
|
db_path = self._config.storage_directory
|
||||||
|
if not isinstance(db_path, Path):
|
||||||
|
db_path = Path(db_path)
|
||||||
|
db_path /= "database.sqlite"
|
||||||
|
self._logger.debug(f"Database path is `{db_path}`")
|
||||||
|
# connect to and setup database
|
||||||
|
self._conn = await aiosqlite.connect(db_path, autocommit=True)
|
||||||
|
self._conn.row_factory = sqlite3.Row
|
||||||
|
self._logger.debug(f"Connected to the database")
|
||||||
|
await self._create_tables()
|
||||||
|
# get database schema version
|
||||||
|
last_schema_version = await self.prop_get("schema_version") or self.SCHEMA_VERSION
|
||||||
|
self._logger.debug(f"On-disk database schema version is `{last_schema_version}`")
|
||||||
|
if not isinstance(last_schema_version, int):
|
||||||
|
raise RuntimeError("Invalid last_schema_version type")
|
||||||
|
# find version difference
|
||||||
|
if self.SCHEMA_VERSION < last_schema_version:
|
||||||
|
self._logger.critical(f"Database schema downgrade is not supported")
|
||||||
|
raise RuntimeError("It is forbidden to downgrade `mab` database version")
|
||||||
|
elif self.SCHEMA_VERSION > last_schema_version:
|
||||||
|
self._logger.info(f"Database schema will be updated to `{self.SCHEMA_VERSION}`")
|
||||||
|
# implement schema updating when needed
|
||||||
|
# save current schema version
|
||||||
|
await self.prop_set("schema_version", self.SCHEMA_VERSION)
|
||||||
|
|
||||||
|
async def close(self) -> None:
|
||||||
|
"""Close the database connection."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
self._logger.debug(f"Closing database connection")
|
||||||
|
await self._conn.close()
|
||||||
|
self._conn = None
|
||||||
|
self._logger.debug(f"Database connection is closed")
|
||||||
|
|
||||||
|
async def prop_get(self, name: str) -> Any | None:
|
||||||
|
"""Gets the value of the property `name` and returns it."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
async with self._conn.execute("SELECT value FROM props WHERE name=?",
|
||||||
|
(name,)) as cursor:
|
||||||
|
row = await cursor.fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return row["value"]
|
||||||
|
|
||||||
|
async def prop_set(self, name: str, value: Any) -> None:
|
||||||
|
"""Sets the value of the property `name` to `value`."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
async with self._conn.execute("REPLACE INTO props(name, value) VALUES(?, ?)",
|
||||||
|
(name, value)) as cursor:
|
||||||
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Updated property `{name}`")
|
||||||
|
|
||||||
|
async def user_kv_get(self, key: str) -> bytes | None:
|
||||||
|
"""Gets user key-value pair from the database. Returns None if it does
|
||||||
|
not exist."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
async with self._conn.execute("SELECT value FROM user_kv_pairs WHERE key=?",
|
||||||
|
(key,)) as cursor:
|
||||||
|
row = await cursor.fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return row["value"]
|
||||||
|
|
||||||
|
async def user_kv_set(self, key: str, value: bytes | None) -> bytes | None:
|
||||||
|
"""Sets user key-value pair in the database. Use `None` to remove it.
|
||||||
|
Returns `value`."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
if value is not None:
|
||||||
|
async with self._conn.execute("REPLACE INTO user_kv_pairs(key, value) VALUES(?, ?)",
|
||||||
|
(key, value)) as cursor:
|
||||||
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Updated user key-value `{key}`")
|
||||||
|
else:
|
||||||
|
async with self._conn.execute("DELETE FROM user_kv_pairs WHERE key=?",
|
||||||
|
(key,)) as cursor:
|
||||||
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Removed user key-value `{key}`")
|
||||||
|
return value
|
||||||
|
|
||||||
|
async def join_timestamp_get(self, room_id: str) -> int | None:
|
||||||
|
"""Returns the server timestamp when the room was joined (or None)."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
async with self._conn.execute("SELECT timestamp FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor:
|
||||||
|
row = await cursor.fetchone()
|
||||||
|
if row is None:
|
||||||
|
return None
|
||||||
|
return row["timestamp"]
|
||||||
|
|
||||||
|
async def join_timestamp_set(self, room_id: str, timestamp: int) -> None:
|
||||||
|
"""Sets the server timestamp when the room was joined."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
async with self._conn.execute("REPLACE INTO join_timestamps(room_id, timestamp) VALUES(?, ?)",
|
||||||
|
(room_id, timestamp)) as cursor:
|
||||||
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Updated join timestamp for room `{room_id}`")
|
||||||
|
|
||||||
|
async def join_timestamp_remove(self, room_id: str) -> None:
|
||||||
|
"""Removes the server timestamp when the room was joined."""
|
||||||
|
if self._conn is None:
|
||||||
|
raise RuntimeError("No connection exists")
|
||||||
|
async with self._conn.execute("DELETE FROM join_timestamps WHERE room_id=?", (room_id,)) as cursor:
|
||||||
|
await cursor.fetchall()
|
||||||
|
self._logger.debug(f"Removed join timestamp for room `{room_id}`")
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
from pathlib import Path
|
|
||||||
import aiofiles
|
|
||||||
import logging
|
|
||||||
import json
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from ..types import MatrixBotConfig
|
|
||||||
|
|
||||||
class Storage:
|
|
||||||
"""This class manages internal storage of the MatrixBot"""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self._logger = logging.getLogger("Storage")
|
|
||||||
self._config: MatrixBotConfig | None = None
|
|
||||||
|
|
||||||
async def setup(self, config: MatrixBotConfig) -> None:
|
|
||||||
"""
|
|
||||||
Setup the internal storage of the MatrixBot.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
- config - the config to use
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- Does not return anything
|
|
||||||
- Raises an exception on error
|
|
||||||
"""
|
|
||||||
self._config = config
|
|
||||||
|
|
||||||
async def write_next_batch(self, next_batch: str) -> None:
|
|
||||||
"""
|
|
||||||
Write `next_batch` value to the disk.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
- next_batch - value to save
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- Does not return anything
|
|
||||||
- Raises an exception on error
|
|
||||||
"""
|
|
||||||
if self._config is None:
|
|
||||||
raise RuntimeError("Storage is not set up")
|
|
||||||
path = Path(self._config.storage_directory) / "next_batch"
|
|
||||||
async with aiofiles.open(path, "w") as f:
|
|
||||||
await f.write(next_batch)
|
|
||||||
self._logger.debug("next_batch value is written to the disk")
|
|
||||||
|
|
||||||
async def read_next_batch(self) -> str | None:
|
|
||||||
"""
|
|
||||||
Read `next_batch` value from the disk.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- Returns `str` if there is `next_batch` value saved on disk
|
|
||||||
- Returns `None` if `next_batch` was never saved yet
|
|
||||||
- Raises an exception on error
|
|
||||||
"""
|
|
||||||
if self._config is None:
|
|
||||||
raise RuntimeError("Storage is not set up")
|
|
||||||
path = Path(self._config.storage_directory) / "next_batch"
|
|
||||||
if not path.is_file():
|
|
||||||
return None
|
|
||||||
async with aiofiles.open(path, "r") as f:
|
|
||||||
return (await f.read()).strip()
|
|
||||||
|
|
||||||
async def write_session_data(self, *, access_token: str, device_id: str) -> None:
|
|
||||||
"""
|
|
||||||
Write session data to disk.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
- access_token - access_token to write to the disk
|
|
||||||
- device_id - device_id to write to disk
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- Does not return anything
|
|
||||||
- Raises an exception on error
|
|
||||||
"""
|
|
||||||
if self._config is None:
|
|
||||||
raise RuntimeError("Storage is not set up")
|
|
||||||
path = Path(self._config.storage_directory) / "session_data.json"
|
|
||||||
data = {
|
|
||||||
"access_token": access_token,
|
|
||||||
"device_id": device_id
|
|
||||||
}
|
|
||||||
async with aiofiles.open(path, "w") as f:
|
|
||||||
await f.write(json.dumps(data, indent=4))
|
|
||||||
self._logger.debug("Session data is writter to the disk")
|
|
||||||
|
|
||||||
async def read_session_data(self) -> dict[str, Any] | None:
|
|
||||||
"""
|
|
||||||
Read session data from disk.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- Dictionary with `access_token` and `device_id` keys if these
|
|
||||||
values were saved using `write_session_data`
|
|
||||||
- `None` if session data was never saved yet
|
|
||||||
"""
|
|
||||||
if self._config is None:
|
|
||||||
raise RuntimeError("Storage is not set up")
|
|
||||||
path = Path(self._config.storage_directory) / "session_data.json"
|
|
||||||
if not path.is_file():
|
|
||||||
return None
|
|
||||||
async with aiofiles.open(path, "r") as f:
|
|
||||||
j = json.loads(await f.read())
|
|
||||||
return j
|
|
||||||
@@ -11,7 +11,7 @@ from ..context import EventContext
|
|||||||
from ..context.vars import ContextVars
|
from ..context.vars import ContextVars
|
||||||
|
|
||||||
from ._validation import Validator
|
from ._validation import Validator
|
||||||
from ._storage import Storage
|
from ._database import _Database
|
||||||
from ._client_auth import ClientAuth
|
from ._client_auth import ClientAuth
|
||||||
from ._client_room_operations import ClientRoomOperations
|
from ._client_room_operations import ClientRoomOperations
|
||||||
from ._client_downloader import ClientDownloader
|
from ._client_downloader import ClientDownloader
|
||||||
@@ -26,20 +26,21 @@ class MatrixBot:
|
|||||||
Asynchronous Matrix Bot Implementation.
|
Asynchronous Matrix Bot Implementation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, config: MatrixBotConfig) -> None:
|
def __init__(self, config: MatrixBotConfig, *, log_level = logging.INFO) -> None:
|
||||||
# create the logger
|
# create the logger
|
||||||
self._logger = logging.getLogger("MatrixBot")
|
self._logger = logging.getLogger(self.__class__.__name__)
|
||||||
|
self._logger.setLevel(log_level)
|
||||||
self._was_started = False
|
self._was_started = False
|
||||||
# create classes that compose MatrixBot
|
# create classes that compose MatrixBot
|
||||||
self._validator = Validator()
|
self._validator = Validator()
|
||||||
self._storage = Storage()
|
self._database = _Database(log_level=log_level)
|
||||||
self._client_auth = ClientAuth(self._storage)
|
self._client_auth = ClientAuth(self._database, log_level=log_level)
|
||||||
self._client_manager = ClientManager(self._client_auth, self._storage)
|
self._client_manager = ClientManager(self._client_auth, self._database, log_level=log_level)
|
||||||
self._client_uploader = ClientUploader(self._storage)
|
self._client_uploader = ClientUploader(self._database)
|
||||||
self._client_downloader = ClientDownloader()
|
self._client_downloader = ClientDownloader()
|
||||||
self._client_room_operations = ClientRoomOperations()
|
self._client_room_operations = ClientRoomOperations()
|
||||||
self._client_sender = ClientSender()
|
self._client_sender = ClientSender()
|
||||||
self._callbacks = Callbacks(self._storage, self)
|
self._callbacks = Callbacks(self._database, self)
|
||||||
# validate the config and save it
|
# validate the config and save it
|
||||||
try:
|
try:
|
||||||
self._validator.validate_bot_config(config)
|
self._validator.validate_bot_config(config)
|
||||||
@@ -79,7 +80,7 @@ class MatrixBot:
|
|||||||
raise RuntimeError("The bot was already started")
|
raise RuntimeError("The bot was already started")
|
||||||
self._was_started = True
|
self._was_started = True
|
||||||
await self._client_manager.setup(self._config)
|
await self._client_manager.setup(self._config)
|
||||||
await self._storage.setup(self._config)
|
await self._database.setup(self._config)
|
||||||
await self._client_auth.setup(self._config)
|
await self._client_auth.setup(self._config)
|
||||||
await self._client_uploader.setup(
|
await self._client_uploader.setup(
|
||||||
self._config,
|
self._config,
|
||||||
@@ -111,6 +112,7 @@ class MatrixBot:
|
|||||||
bot to completely stop.
|
bot to completely stop.
|
||||||
"""
|
"""
|
||||||
await self._client_manager.stop()
|
await self._client_manager.stop()
|
||||||
|
await self._database.close()
|
||||||
|
|
||||||
async def run(self) -> None:
|
async def run(self) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -126,6 +128,24 @@ class MatrixBot:
|
|||||||
finally:
|
finally:
|
||||||
await self.stop()
|
await self.stop()
|
||||||
|
|
||||||
|
async def save_value(self, key: str, value: bytes | None) -> bytes | None:
|
||||||
|
"""Save key-value pair to the database. Save `None` to remove the key.
|
||||||
|
Returns `value`.
|
||||||
|
|
||||||
|
Please use this feature for simple bots only. Prefer your own database
|
||||||
|
for higher efficiency.
|
||||||
|
"""
|
||||||
|
return await self._database.user_kv_set(key, value)
|
||||||
|
|
||||||
|
async def load_value(self, key: str) -> bytes | None:
|
||||||
|
"""Load key-value pair from the database. Returns `None` if the key
|
||||||
|
does not exist.
|
||||||
|
|
||||||
|
Please use this feature for simple bots only. Prefer your own database
|
||||||
|
for higher efficiency.
|
||||||
|
"""
|
||||||
|
return await self._database.user_kv_get(key)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def client(self) -> AsyncClient:
|
def client(self) -> AsyncClient:
|
||||||
"""
|
"""
|
||||||
|
|||||||
3
src/mab/context/vars/reaction/__init__.py
Normal file
3
src/mab/context/vars/reaction/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
from .types import *
|
||||||
|
from .keys import *
|
||||||
|
from . import builders
|
||||||
18
src/mab/context/vars/reaction/builders.py
Normal file
18
src/mab/context/vars/reaction/builders.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
from ... import EventContext
|
||||||
|
from .. import ContextVars, ContextVarsPopulator
|
||||||
|
|
||||||
|
from . import *
|
||||||
|
import json
|
||||||
|
|
||||||
|
@ContextVarsPopulator.autobuilder
|
||||||
|
def _build_reaction(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
|
"""This builder creates a CTX_MESSAGE variable for any message."""
|
||||||
|
source = ctx.event.source
|
||||||
|
if source.get("type") != "m.reaction":
|
||||||
|
return
|
||||||
|
res = Reaction(
|
||||||
|
message_id=source["content"]["m.relates_to"]["event_id"],
|
||||||
|
reaction=source["content"]["m.relates_to"]["key"],
|
||||||
|
sender=source["sender"]
|
||||||
|
)
|
||||||
|
vars[CTX_REACTION] = res
|
||||||
6
src/mab/context/vars/reaction/keys.py
Normal file
6
src/mab/context/vars/reaction/keys.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
from .types import *
|
||||||
|
from .. import ContextVarKey
|
||||||
|
|
||||||
|
CTX_REACTION = ContextVarKey[Reaction]("CTX_REACTION")
|
||||||
|
"""Variable that describes the reaction. It exists when the event is a new
|
||||||
|
reaction."""
|
||||||
13
src/mab/context/vars/reaction/types.py
Normal file
13
src/mab/context/vars/reaction/types.py
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
class Reaction(BaseModel):
|
||||||
|
"""A reaction to a message"""
|
||||||
|
|
||||||
|
message_id: str
|
||||||
|
"""Event ID for the message this reaction is added to."""
|
||||||
|
|
||||||
|
reaction: str
|
||||||
|
"""The reaction (emoji)."""
|
||||||
|
|
||||||
|
sender: str
|
||||||
|
"""Fully qualified username of the reactor."""
|
||||||
@@ -5,7 +5,7 @@ from ..types import MessageType
|
|||||||
from ..context import EventContext
|
from ..context import EventContext
|
||||||
from ..context.vars import ContextVars
|
from ..context.vars import ContextVars
|
||||||
|
|
||||||
from nio import RedactionEvent
|
from nio import RedactionEvent, ReactionEvent
|
||||||
|
|
||||||
class MessageTypeFilter(BaseEventFilter):
|
class MessageTypeFilter(BaseEventFilter):
|
||||||
"""
|
"""
|
||||||
@@ -131,3 +131,30 @@ class MessageHasFileFilter(BaseEventFilter):
|
|||||||
if "file" not in content and "url" not in content:
|
if "file" not in content and "url" not in content:
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
class MessageReactionFilter(EventTypeFilter):
|
||||||
|
"""
|
||||||
|
This filter returns True if the event is a new reaction added to the
|
||||||
|
message. Additionals checks are supported if you pass `sender` and
|
||||||
|
`reaction` when initializing the filter. They are checked case-sensetively
|
||||||
|
and stored by reference so you may modify behavior of this filter
|
||||||
|
dynamically.
|
||||||
|
"""
|
||||||
|
def __init__(self, *, sender: list[str] | str = [], reaction: list[str] | str = [], **kwargs):
|
||||||
|
super().__init__(ReactionEvent, **kwargs)
|
||||||
|
if isinstance(sender, str):
|
||||||
|
sender = [sender]
|
||||||
|
if isinstance(reaction, str):
|
||||||
|
reaction = [reaction]
|
||||||
|
self._sender = sender
|
||||||
|
self._reaction = reaction
|
||||||
|
|
||||||
|
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
|
||||||
|
if not await super().__call__(ctx, vars):
|
||||||
|
return False
|
||||||
|
sender = ctx.event.sender
|
||||||
|
if self._sender and sender not in self._sender:
|
||||||
|
return False
|
||||||
|
if self._reaction and ctx.event.key not in self._reaction: # type: ignore
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|||||||
@@ -31,9 +31,6 @@ class MatrixBotConfig:
|
|||||||
auto_ffmpeg: bool = True
|
auto_ffmpeg: bool = True
|
||||||
"""Enabled automatic `ffmpeg` execution to generate some media (e.g. thumbnails)"""
|
"""Enabled automatic `ffmpeg` execution to generate some media (e.g. thumbnails)"""
|
||||||
|
|
||||||
allow_ainput_password: bool = True
|
|
||||||
"""Allow `aioconsole.ainput` usage to get user password"""
|
|
||||||
|
|
||||||
client_sync_period_ms: int = 5000
|
client_sync_period_ms: int = 5000
|
||||||
"""Sync period for `nio.AsyncClient` in milliseconds"""
|
"""Sync period for `nio.AsyncClient` in milliseconds"""
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user