21 Commits

Author SHA1 Message Date
4dae739cfe Added branches system, updated database, v0.8.0
- Updated to v0.8.0
- Added note about rate limitting to README
- Updated examples to work with new callback system
- Updated README to describe new callback system correctly
- Added branch_bot.py example
- Updated database so internal functions are prefixed with underscore now
- Replaced MatrixBot.add_room_event_callback with MatrixBot.add_callback
- Database schema version is 4 now
- Added room state to database to simplify user code
- Added RoomStateFilter
2026-12-06 21:24:05 +03:00
b99b2fa9bf Added user key-value pairs in bot database. v0.7.1
- Bumped patch number
- Added user key-value pairs to the built-in database
- Updated reaction_bot example to use key-value pairs storage
- Database schema version is 3 now (added a table for user kv pairs)
2026-12-05 23:30:34 +03:00
86b1c6c142 Readme update, version update, examples update 2026-12-01 21:22:57 +03:00
d442aa7322 pyproject.toml and aioconsole
- Python 3.13+ is required now
- Shortened dependencies list in pyproject.toml
- peewee and aioconsole are no longer depended on
- Default password getter does not ask for password interactively anymore
- Default environment variable for password is MAB_PASSWORD now (was MATRIX_PASSWORD)
2026-12-01 20:20:50 +03:00
2ace008068 Added aiosqlite to deps 2026-11-21 23:35:48 +03:00
3b929a1d88 Added ability to set log level for bot 2026-11-21 23:28:00 +03:00
cbbafb7778 Implemented ignoring of events sent before the room was joined
- Fixed room bot so that it only sends help message when the message has text in it
- Incremeneted database SCHEMA_VERSION, now it's 2
2026-11-21 22:20:36 +03:00
eab2e8acb8 Implemented database, removed old Storage system 2026-11-21 20:46:13 +03:00
05a286b57a Added ability to add reactions 2026-11-13 16:11:42 +03:00
4b4c434bd8 Added reaction filter and context var 2026-11-13 15:58:43 +03:00
b7a471659d is_html=False by default now 2026-11-08 20:14:02 +03:00
d758bdedac Added support for file in message context variables
- Fixed file_bot example
- Added functions for extacting file data when building CTX_MESSAGE
- Added `file` variable for Message model
- Fixed RoomEvent builder inability to set room ID when it is missing in source
2026-11-08 20:02:02 +03:00
b5210359b1 Message is built by Pydantic now 2026-10-31 21:34:17 +03:00
ada7af9dd6 Added CTX_ROOM_EVENT 2026-10-31 21:00:45 +03:00
d5367ebc6b Big refactoring
- Changed event callback signature to `(ctx: EventContext, vars: ContextVars)`
- Changed event filter signature to `(ctx: EventContext, vars: ContextVars)`
- Partially fixed examples
- Refactored `src/mab/__init__.py` to be more structured
- Added support for local event context variables so that different filters don't mess with each other
- Refactored file structure for context variables
- Added support for combination of ContextVars
- `ContextVarsPopulator` does not look builders dynamically anymore; `ContextVarsPopulator.autobuilder` is used to mark function as a builder that must be automatically called
- `ContextVarsPopulator` does not required to be created anymore
- Added context variable `CTX_COMMAND`
- `MessageTypeFilter` supports message types passed as strings from now on
- `MessageHasFile` renamed to `MessageHasFileFilter`
- Added docs for context variables
2026-10-31 20:37:57 +03:00
eacb0c0d25 Refactoring in progress
- Context variables are no longer stored in `EventContext`, they are stored in `ContextVars` from now on
- Context variables related stuff has been moved to `mab.context.vars`
- Removed `CTX_FILE`
- Changed variable builder name prefix to `autobuild_`
- Changed variable builder signature to (EventContext, ContextVars)
- Most examples are broken
2026-10-31 16:30:24 +03:00
33efd5e104 Added CTX_FILE variable
- Modified file_bot.py example to utilize CTX_FILE
- Removed docstring for message builders.py
- Removed mab.models namespace package
2026-10-18 16:22:35 +03:00
17031500e9 Added context variable builders system
- Fixed subpackages missing __init__.py
- Fixed mab/__init__.py containing __all__
- Filters no longer add variables to EventContext
- Removed most context variables
- Reorganized file tree a bit
- Fixed echo_bot.py example

Most examples are broken
2026-10-18 15:29:12 +03:00
afcd3f53f4 Added more room APIs, filter changes
- Added APIs to create rooms and forget rooms
- Removed excess imports from filters
- `BaseEventFilter` now sets `CTX_SENDER`
- Added an example for rooms
- Added a note about version freezing to README
2026-10-04 21:37:08 +03:00
b22e7b4903 Added room operations (not tested) 2026-09-27 16:47:08 +03:00
2867582c01 Got rid of proxy methods in MatrixBot, v0.6.0
- Updated README.md
- Updated examples
- `MatrixBot` does not redefine methods from classes it is composed of anymore
2026-09-27 16:17:40 +03:00
48 changed files with 2228 additions and 1002 deletions

171
README.md
View File

@@ -4,12 +4,18 @@
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.
> [!IMPORTANT]
> You may need to tweak rate limits for your bot account in the server admin
> settings in order the server not to throttle your bot. Check
> [Ketasa](https://cloud.ketesa.app) if you use Synapse.
## ✨ Features ## ✨ Features
The library supports the following features: The library supports the following features:
- **Completely `asyncio` based** - **Completely `asyncio` based**
- **Filter-based callback system** - **Filter-based callback system**
- **Downloading and transparently decrypting files** - **Downloading and transparently decrypting files**
- **Sending files**
- **Sending images** - **Sending images**
- **Sending videos with automatic thumbnail generation (requires `ffmpeg`)** - **Sending videos with automatic thumbnail generation (requires `ffmpeg`)**
@@ -18,81 +24,134 @@ The library supports the following features:
Use `apt` to install required system packages and `pip` to install the package. 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 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 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 ```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.5.1 python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.8.0
``` ```
`libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev` `libmagic1-dev` is needed for automatic file MIME type detection, `libolm-dev`
is needed for E2EE to work. is needed for E2EE to work.
Please inspect [`examples/image_bot.py`](examples/image_bot.py), Please refer to [examples](examples/) for some basic bots. Examples are the best
[`examples/echo_bot.py`](examples/echo_bot.py) or open [`examples/`](examples/) introduction to this library. They are tested manually on each tagged commit.
directory to find usage examples. Examples require that you set You need to set `MAB_SERVER`, `MAB_USER` and `MAB_PASSWORD` environment
`MATRIX_HOMESERVER` and `MATRIX_USERNAME` environment variables. Examples create variables to pass server, username and password to the example.
`session_storage` directory in working directory.
| Variable | Example value |
|----------------|------------------------------|
| `MAB_SERVER` | `https://matrix.example.org` |
| `MAB_USER` | `localusername` |
| `MAB_PASSWORD` | `1337--w4-w1ll-r0ck-y0u!` |
## 🚀 Usage ## 🚀 Usage
If you use `mab`, your application will *most likely* be using **callbacks** to The architecture of `mab` is quite primitive. You define your callback
react to user actions. `mab` uses filter-based callback system to avoid exposing functions, you register them and you start the bot. When an event of interest
raw `nio-matrix` event objects. happens your callback functions get called. That's it. However, some spices are
poured in to enhance the development experience a little bit.
This is the workflow you will most likely follow: First of all, most encryption things are done transparently and automatically.
1. **Define the callback as `async` function that take 1 argument of type The most important thing that is not provided by `matrix-nio` is automatic
`EventContext`.** For example, this callback would print the caption of the **asynchronous** decryption of the files you download. You don't need to worry
message: about it **at all** when you use `mab`.
```python
from mab import *
async def on_media_with_body(ctx: EventContext): You need to create `MatrixBot` object to create a bot. This is the common way
"""To be called when a message with image/video and caption is received.""" of creating a bot:
print(ctx[CTX_BODY]) ```python
``` import asyncio
2. **Define the conditions your callback must be called on.** For example, you from mab import *
may want your callback to be called when `the sender is not the bot` and
`the message contains textual body` and (`the message is an image` or
`the message is a video`).
3. **Define the conditions as `filters`.** Most of them are pretty
straightforward. For example, if you want to use the conditions from above:
```python
from mab import *
filters = ( async def main():
~SenderIsBotFilter() # Create the config for the bot object
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO]) bot_config = MatrixBotConfig(
& BodyExistsFilter() matrix_homeserver_url="https://matrix.example.org",
) matrix_username_localpart="username-here",
``` storage_directory="session_storage"
4. **Add the callback to your `MatrixBot` instance.** For example, if you would )
have used everything from above, then your code would look something like # Create the bot itself
this: bot = MatrixBot(bot_config)
```python # Add callbacks (use `None` instead of callback name to print debug info)
from mab import * 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, **filter** 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 users in `admins_list`
admins_list = [
"@server-admin:matrix.example.org",
"@bot-admin:matrix.example.org"
]
sent_by_admin = SenderIsFilter(admins_list)
filters = ( # Filter that is True for messages that have file attached to them
~SenderIsBotFilter() has_file = MessageHasFileFilter()
& MessageTypeFilter([MessageType.IMAGE, MessageType.VIDEO])
& BodyExistsFilter()
)
bot.add_callback(filters, on_media_with_body)
... # Filter that is True for messages with nonempty body
``` has_body = BodyExistsFilter()
```
Filters support bitwise operators to implement complex matching logic. Some In fact, you can't create usable bot with just these filters. You need to
filters set context variables which can be accessed by combine them in different ways. So all filters support bitwise logical
`context[CTX_KEY_NAME]`-like syntax. Possible variables are defined in operators on them. For example, if you'd like to create a filter for a callback
[this file](src/mab/context.py). Filters are implemented in that must be called each time a different user adds a reaction to some message,
[files of this directory](src/mab/filters/). 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 = (
MessageHasFileFilter()
& SenderIsFilter(admin_list)
)
```
Sometimes it is useful to add some sort of hierarchy for your callbacks to
simplify the code. That's the moment when **Branch** concept becomes useful.
Let's assume you want to add specific event handlers that are executed only for
users from `admin_list`. You would write something like that:
```python
is_admin = SenderIsFilter(admin_list)
delete_command_filter = is_admin & BodyCommandFilter("delete")
create_command_filter = is_admin & BodyCommandFilter("create")
bot.callbacks.add_callback(delete_command_filter, callback_1)
bot.callbacks.add_callback(create_command_filter, callback_2)
```
You can logically organize these events in one branch to manage them more
efficiently:
```python
admin_branch = Branch(SenderIsFilter(admin_list))
admin_branch.add_callback(BodyCommandFilter("delete"), callback_1)
admin_branch.add_callback(BodyCommandFilter("create"), callback_2)
bot.callbacks.add_branch(admin_branch)
```
Please refer to [branch_bot.py](examples/branch_bot.py) for detailed usage
example.
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

72
docs/ContextVariables.md Normal file
View 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

View File

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

View File

@@ -0,0 +1,225 @@
import random, hashlib, math, io
from PIL import Image, ImageChops as C, ImageOps as O, ImageDraw, ImageFilter
def generate_image(text: str) -> bytes:
"""Generated by ChatGPT"""
r = random.Random(hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest())
u, pick = r.uniform, r.choice
sin, cos, pi = math.sin, math.cos, math.pi
S, N = 640, 192
scale = S / 384
def px(n): return max(1, round(n * scale))
B = Image.Resampling.BICUBIC
size = (S, S)
def noise(n, s=S):
return Image.frombytes('L',(n,n),r.randbytes(n*n)).resize((s,s),B)
# OKLCH -> sRGB, with gamut mapping (reduce chroma rather than clip).
def rgb(L, c, h):
for _ in range(12):
a,b = c*cos(h),c*sin(h)
l=(L+.3963377774*a+.2158037573*b)**3
m=(L-.1055613458*a-.0638541728*b)**3
s=(L-.0894841775*a-1.291485548*b)**3
v=(4.0767416621*l-3.3077115913*m+.2309699292*s,
-1.2684380046*l+2.6097574011*m-.3413193965*s,
-.0041960863*l-.7034186147*m+1.707614701*s)
if min(v)>=0 and max(v)<=1: break
c*=.84
return tuple(round(255*max(0,min(1,12.92*x if x<=.0031308 else 1.055*x**(1/2.4)-.055))) for x in v) # type: ignore
h=u(0,2*pi); dh=pick((-1,1))*u(.18,1.05)
accent=h+dh*pick((1,1,1.5,2.5))+pick((0,0,0,pi*.7))
colors=[rgb(u(.27,.36),u(.075,.13),h), rgb(u(.46,.57),u(.15,.23),h+dh*.35),
rgb(u(.62,.73),u(.17,.25),h+dh),rgb(u(.74,.83),u(.13,.21),accent),
rgb(u(.87,.93),u(.06,.12),accent)]
keys=[0,u(.2,.3),u(.45,.6),u(.72,.86),1]; pal=[]; j=0
for i in range(256):
t=i/255
if j<3 and t>keys[j+1]: j+=1
w=(t-keys[j])/(keys[j+1]-keys[j]); w=w*w*(3-2*w)
pal.append(tuple(round(a+(b-a)*w) for a,b in zip(colors[j],colors[j+1])))
def paint(im):
im=im.copy(); im.putpalette([v for p in pal for v in p]); return im.convert('RGB')
def normalize(im): return O.autocontrast(im,cutoff=1)
def field():
dx,dy=noise(r.randint(3,6),N).tobytes(),noise(r.randint(3,6),N).tobytes()
a,b,c=u(1.3,5.5),u(1.1,4.5),u(-3,3)
ox,oy,t=u(-.9,.9),u(-.9,.9),u(0,2*pi)
ct,st,w=cos(t),sin(t),u(.12,.85)
f=pick((lambda x,y: sin(a*x+b*sin(c*y+x)),
lambda x,y: sin(a*math.hypot(x,y)+b*math.atan2(y,x)),
lambda x,y: sin(a*x)*cos(b*y)+.55*x,
lambda x,y: sin(a*x+b*y)+.7*cos(b*x-a*y+c),
lambda x,y: cos(a*(x*x-y*y)+b*x*y)+.6*y,
lambda x,y: math.hypot(sin(a*x),cos(b*y+c)),
lambda x,y: math.hypot(x+.4*sin(b*y),y+.4*cos(a*x))+.4*sin(c*x)))
vals=[]
for i,(p,q) in enumerate(zip(dx,dy)):
x=(i%N)/(N/2)-1+w*(p-128)/128+ox
y=(i//N)/(N/2)-1+w*(q-128)/128+oy
vals.append(f(ct*x-st*y,st*x+ct*y))
lo,hi=min(vals),max(vals); k=255/max(hi-lo,1e-9)
return Image.frombytes('L',(N,N),bytes(min(255,int((v-lo)*k)) for v in vals)).resize(size,B)
def height():
im=field() if r.random()<.7 else noise(r.randint(3,6))
im=Image.blend(im,noise(r.randint(5,11)),u(.12,.36))
im=Image.blend(im,noise(r.randint(16,28)),u(.06,.14))
return normalize(im)
def shade(im, strength):
dx,dy=pick(((2,1),(-2,1),(1,-2)))
dx,dy=round(dx*scale),round(dy*scale)
g=C.subtract(C.offset(im,dx,dy),im,offset=128)
g=g.point(lambda i:max(65,min(255,235+strength*(i-128))))
return Image.merge('RGB',(g,g,g))
mode=r.randrange(9)
if mode<3:
im=height()
if r.random()<.3: im=C.invert(im)
if mode==2:
a=field(); im=normalize(Image.blend(im,pick((C.difference,C.multiply,C.lighter))(im,a),u(.35,.8)))
if mode==1: # terraced contours
n=r.randint(4,11); phase=u(0,1)
t=im.point(lambda i: int(255*(.78*(int(i*n/256)/n)+.22*i/255)))
result=paint(t)
edges=im.point([round(255*max(0,1-abs((i*n/255+phase)%1-.5)*18)) for i in range(256)])
result=Image.composite(Image.new('RGB',size,pal[pick((12,242))]),result,edges.point(lambda i:i*.64))
result=C.multiply(result,shade(im,2.3))
else:
result=C.multiply(paint(im),shade(im,u(4.0,9.0)))
if r.random()<.8:
n=r.randint(3,10)
lines=im.point([int(200*max(0,1-abs((i*n/255)%1-.5)*24)) for i in range(256)])
result=Image.composite(Image.new('RGB',size,pal[pick((12,230,250))]),result,lines)
elif mode==3 or mode==4: # streamlines / ribbons
bg=Image.blend(height(),Image.new('L',size,pick((10,20,60,130,165))),.84)
result=paint(bg); d=ImageDraw.Draw(result,'RGBA')
a,b,p=u(2,6),u(2,6),u(-pi,pi)
cx,cy=u(.15,.85),u(.15,.85)
k=u(.7,2.2); step=u(1.7,3.8)*scale; steps=r.randint(35,90)
vector=pick((lambda x,y:p+2.5*sin(a*x+b*y)+1.2*cos(b*y-p),
lambda x,y:p+2*sin(a*x+p)*cos(b*y-p),
lambda x,y:math.atan2(y-cy,x-cx)+pi/2+k*sin(a*x+b*y+p),
lambda x,y:p+1.8*sin(a*math.hypot(x-cx,y-cy)+b*x)))
for _ in range(r.randint(210,390)):
x,y=u(-.16,1.16)*S,u(-.16,1.16)*S; pts=[]
for i in range(steps):
pts.append((x,y)); ang=vector(x/S,y/S)
x+=step*cos(ang); y+=step*sin(ang)
idx=r.randint(110,250) if mode==3 else r.randint(10,245); width=pick((1,1,2,2,3) if mode==3 else (1,2,4,7))
d.line(pts,fill=(*pal[idx],r.randint(105,245)),width=px(width),joint='curve')
if width>=4: d.line(pts,fill=(*pal[min(255,idx+45)],185),width=px(1))
elif mode==5: # Peter de Jong strange attractor
best=0
for _ in range(8):
a,b,c,d=(u(-pi,pi) for _ in range(4)); x=y=.1; seen=set()
for i in range(2600):
x,y=sin(a*y)-cos(b*x),sin(c*x)-cos(d*y)
if i>100: seen.add((int(x*35),int(y*35)))
if len(seen)>best: best,params=len(seen),(a,b,c,d)
if best>1400: break
a,b,c,d=params; x=y=.1; hist=[0]*(S*S) # type: ignore
for i in range(120000):
x,y=sin(a*y)-cos(b*x),sin(c*x)-cos(d*y)
if i>=100: hist[int((y+2)*(.23*S)+.04*S)*S+int((x+2)*(.23*S)+.04*S)]+=1
hits=sorted(v for v in hist if v)
peak=max(8,hits[-max(1,len(hits)//100)])
lut=[min(255,round(255*math.log1p(i)/math.log1p(peak))) for i in range(max(hist)+1)]
im=Image.frombytes('L',size,bytes(lut[i] for i in hist))
if best<150:
im=height(); result=C.multiply(paint(im),shade(im,3))
else:
core=im.filter(ImageFilter.GaussianBlur(.25*scale))
glow=im.filter(ImageFilter.GaussianBlur(4*scale)).point(lambda i:min(255,2.4*i)) # type: ignore
bg=Image.blend(noise(5),Image.new('L',size,10),.88)
result=paint(C.add(C.add(bg,glow),core))
elif mode==6: # projected parametric surface
bg=Image.blend(height(),Image.new('L',size,pick((14,38,100,170))),.88)
result=paint(bg); draw=ImageDraw.Draw(result,'RGBA')
a,b=r.randint(2,7),r.randint(1,5)
phase,rot,tilt=u(0,2*pi),u(0,2*pi),u(.35,1.25)
ct,st=cos(rot),sin(rot); ctil,stil=cos(tilt),sin(tilt); R=u(.21,.32)*S; q=u(.10,.24)*S
cx,cy=u(.42,.58)*S,u(.42,.58)*S
count=r.randint(42,86); curves=[]; form=r.randrange(3)
for j in range(count):
v=2*pi*j/count; pts=[]; depth=0
for i in range(481):
t=2*pi*i/480
radius=R+q*cos(a*t+v+phase)
x=radius*cos(b*t); y=radius*sin(b*t); z=q*sin(a*t+v+phase)
if form==1:
x=R*sin(a*t+v)+q*cos(b*t); y=R*cos(b*t+v)+q*sin(a*t); z=q*sin(a*t-b*t+v)
elif form==2:
x=radius*cos(t); y=radius*sin(t); z=q*cos(b*t+v)*sin(a*t+phase)
y,z=y*ctil-z*stil,y*stil+z*ctil
pts.append((cx+ct*x-st*y,cy+st*x+ct*y)); depth+=z
curves.append((depth,j,pts))
for _,j,pts in sorted(curves):
k=int(110+140*(.5+.5*sin(j*2*pi/count+phase)))
draw.line(pts,fill=(*pal[k],r.randint(110,210)),width=px(pick((1,1,2))))
elif mode==7: # layered, fractured geometry with independent contour fields
im=height(); other=field()
result=paint(im)
n=r.randint(4,8)
sites=[(u(0,S),u(0,S)) for _ in range(n)]
def cell(i):
x,y=sites[i]; poly=[(0,0),(S,0),(S,S),(0,S)]
for j,(a,b) in enumerate(sites):
if i==j: continue
dx,dy=a-x,b-y; k=(a*a+b*b-x*x-y*y)/2
clipped=[]
for p,q in zip(poly,poly[1:]+poly[:1]):
P=p[0]*dx+p[1]*dy-k; Q=q[0]*dx+q[1]*dy-k
if P<=0: clipped.append(p)
if (P<=0)!=(Q<=0):
t=P/(P-Q); clipped.append((p[0]+t*(q[0]-p[0]),p[1]+t*(q[1]-p[1])))
poly=clipped
return poly
polys=[cell(i) for i in range(n)]
for i in range(n):
m=Image.new('L',size); d=ImageDraw.Draw(m)
poly=polys[i]
d.polygon(poly,fill=255)
source=pick((im,other,C.invert(im),C.invert(other)))
shift=r.randint(-65,65)
source=source.point(lambda x:max(0,min(255,x+shift))) # type: ignore
if r.random()<.6:
k=r.randint(3,9)
source=source.point(lambda x:int(255*(.7*int(x*k/256)/k+.3*x/255)))
result.paste(C.multiply(paint(source),shade(source,4)),mask=m)
draw=ImageDraw.Draw(result,'RGBA')
if r.random()<.7:
for poly in polys: draw.line(poly+poly[:1],fill=(*pal[240],100),width=px(1))
else: # Mandelbrot: randomized zoom and entropy-based selection
best=-float("inf")
for _ in range(6):
a,b=pick(((-.743643887,.131825904),(-.1011,.9563),(-1.25,0),(-.5,.55),(-.75,.1)))
z=10**u(-2.2,-.55); a+=u(-.35,.35)*z; b+=u(-.35,.35)*z
extent=(a-z,b-z,a+z,b+z); n=r.randint(70,115)
test=Image.effect_mandelbrot((96,96),extent,n)
score=test.entropy()-2*test.histogram()[0]/9216
if score>best: best,chosen=score,(extent,n)
if score>4.5: break
im=Image.effect_mandelbrot(size,*chosen) # type: ignore
im=normalize(im.point(lambda i:255*(i/255)**.43)) # type: ignore
if best<2.8:
im=normalize(Image.blend(height(),im,.35))
else:
im=normalize(Image.blend(im,noise(r.randint(3,8)),u(.08,.15)))
result=C.multiply(paint(im),shade(im,2))
# Subtle, deterministic film grain; high-quality downsampling and JPEG.
result=result.resize((512,512),Image.Resampling.LANCZOS)
grain=Image.frombytes('L',(512,512),r.randbytes(512*512)).point(lambda i: i*.035+123)
result=C.add(result,Image.merge('RGB',(grain,grain,grain)),offset=-127)
out=io.BytesIO(); result.save(out,'JPEG',quality=94,subsampling=0)
return out.getvalue()

138
examples/branch_bot.py Normal file
View File

@@ -0,0 +1,138 @@
"""
This example implements Matrix bot that demonstates branches and room states.
It uses environment variables to specify authorization data. Use Ctrl+C to stop
the bot.
"""
import asyncio
import os
import logging
import hashlib
from mab import *
from _environment import check_environment
from _image_generator import generate_image
#
# HELP MESSAGES
#
async def msg_on_upper(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to convert to upper case")
async def msg_on_sha256(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to find SHA256 for")
async def msg_on_count(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to count symbols in")
async def msg_on_image(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to convert to a random image")
async def msg_on_help(ctx: EventContext, vars: ContextVars) -> None:
TEXT = "Please choose the action to do:\n"
for state in STATES:
TEXT += f"\n{state} - {STATES[state][0]}"
event_id = await ctx.bot.send.text(ctx.room, TEXT)
for state in STATES:
await ctx.bot.send.reaction(ctx.room, event_id, state)
#
# CALLBACKS
#
async def on_upper(ctx: EventContext, vars: ContextVars) -> None:
"""🔠"""
await ctx.bot.send.text(ctx.room, vars[CTX_MESSAGE].body.upper())
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await asyncio.sleep(0.5)
await msg_on_help(ctx, vars)
async def on_sha256(ctx: EventContext, vars: ContextVars) -> None:
"""🔮"""
res = hashlib.sha256(vars[CTX_MESSAGE].body.encode("utf-8")).hexdigest()
await ctx.bot.send.text(ctx.room, res)
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await asyncio.sleep(0.5)
await msg_on_help(ctx, vars)
async def on_count(ctx: EventContext, vars: ContextVars) -> None:
"""🔍"""
await ctx.bot.send.text(ctx.room, f"The length is {len(vars[CTX_MESSAGE].body)}")
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await asyncio.sleep(0.5)
await msg_on_help(ctx, vars)
async def on_image(ctx: EventContext, vars: ContextVars) -> None:
"""🖼"""
inputs = [a.strip() for a in vars[CTX_MESSAGE].body.split("\n") if a.strip()]
for i in inputs:
await ctx.bot.send.image_bytes(
ctx.room,
generate_image(i),
"generated.jpg",
text=i
)
await asyncio.sleep(0.5)
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await msg_on_help(ctx, vars)
async def on_invalid(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a room with unset state appears."""
await msg_on_help(ctx, vars)
async def on_reaction(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a reaction is added to some message."""
state = vars[CTX_REACTION].reaction
if state not in STATES:
await msg_on_help(ctx, vars)
return
await ctx.bot.database.room_state_set(ctx.room.room_id, state)
await STATES[state][2](ctx, vars)
#
# STATES DATA
#
STATES = {
"🔠": ("Convert the text to upper case", on_upper, msg_on_upper),
"🔮": ("Find SHA256 for the text", on_sha256, msg_on_sha256),
"🔍": ("Count the symbols in the message", on_count, msg_on_count),
"🖼": ("Convert the text to a random image", on_image, msg_on_image),
}
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)
# create the root branch
branch_root = Branch(~SenderIsBotFilter() & NewMessageFilter())
# callbacks for state transitions
for state in STATES:
branch_root.add_callback(MessageReactionFilter(reaction=state), on_reaction)
# callbacks for active states
for state in STATES:
branch = Branch(RoomStateFilter(state))
branch.add_callback(MessageTypeFilter(MessageType.TEXT), STATES[state][1])
branch.add_callback(BaseEventFilter(), STATES[state][2])
branch_root.add_branch(branch)
# callback that fires for unhandled events (must be the last one added!)
branch_root.add_callback(BaseEventFilter(), on_invalid)
# register the root branch
bot.callbacks.add_branch(branch_root)
# run until Ctrl+C
try:
await bot.run()
except asyncio.CancelledError:
pass
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -16,7 +16,7 @@ from mab import *
from _environment import check_environment 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"""
HELP_MESSAGE = ( HELP_MESSAGE = (
"<strong>Here is the list of the commands:</strong><br>" "<strong>Here is the list of the commands:</strong><br>"
@@ -29,69 +29,84 @@ async def on_help_command(ctx: EventContext) -> 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(
async def on_time_command(ctx: EventContext) -> None:
"""!time"""
await ctx.bot.send_text(
ctx.room, ctx.room,
f"Current UNIX timestamp is <strong>{int(time.time())}</strong>" HELP_MESSAGE,
is_html=True
) )
async def on_raise_command(ctx: EventContext) -> None: async def on_time_command(ctx: EventContext, vars: ContextVars) -> None:
"""!raise""" """!time"""
await ctx.bot.send_text( await ctx.bot.send.text(
ctx.room, ctx.room,
"<strong>Executing <code>raise RuntimeError()</code>...</strong>" f"Current UNIX timestamp is <strong>{int(time.time())}</strong>",
is_html=True
)
async def on_raise_command(ctx: EventContext, vars: ContextVars) -> None:
"""!raise"""
await ctx.bot.send.text(
ctx.room,
"<strong>Executing <code>raise RuntimeError()</code>...</strong>",
is_html=True
) )
raise RuntimeError() raise RuntimeError()
async def on_assert_command(ctx: EventContext) -> None: 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
async def on_mul_command(ctx: EventContext) -> None: async def on_mul_command(ctx: EventContext, vars: ContextVars) -> None:
"""!mul""" """!mul"""
try: try:
numbers = [float(v) for v in ctx[CTX_CMD_ARGS]] numbers = [float(v) for v in vars[CTX_COMMAND].args]
v = numbers[0] v = numbers[0]
for n in numbers[1:]: for n in numbers[1:]:
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}")
async def on_args_command(ctx: EventContext) -> None: async def on_args_command(ctx: EventContext, vars: ContextVars) -> None:
"""!args""" """!args"""
try: try:
response = ( response = (
f"Prefix: <code>{ctx[CTX_CMD_PREFIX]}</code><br>" f"Prefix: <code>{vars[CTX_COMMAND].prefix}</code><br>"
f"Verb: <code>{ctx[CTX_CMD_VERB]}</code><br>" f"Verb: <code>{vars[CTX_COMMAND].verb}</code><br>"
f"Arguments: <code>{len(ctx[CTX_CMD_ARGS])}</code><br>" f"Arguments: <code>{len(vars[CTX_COMMAND].args)}</code><br>"
f"Arguments are:<br><ol>" 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 += f"<li><code>{html.escape(arg)}</code></li>"
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(
ctx.room, ctx.room,
f"Could not process the command: {traceback.format_exc()}" 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.""" """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)
@@ -116,9 +131,8 @@ async def main() -> None:
on_args_command: BodyCommandFilter("args", min_args=1, max_args=5), on_args_command: BodyCommandFilter("args", min_args=1, max_args=5),
} }
for callback, filter in COMMANDS.items(): for callback, filter in COMMANDS.items():
f = ~SenderIsBotFilter() & filter bot.callbacks.add_callback(filter, callback)
bot.add_callback(f, callback) bot.callbacks.add_callback(BodyExistsFilter(), invalid_usage)
bot.add_callback(~SenderIsBotFilter() & NewMessageFilter(), invalid_usage)
# run until Ctrl+C # run until Ctrl+C
try: try:

View File

@@ -13,9 +13,9 @@ from mab import *
from _environment import check_environment 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.""" """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: async def main() -> None:
"""Application entry point""" """Application entry point"""
@@ -24,14 +24,12 @@ 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)
bot.add_callback( bot.callbacks.add_callback(MessageTypeFilter(MessageType.TEXT), on_text_message)
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
on_text_message)
# run until Ctrl+C # run until Ctrl+C
try: try:

View File

@@ -16,20 +16,25 @@ from mab import *
from _environment import check_environment 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.""" """This callback is called when a text message arrives."""
await ctx.bot.send_text(ctx.room, "Please send a file/image/video") await ctx.bot.send.text(ctx.room, "Please send a file/image/video/audio")
async def on_file_message(ctx: EventContext) -> None: async def on_file_message(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a file arrives.""" """This callback is called when a file arrives."""
sha = hashlib.sha256() sha = hashlib.sha256()
does_temp_exist = False does_temp_exist = False
if ctx[CTX_FILE_SIZE] > 1_000_000: file = vars[CTX_MESSAGE].file
await ctx.bot.send_text( if not file:
return
if not file.filesize:
file.filesize = 0
if file.filesize > 1_000_000:
await ctx.bot.send.text(
ctx.room, ctx.room,
"The file is larger than 1 MB, downloading to filesystem" "The file is larger than 1 MB, downloading to filesystem"
) )
await ctx.bot.download_file(ctx, path="temp.tmp") await ctx.bot.download.file(ctx, path="temp.tmp")
async with aiofiles.open("temp.tmp", "rb") as f: async with aiofiles.open("temp.tmp", "rb") as f:
while True: while True:
data = await f.read(64 * 1024) data = await f.read(64 * 1024)
@@ -38,16 +43,16 @@ async def on_file_message(ctx: EventContext) -> None:
sha.update(data) sha.update(data)
does_temp_exist = True does_temp_exist = True
else: else:
await ctx.bot.send_text( await ctx.bot.send.text(
ctx.room, ctx.room,
"The file is smaller than 1 MB, downloading to RAM" "The file is smaller than 1 MB, downloading to RAM"
) )
content = await ctx.bot.download_file(ctx, path=None) content = await ctx.bot.download.file(ctx, path=None)
sha.update(content) sha.update(content)
# result # result
response = f"SHA256 for file `{ctx[CTX_FILE_NAME]}`" response = f"SHA256 for file `{file.filename}`"
response += f" ({ctx[CTX_FILE_SIZE]} bytes, {ctx[CTX_FILE_MIME]})" response += f" ({file.filesize} bytes, {file.filename})"
await ctx.bot.send_file_bytes( await ctx.bot.send.file_bytes(
room=ctx.room, room=ctx.room,
data=sha.hexdigest().encode("utf-8"), data=sha.hexdigest().encode("utf-8"),
filename="hash of the file.txt", filename="hash of the file.txt",
@@ -56,10 +61,10 @@ async def on_file_message(ctx: EventContext) -> None:
) )
# resend the file to test uploading # resend the file to test uploading
if does_temp_exist: if does_temp_exist:
await ctx.bot.send_file( await ctx.bot.send.file(
room=ctx.room, room=ctx.room,
path="temp.tmp", path="temp.tmp",
filename=ctx[CTX_FILE_NAME], filename=file.filename,
text="This is the file you have sent, but it was reuploaded" text="This is the file you have sent, but it was reuploaded"
) )
try: try:
@@ -75,17 +80,13 @@ 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)
bot.add_callback( bot.callbacks.add_callback(MessageTypeFilter(MessageType.TEXT), on_text_message)
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT), bot.callbacks.add_callback(MessageHasFileFilter(), on_file_message)
on_text_message)
bot.add_callback(
~SenderIsBotFilter() & MessageHasFile() & NewMessageFilter(),
on_file_message)
# run until Ctrl+C # run until Ctrl+C
try: try:

View File

@@ -18,15 +18,15 @@ from mab import *
from _environment import check_environment 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.""" """This callback is called when `!gen R G B` command is received."""
# convert R, G and B to floats # convert R, G and B to floats
try: 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: except:
await data.bot.send_text(data.room, "Invalid arguments") await ctx.bot.send.text(ctx.room, "Invalid arguments")
return 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 # create the basic noise
img = Image.new("RGB", (16, 16)) img = Image.new("RGB", (16, 16))
for x in range(img.width): for x in range(img.width):
@@ -44,13 +44,13 @@ async def on_gen_command(data: EventContext) -> None:
buf.seek(0) buf.seek(0)
buf = buf.read() buf = buf.read()
# send # 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_image(ctx: EventContext) -> None: async def on_image(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when an image is received.""" """This callback is called when an image is received."""
# download # download
s = time.time() s = time.time()
data = await ctx.bot.download_file(ctx) data = await ctx.bot.download.file(ctx)
took_time = time.time() - s took_time = time.time() - s
# convert to Image # convert to Image
with BytesIO(data) as buf: with BytesIO(data) as buf:
@@ -66,18 +66,19 @@ async def on_image(ctx: EventContext) -> None:
buf.seek(0) buf.seek(0)
buf = buf.read() buf = buf.read()
# send # send
await ctx.bot.send_image_bytes( await ctx.bot.send.image_bytes(
ctx.room, ctx.room,
buf, buf,
"blurred.png", "blurred.png",
text="Download and decryption took %.4f seconds" % took_time text="Download and decryption took %.4f seconds" % took_time
) )
async def on_wrong_message(data: EventContext) -> None: 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 data.bot.send_text( await ctx.bot.send.text(
data.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)
@@ -98,26 +99,12 @@ async def main() -> None:
max_args=3 max_args=3
) )
# callback for message that # callback for message that match the command filter
# 1. are sent not by this bot bot.callbacks.add_callback(command_filter, on_gen_command)
# 2. do match the command filter
bot.add_callback(
~SenderIsBotFilter() & command_filter,
on_gen_command)
# callback for new image message # callback for new image message
bot.add_callback( bot.callbacks.add_callback(MessageTypeFilter(MessageType.IMAGE), on_image)
~SenderIsBotFilter() & MessageTypeFilter(MessageType.IMAGE) & NewMessageFilter(), # callback for message that contain body
on_image bot.callbacks.add_callback(BodyExistsFilter(), on_wrong_message)
)
# callback for message that
# 1. are sent not by this bot
# 2. are new messages (not edits)
bot.add_callback(
~SenderIsBotFilter() & BodyExistsFilter() & NewMessageFilter(),
on_wrong_message
)
# run until Ctrl+C # run until Ctrl+C
try: try:

75
examples/reaction_bot.py Normal file
View File

@@ -0,0 +1,75 @@
"""
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.database.custom_get("reactions_processed")
val = 0 if val is None else int.from_bytes(val)
val += 1
await bot.database.custom_set("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.callbacks.add_callback(MessageReactionFilter(reaction=["❤️", "👍"]), on_specific_reaction)
bot.callbacks.add_callback(MessageReactionFilter(), on_reaction)
bot.callbacks.add_callback(NewMessageFilter(), on_message)
# run until Ctrl+C
try:
await bot.run()
except asyncio.CancelledError:
pass
if __name__ == "__main__":
asyncio.run(main())

204
examples/room_bot.py Normal file
View File

@@ -0,0 +1,204 @@
"""
This example implements Matrix bot that does some rooms stuff.
It uses environment variables to specify authorization data. Use Ctrl+C to stop
the bot.
"""
import asyncio
import os
import random
import traceback
import logging
from mab import *
from _environment import check_environment
async def on_help_message(ctx: EventContext, vars: ContextVars) -> None:
"""Help message"""
RESPONSE = (
"Here's how you use the bot:"
"\n"
"\n!create - create a new room"
"\n!leave - leave the room"
"\n!forget - leave the room and forget it"
"\n!join <room_id> - join the room (requires invitation)"
"\n!invite <room_id> <user_id> - invite the user to the room"
"\n!kick <room_id> <user_id> - kick the user from the room"
"\n!ban <room_id> <user_id> - ban the user from the room"
"\n!unban <room_id> <user_id> - unban the user from the room"
"\n!members <room_id> - get list of room members"
)
await ctx.bot.send.text(ctx.room, RESPONSE)
async def on_cmd_create(ctx: EventContext, vars: ContextVars) -> None:
"""!create"""
await ctx.bot.rooms.create()
alias = "".join([random.choice("abcdefghj") for i in range(10)])
name = alias.capitalize()
topic = "This room was craeted by the example bot"
try:
res = await ctx.bot.rooms.create(
alias=alias,
name=name,
topic=topic,
invite_list=[vars[CTX_ROOM_EVENT].sender]
)
await ctx.bot.send.text(ctx.room, f"Created the room {res}")
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def on_cmd_leave(ctx: EventContext, vars: ContextVars) -> None:
"""!leave"""
await ctx.bot.send.text(ctx.room, "Leaving this room")
await asyncio.sleep(1)
await ctx.bot.rooms.leave(ctx.room)
async def on_cmd_forget(ctx: EventContext, vars: ContextVars) -> None:
"""!forget"""
await ctx.bot.send.text(ctx.room, "Leaving the room and forgetting it")
await asyncio.sleep(1)
await ctx.bot.rooms.leave(ctx.room)
await asyncio.sleep(1)
await ctx.bot.rooms.forget(ctx.room)
async def on_cmd_join(ctx: EventContext, vars: ContextVars) -> None:
"""!join"""
try:
room_id = vars[CTX_COMMAND].args[0]
await ctx.bot.send.text(ctx.room, f"Joining the room {room_id}")
await asyncio.sleep(1)
await ctx.bot.rooms.join(room_id)
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def on_cmd_invite(ctx: EventContext, vars: ContextVars) -> None:
"""!invite"""
try:
room_id = vars[CTX_COMMAND].args[0]
user_id = vars[CTX_COMMAND].args[1]
await ctx.bot.send.text(ctx.room, f"Inviting {user_id} to {room_id}")
await asyncio.sleep(1)
await ctx.bot.rooms.invite(room_id, user_id)
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def on_cmd_kick(ctx: EventContext, vars: ContextVars) -> None:
"""!kick"""
try:
room_id = vars[CTX_COMMAND].args[0]
user_id = vars[CTX_COMMAND].args[1]
await ctx.bot.send.text(ctx.room, f"Kicking {user_id} from {room_id}")
await asyncio.sleep(1)
await ctx.bot.rooms.kick(room_id, user_id, "Testing rooms")
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def on_cmd_ban(ctx: EventContext, vars: ContextVars) -> None:
"""!ban"""
try:
room_id = vars[CTX_COMMAND].args[0]
user_id = vars[CTX_COMMAND].args[1]
await ctx.bot.send.text(ctx.room, f"Banning {user_id} in {room_id}")
await asyncio.sleep(1)
await ctx.bot.rooms.ban(room_id, user_id, "Testing rooms")
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def on_cmd_unban(ctx: EventContext, vars: ContextVars) -> None:
"""!unban"""
try:
room_id = vars[CTX_COMMAND].args[0]
user_id = vars[CTX_COMMAND].args[1]
await ctx.bot.send.text(ctx.room, f"Unbanning {user_id} in {room_id}")
await asyncio.sleep(1)
await ctx.bot.rooms.unban(room_id, user_id)
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def on_cmd_members(ctx: EventContext, vars: ContextVars) -> None:
"""!members"""
try:
room_id = vars[CTX_COMMAND].args[0]
await ctx.bot.send.text(ctx.room, f"Listing members of {room_id}")
await asyncio.sleep(1)
members = await ctx.bot.rooms.members(room_id)
for m in members:
await ctx.bot.send.text(ctx.room, f"{m.display_name} - {m.user_id}", is_html=False)
await asyncio.sleep(1)
await ctx.bot.send.text(ctx.room, f"Done")
except:
await ctx.bot.send.text(ctx.room, traceback.format_exc())
async def main() -> None:
"""Application entry point"""
logging.basicConfig(level=logging.INFO)
logging.getLogger("nio").setLevel(logging.CRITICAL+1)
check_environment()
config = MatrixBotConfig(
matrix_homeserver_url=os.environ["MAB_SERVER"],
matrix_username_localpart=os.environ["MAB_USER"],
storage_directory="session_storage"
)
bot = MatrixBot(config)
#
bot.callbacks.add_callback(
BodyCommandFilter("create"),
on_cmd_create
)
#
bot.callbacks.add_callback(
BodyCommandFilter("leave"),
on_cmd_leave
)
#
bot.callbacks.add_callback(
BodyCommandFilter("forget"),
on_cmd_forget
)
#
bot.callbacks.add_callback(
BodyCommandFilter("join", min_args=1),
on_cmd_join
)
#
bot.callbacks.add_callback(
BodyCommandFilter("invite", min_args=2),
on_cmd_invite
)
#
bot.callbacks.add_callback(
BodyCommandFilter("kick", min_args=2),
on_cmd_kick
)
#
bot.callbacks.add_callback(
BodyCommandFilter("ban", min_args=2),
on_cmd_ban
)
#
bot.callbacks.add_callback(
BodyCommandFilter("unban", min_args=2),
on_cmd_unban
)
#
bot.callbacks.add_callback(
BodyCommandFilter("members", min_args=1),
on_cmd_members
)
#
bot.callbacks.add_callback(
BodyExistsFilter(),
on_help_message
)
# run until Ctrl+C
try:
await bot.run()
except asyncio.CancelledError:
pass
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -4,51 +4,23 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "mab" name = "mab"
version = "0.5.2" version = "0.8.0"
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]

View File

@@ -1,57 +1,19 @@
from . import bot # Bot and its config types
from . import types
from .types import MatrixBotConfig, MessageType
from .context import *
from .bot import MatrixBot from .bot import MatrixBot
from .types import MatrixBotConfig
from .filters.base import * # Introduce all filters into mab namespace
from .filters.message import * from .filters import *
from .filters.body import *
__all__ = [ # Types for callback arguments
# module names from .context import EventContext
"bot", from .context.vars import ContextVars
"types",
# .types # Branches
"MatrixBotConfig", from .branch import Branch, BranchCallback
"MessageType",
# .context # Context variables
"EventContext", from .context.vars.command import *
"CTX_BODY", from .context.vars.message import *
"CTX_MESSAGE_TYPE", from .context.vars.reaction import *
"CTX_SENDER", from .context.vars.room_event import *
"CTX_CMD_PREFIX",
"CTX_CMD_VERB",
"CTX_CMD_ARGS",
"CTX_FILE_SIZE",
"CTX_FILE_MIME",
"CTX_FILE_NAME",
# .bot
"MatrixBot",
# .filters.base
"BaseEventFilter",
"EventTypeFilter",
# .filters.body
"BodyExistsFilter",
"BodyContainsFilter",
"BodyStartsWithFilter",
"BodyEndsWithFilter",
"BodyCommandFilter",
"BodyRegexFilter",
# .filters.message
"MessageTypeFilter",
"NewMessageFilter",
"EditedMessageFilter",
"RedactedMessageFilter",
"SenderIsFilter",
"SenderIsBotFilter",
"MessageHasFile",
]

View File

@@ -7,13 +7,18 @@ 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 ..filters.base import BaseEventFilter from ..filters.base import BaseEventFilter
from ..branch import Branch, BranchCallback, _BranchStopException
from ..filters import SenderIsBotFilter, NewMessageFilter, MessageReactionFilter
if TYPE_CHECKING: if TYPE_CHECKING:
from .bot import MatrixBot from .bot import MatrixBot
@@ -32,7 +37,7 @@ class Callbacks:
filter: BaseEventFilter filter: BaseEventFilter
"""Filter to use for matching""" """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""" """Callback that will be called if the filter matches"""
stop_matching: bool stop_matching: bool
@@ -41,6 +46,51 @@ 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 _event_branch_executor(self, ctx: EventContext, vars: ContextVars) -> None:
"""This cancellable coroutine executes all branches with given `ctx`
and `vars`. It also correctly handles `_BranchStopException`."""
try:
for branch in self._branches:
await branch._execute(ctx, vars)
except _BranchStopException:
pass
async def _callback_room_event_router(self, async def _callback_room_event_router(self,
room: MatrixRoom, room: MatrixRoom,
event: RoomEvent) -> None: event: RoomEvent) -> None:
@@ -49,47 +99,34 @@ 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")
for callback_info in self._filters: # update join time if needed
if not isinstance(callback_info, self._FilterBasedCallback): joined_timestamp = await self._db._join_timestamp_get(room.room_id)
continue if joined_timestamp is None:
event_data = EventContext( joined_timestamp = await self._get_room_join_timestamp(room.room_id)
room=room, if joined_timestamp is not None:
event=event, await self._db._join_timestamp_set(room.room_id, joined_timestamp)
bot=self._matrix_bot else:
) return
try: # do not handle the event if it happened before we joined
if not await callback_info.filter(event_data): if event.server_timestamp < joined_timestamp:
continue return
except asyncio.CancelledError: # build the event context
raise event_context = EventContext(
except: room=room,
self._logger.error(traceback.format_exc()) event=event,
continue bot=self._matrix_bot
try: )
# dump argument types event_vars = ContextVars()
if callback_info.callback is None: self._context_vars_populator.sync_populate(event_context, event_vars)
self._logger.critical( await self._context_vars_populator.async_populate(event_context, event_vars)
f"Filter {repr(callback_info.filter)} has no callback. " # check all branches
f"`room` type is `{type(event_data.room)}`. " cor = self._event_branch_executor(event_context, event_vars)
f"`event` type is `{type(event_data.event)}`." if self._config.enable_multitasking_callbacks:
) t = asyncio.create_task(cor)
continue t.add_done_callback(self._multitasking_set.discard)
# create the coroutine self._multitasking_set.add(t)
cor = callback_info.callback(event_data) else:
# multitasking await cor
if self._config.enable_multitasking_callbacks:
t = asyncio.create_task(cor)
t.add_done_callback(self._multitasking_set.discard)
self._multitasking_set.add(t)
# no multitasking
else:
await cor
except asyncio.CancelledError:
raise
except:
self._logger.error(traceback.format_exc())
if callback_info.stop_matching:
break
async def _callback_autojoin(self, async def _callback_autojoin(self,
room: MatrixInvitedRoom, room: MatrixInvitedRoom,
@@ -120,6 +157,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)
@@ -131,37 +171,42 @@ 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._default_branch = Branch(
~SenderIsBotFilter() & (NewMessageFilter() | MessageReactionFilter()),
stop_on_callback=True
)
self._branches = [self._default_branch]
self._config: MatrixBotConfig | None = None self._config: MatrixBotConfig | None = None
self._client: AsyncClient | None = None self._client: AsyncClient | None = None
self._filters: list = [] self._filters: list = []
self._multitasking_set: set[asyncio.Task] = set() self._multitasking_set: set[asyncio.Task] = set()
def add_room_event_callback( def add_callback(self, filter: BaseEventFilter, callback: BranchCallback | None) -> None:
self, """Register a callback for default branch. Execution of the rest of
filter: BaseEventFilter, callbacks will not happen if this callback is executed. Use `add_branch`
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None, if you want to modify this behavior.
*,
stop_matching: bool = True) -> None:
"""
Add filter-based callback.
Args: Args:
- filter - filter to use for the callback - filter - filter for the callback
- callback - the callback that must be called if the filter matches - callback - callback to add
- stop_matching - whether to stop matching if the filter matches
""" """
callback_info = self._FilterBasedCallback( self._default_branch.add_callback(filter, callback)
filter=filter,
callback=callback,
stop_matching=stop_matching
)
self._filters.append(callback_info)
def add_branch(self, branch: Branch) -> None:
"""Register a branch in the callback system.
Args:
- branch - the branch to register
"""
if branch in self._branches:
raise RuntimeError("The branch is already added")
self._branches.append(branch)
async def setup(self, config: MatrixBotConfig, client: AsyncClient) -> None: async def setup(self, config: MatrixBotConfig, client: AsyncClient) -> None:
""" """

View File

@@ -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:
""" """

View File

@@ -2,6 +2,7 @@ import asyncio
import aiofiles import aiofiles
import logging import logging
import os import os
from typing import overload
import threading import threading
from uuid import uuid4 from uuid import uuid4
from pathlib import Path from pathlib import Path
@@ -149,7 +150,19 @@ class ClientDownloader:
cancel.set() cancel.set()
raise raise
async def download_file(self, @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, source: EventContext | Event,
*, *,
path: str | Path | None = None) -> Path | bytes: path: str | Path | None = None) -> Path | bytes:

View File

@@ -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")

View 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

View File

@@ -98,9 +98,10 @@ class ClientSender:
self._client = client self._client = client
self._uploader = uploader self._uploader = uploader
async def send_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,14 +118,14 @@ 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:
if self._config.auto_verify_all_known_devices: if self._config.auto_verify_all_known_devices:
if not Utils.verify_all_known_devices(self._client): if not Utils.verify_all_known_devices(self._client):
raise raise
return await self.send_content(room, content) return await self.content(room, content)
else: else:
raise raise
if type(result) is RoomSendResponse: if type(result) is RoomSendResponse:
@@ -134,11 +135,33 @@ class ClientSender:
else: else:
raise RuntimeError("Unknown error has occured", result) raise RuntimeError("Unknown error has occured", result)
async def send_text(self, async def reaction(self, room: MatrixRoom | str, message_id: str, reaction: str) -> str:
room: MatrixRoom | str, """
text: str, Add `reaction` to the message `message_id` in `room`.
*,
is_html: bool | None = None) -> str: Args:
- room - the room of `message_id`
- message_id - the message to add the `reaction` to
- reaction - emoji of reaction
Returns:
- `event_id` of added reaction on success
- Raises an exception on error
"""
content = {
"m.relates_to": {
"event_id": message_id,
"key": reaction,
"rel_type": "m.annotation"
}
}
return (await self.content(room, content, message_type="m.reaction")).event_id
async def text(self,
room: MatrixRoom | str,
text: str,
*,
is_html: bool | None = False) -> str:
""" """
Send text message to `room`. Send text message to `room`.
@@ -156,15 +179,15 @@ class ClientSender:
"msgtype": "m.text", "msgtype": "m.text",
**text_data **text_data
} }
return (await self.send_content(room, content)).event_id return (await self.content(room, content)).event_id
async def send_image(self, async def image(self,
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:
""" """
Send the image to `room`. Please note that formatted text is displayed Send the image to `room`. Please note that formatted text is displayed
incorrectly in some clients as of September 8th, 2026 incorrectly in some clients as of September 8th, 2026
@@ -213,16 +236,16 @@ class ClientSender:
"h": height "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, async def image_bytes(self,
room: MatrixRoom | str, room: MatrixRoom | str,
data: bytes, data: bytes,
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
incorrectly in some clients as of September 8th, 2026 incorrectly in some clients as of September 8th, 2026
@@ -276,16 +299,16 @@ class ClientSender:
"h": height "h": height
} }
} }
return (await self.send_content(room, content)).event_id return (await self.content(room, content)).event_id
async def send_video(self, async def video(self,
room: MatrixRoom | str, room: MatrixRoom | str,
path: Path | str, path: Path | str,
*, *,
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
incorrectly in some clients as of September 8th, 2026. Unknown video incorrectly in some clients as of September 8th, 2026. Unknown video
@@ -361,17 +384,17 @@ class ClientSender:
} }
} }
# send # send
return (await self.send_content(room, content)).event_id return (await self.content(room, content)).event_id
async def send_file(self, async def file(self,
room: MatrixRoom | str, room: MatrixRoom | str,
path: Path | str, path: Path | str,
*, *,
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
incorrectly in some clients as of September 8th, 2026. incorrectly in some clients as of September 8th, 2026.
@@ -422,17 +445,17 @@ class ClientSender:
"size": upload_result.filesize "size": upload_result.filesize
} }
} }
return (await self.send_content(room, content)).event_id return (await self.content(room, content)).event_id
async def send_file_bytes(self, async def file_bytes(self,
room: MatrixRoom | str, room: MatrixRoom | str,
data: bytes, data: bytes,
filename: str, filename: str,
*, *,
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`.
@@ -480,4 +503,4 @@ class ClientSender:
"size": upload_result.filesize "size": upload_result.filesize
} }
} }
return (await self.send_content(room, content)).event_id return (await self.content(room, content)).event_id

View File

@@ -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

198
src/mab/bot/_database.py Normal file
View File

@@ -0,0 +1,198 @@
import sqlite3
import aiosqlite
import logging
from typing import Any
from pathlib import Path
from ..types import MatrixBotConfig
class _Database:
"""Database interface"""
SCHEMA_VERSION = 4
"""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"
")"
),
(
"CREATE TABLE IF NOT EXISTS room_states("
"room_id TEXT UNIQUE ON CONFLICT REPLACE,"
"state TEXT"
")"
)
)
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 custom_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 custom_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 room_state_get(self, room_id: str) -> str | None:
"""Gets room state by its ID. Returns None if the state is not set."""
if self._conn is None:
raise RuntimeError("No connection exists")
async with self._conn.execute("SELECT state FROM room_states WHERE room_id=?",
(room_id,)) as cursor:
row = await cursor.fetchone()
if row is None:
return None
return row["state"]
async def room_state_set(self, room_id: str, state: str | None) -> str | None:
"""Sets room state in the database. Use `None` to remove it. Returns `state`."""
if self._conn is None:
raise RuntimeError("No connection exists")
if state is not None:
async with self._conn.execute("REPLACE INTO room_states(room_id, state) VALUES(?, ?)",
(room_id, state)) as cursor:
await cursor.fetchall()
self._logger.debug(f"Set room `{room_id}` state to `{state}`")
else:
async with self._conn.execute("DELETE FROM room_states WHERE room_id=?",
(room_id,)) as cursor:
await cursor.fetchall()
self._logger.debug(f"Removed state of the room `{room_id}` from the database")
return state
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}`")

View File

@@ -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

View File

@@ -8,10 +8,13 @@ from nio import AsyncClient, MatrixRoom, Event
from ..filters.base import BaseEventFilter from ..filters.base import BaseEventFilter
from ..types import * from ..types import *
from ..context import EventContext from ..context import EventContext
from ..context.vars import ContextVars
from ..branch import Branch, BranchCallback
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_downloader import ClientDownloader from ._client_downloader import ClientDownloader
from ._client_manager import ClientManager from ._client_manager import ClientManager
from ._client_uploader import ClientUploader from ._client_uploader import ClientUploader
@@ -24,19 +27,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_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)
@@ -45,27 +50,6 @@ class MatrixBot:
self._logger.error(f"Couldn't validate bot config: {e}") self._logger.error(f"Couldn't validate bot config: {e}")
raise raise
def add_callback(self,
filter: BaseEventFilter,
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None,
*,
stop_matching: bool = True) -> None:
"""
Add filter-based callback.
Args:
- filter - filter to use for the callback
- callback - the callback that must be called if the filter matches.
Use `None` to log the type of the Event that will
happen for specified filter.
- stop_matching - whether to stop matching if the filter matches
"""
self._callbacks.add_room_event_callback(
filter=filter,
callback=callback,
stop_matching=stop_matching
)
async def start(self) -> None: async def start(self) -> None:
""" """
Start client operation in background. This method can be called Start client operation in background. This method can be called
@@ -76,7 +60,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,
@@ -86,6 +70,10 @@ class MatrixBot:
self._config, self._config,
self._client_manager.get_client() self._client_manager.get_client()
) )
await self._client_room_operations.setup(
self._config,
self._client_manager.get_client()
)
await self._client_sender.setup( await self._client_sender.setup(
self._config, self._config,
self._client_manager.get_client(), self._client_manager.get_client(),
@@ -104,6 +92,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:
""" """
@@ -119,7 +108,18 @@ class MatrixBot:
finally: finally:
await self.stop() await self.stop()
def get_client(self) -> AsyncClient: @property
def database(self) -> _Database:
"""Get built-in Database."""
return self._database
@property
def callbacks(self) -> Callbacks:
"""Get Callbacks."""
return self._callbacks
@property
def client(self) -> AsyncClient:
""" """
Get AsyncClient. Get AsyncClient.
@@ -129,231 +129,19 @@ class MatrixBot:
""" """
return self._client_manager.get_client() return self._client_manager.get_client()
async def send_text(self, @property
room: MatrixRoom | str, def send(self) -> ClientSender:
text: str, """Get ClientSender that you should use to send messages."""
*, return self._client_sender
is_html: bool | None = None) -> str:
@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`. return self._client_room_operations
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
)
async def send_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 auto)
- 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
"""
return await self._client_sender.send_file(
room=room,
path=path,
filename=filename,
mime_type=mime_type,
text=text,
is_html=is_html,
timeout=timeout
)
async def send_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
- 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
"""
return await self._client_sender.send_file_bytes(
room=room,
data=data,
filename=filename,
mime_type=mime_type,
text=text,
is_html=is_html,
timeout=timeout
)
@overload
async def download_file(self,
source: EventContext | Event,
*,
path: str | Path) -> Path: ...
@overload
async def download_file(self,
source: EventContext | Event,
*,
path: None = None) -> bytes: ...
async def download_file(self,
source: EventContext | Event,
*,
path: str | Path | None = None) -> Path | bytes:
"""
Download the file from the event. Automatically dechiphers 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
"""
return await self._client_downloader.download_file(
source=source,
path=path
)

100
src/mab/branch/__init__.py Normal file
View File

@@ -0,0 +1,100 @@
import asyncio
import logging
import traceback
from typing import Self, Callable, Coroutine, Any
from ..filters import BaseEventFilter
from ..context import EventContext
from ..context.vars import ContextVars
type BranchCallback = Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]]
"""To shorten callback type hints"""
class _BranchStopException(Exception):
"""This exceptions is raised when the branch has called a callback and has
`stop_on_callback` set to `True`"""
def __init__(self):
super().__init__(
"Branch has called a callback and has stop_on_callback set to True"
)
class Branch:
async def _check_filter(self, filter: BaseEventFilter, ctx: EventContext, vars: ContextVars) -> bool:
"""Check if the filter returns True."""
try:
return await filter(ctx, vars)
except (asyncio.CancelledError, SystemExit, KeyboardInterrupt):
raise
except:
self._logger.critical(traceback.format_exc())
return False
def __init__(self, filter: BaseEventFilter, *, stop_on_callback: bool = True, log_level: int = logging.CRITICAL):
"""Create branch with specified filter.
Args:
- `filter` - filter that needs to be True in order this branch to
execute
- `stop_on_callback` - if this branch has any callbacks directly
added to this branch (not to subbranches) and these callbacks are
called, then `StopProcessingException` will be raised
"""
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}.{filter}")
self._logger.setLevel(log_level)
self._filter = filter
self._stop_on_callback = stop_on_callback
self._subbranches: list[tuple[BaseEventFilter, BranchCallback | None] | Branch] = []
def add_branch(self, branch: Branch) -> Self:
"""Add another branch as a subbranch."""
if branch in self._subbranches:
raise RuntimeError("This branch is already added")
self._subbranches.append(branch)
self._logger.debug("Added a new subbranch (branch)")
return self
def add_callback(self, filter: BaseEventFilter, callback: BranchCallback | None) -> Self:
"""Add a callback as a subbranch."""
self._subbranches.append((filter, callback))
self._logger.debug("Added a new subbranch (callback)")
return self
async def _execute(self, ctx: EventContext, vars: ContextVars) -> None:
"""Execute the branch. May raise `_BranchStopException`. Cancellable."""
# the branch must be executed only if its filter returns True
local_vars = ContextVars()
if not await self._check_filter(self._filter, ctx, local_vars):
return
vars = vars + local_vars
# execute every subbranch
for subbranch in self._subbranches:
callback_executed = False
try:
if isinstance(subbranch, Branch):
await subbranch._execute(ctx, vars)
else:
filter, callback = subbranch
local_vars = ContextVars()
if await self._check_filter(filter, ctx, local_vars):
callback_executed = True
if callback is None:
self._logger.critical(
f"Filter {repr(filter)} has no callback. "
f"`room` type is `{type(ctx.room)}`. "
f"`event` type is `{type(ctx.event)}`."
)
else:
await callback(ctx, vars + local_vars)
except (
asyncio.CancelledError,
SystemExit,
KeyboardInterrupt,
_BranchStopException
):
raise
except:
self._logger.critical(traceback.format_exc())
# stop execution
if self._stop_on_callback and callback_executed:
raise _BranchStopException()

View File

@@ -1,88 +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"""
CTX_FILE_SIZE = ContextDataKey[int]("CTX_FILE_SIZE")
"""Size of the file attached to the message (bytes)"""
CTX_FILE_MIME = ContextDataKey[str]("CTX_FILE_MIME")
"""Mime type of the file attached to the message"""
CTX_FILE_NAME = ContextDataKey[str]("CTX_FILE_NAME")
"""Name of the file attached to the message"""
#
# 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

View 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"""

View 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()

View File

@@ -0,0 +1,2 @@
from .types import *
from .keys import *

View 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`."""

View 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"""

View File

@@ -0,0 +1,3 @@
from .types import *
from .keys import *
from . import builders

View 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

View 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."""

View 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."""

View File

@@ -0,0 +1,3 @@
from .types import *
from .keys import *
from . import builders

View 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

View 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."""

View 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."""

View File

@@ -0,0 +1,3 @@
from .types import *
from .keys import *
from . import builders

View 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"]
)

View 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."""

View 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."""

View File

@@ -0,0 +1,5 @@
from .base import EventTypeFilter
from .body import *
from .message import *
from .room import *

View File

@@ -1,14 +1,12 @@
from abc import ABC, abstractmethod from abc import ABC
import logging import logging
from typing import Any, Type from typing import Type
from nio import AsyncClient
from nio import MatrixRoom, Event
from ..context import EventContext from ..context import EventContext
from ..context.vars import ContextVars
class BaseEventFilter(ABC): class BaseEventFilter(ABC):
"""Base class for all message filters""" """Base class for all message filters. Always returns True."""
_logger = logging.Logger("EventFilter") _logger = logging.Logger("EventFilter")
def __init__(self, **kwargs): def __init__(self, **kwargs):
@@ -66,37 +64,37 @@ class BaseEventFilter(ABC):
""" """
return str(self.__class__.__name__) 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 This method checks if the event from `ctx` matches filter-specific
filter operates according to its description. This method must not raise criteria. The filter may add variables to `vars`. If the callback will
exceptions. In case of exception it should log it using `self._logger` be called then these variables will be added to the final context
and return False variables. This function should return True if criteria is matched.
False must be returned otherwise.
Args: Args:
- context - event context; your derived classes may add variables - ctx - context to filter
to it (see `message.MessageTypeFilter` implementation - vars - variables object that may be modified by the filter
for reference)
Returns: Returns:
- True if the event satisfies this filter - True if the context matches the criteria
- False if the event does not satisfy this filter - False if the context does not match the criteria
""" """
return True return True
class EventTypeFilter(BaseEventFilter): 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): def __init__(self, type: Type, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
self._type = type self._type = type
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
return isinstance(context.event, self._type) return isinstance(ctx.event, self._type)
class CompoundEventFilter(BaseEventFilter): class CompoundEventFilter(BaseEventFilter):
"""Event filter that consists of multiple filters""" """Event filter that consists of multiple filters."""
OPERATOR_AND = "and" OPERATOR_AND = "and"
OPERATOR_OR = "or" OPERATOR_OR = "or"
OPERATOR_XOR = "xor" OPERATOR_XOR = "xor"
@@ -144,10 +142,10 @@ class CompoundEventFilter(BaseEventFilter):
expression = f"~{reprs[0]}" expression = f"~{reprs[0]}"
return f"({expression})" return f"({expression})"
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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: if self._operator == self.OPERATOR_AND:
return all(evaluated) return all(evaluated)
elif self._operator == self.OPERATOR_OR: elif self._operator == self.OPERATOR_OR:

View File

@@ -1,54 +1,43 @@
import re import re
import traceback import traceback
from .message import NewMessageFilter 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 ..context import EventContext
from nio import MatrixRoom, Event from ..context.vars import ContextVars
from ..context.vars.command import CTX_COMMAND, Command
class BodyExistsFilter(NewMessageFilter): class BodyExistsFilter(NewMessageFilter):
""" """
This filter returns True if all conditions are met: This filter returns True if all conditions are met:
1. `event` has attribute `body` 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 3. `event.body.strip()` evaluates to True
If this filter matches, you can access `event.body` and it stores If `event.body` value equals to filename (if it is present, of course) then
unformatted text of the message. this filter will return False by default. You may disable
`ignore_filename_in_body` to disable this feature.
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.
This filter will match any message that has `body` in it, including images, This filter will match any message that has `body` in it, including images,
videos, files, etc. videos, files, etc.
This filter sets `CTX_BODY` context variable.
""" """
def __init__(self, *, ignore_filename_in_body: bool = True, **kwargs): def __init__(self, *, ignore_filename_in_body: bool = True, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
self._ignore_filename_in_body = ignore_filename_in_body self._ignore_filename_in_body = ignore_filename_in_body
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
if not hasattr(context.event, "body"): if not hasattr(ctx.event, "body"):
return False return False
if not isinstance(context.event.body, str): # type: ignore if not isinstance(ctx.event.body, str): # type: ignore
return False return False
if not context.event.body.strip(): # type: ignore if not ctx.event.body.strip(): # type: ignore
return False return False
if self._ignore_filename_in_body: if self._ignore_filename_in_body:
content = context.event.source["content"] content = ctx.event.source["content"]
if "filename" in content and content["filename"] == context.event.body: # type: ignore if "filename" in content and content["filename"] == ctx.event.body: # type: ignore
return False return False
context[CTX_BODY] = context.event.body # type: ignore
return True return True
class BodyContainsFilter(BodyExistsFilter): class BodyContainsFilter(BodyExistsFilter):
@@ -71,10 +60,10 @@ class BodyContainsFilter(BodyExistsFilter):
self._any_case = any_case self._any_case = any_case
self._needle = needle self._needle = needle
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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: for n in self._needle:
if n in body: if n in body:
return True return True
@@ -100,10 +89,10 @@ class BodyStartsWithFilter(BodyExistsFilter):
self._any_case = any_case self._any_case = any_case
self._substring = substring self._substring = substring
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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: for s in self._substring:
if body.startswith(s): if body.startswith(s):
return True return True
@@ -129,10 +118,10 @@ class BodyEndsWithFilter(BodyExistsFilter):
self._any_case = any_case self._any_case = any_case
self._substring = substring self._substring = substring
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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: for s in self._substring:
if body.endswith(s): if body.endswith(s):
return True return True
@@ -155,10 +144,7 @@ class BodyCommandFilter(BodyExistsFilter):
store all verbs in lower case. This filter will not match any verbs that store all verbs in lower case. This filter will not match any verbs that
use mixed case of upper case. use mixed case of upper case.
This filter sets the following context variables: This filter sets CTX_COMMAND context variable if it returns True.
- `CTX_CMD_PREFIX` - prefix that was used
- `CTX_CMD_VERB` - verb that was used
- `CTX_CMD_ARGS` - arguments that were passed
""" """
def __init__(self, verbs: str | list[str], min_args: int = 0, max_args: int | None = None, prefix: str = "!", **kwargs): def __init__(self, verbs: str | list[str], min_args: int = 0, max_args: int | None = None, prefix: str = "!", **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
@@ -169,10 +155,10 @@ class BodyCommandFilter(BodyExistsFilter):
self._max_args = max_args self._max_args = max_args
self._prefix = prefix self._prefix = prefix
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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 args_count = len(parts) - 1
if args_count < self._min_args: if args_count < self._min_args:
return False return False
@@ -183,9 +169,11 @@ class BodyCommandFilter(BodyExistsFilter):
cmd = parts[0][len(self._prefix):].lower() cmd = parts[0][len(self._prefix):].lower()
for verb in self._verbs: for verb in self._verbs:
if cmd == verb: if cmd == verb:
context[CTX_CMD_PREFIX] = self._prefix vars[CTX_COMMAND] = Command(
context[CTX_CMD_VERB] = verb prefix=self._prefix,
context[CTX_CMD_ARGS] = parts[1:] verb=cmd,
args=parts[1:]
)
return True return True
return False return False
@@ -199,11 +187,11 @@ class BodyRegexFilter(BodyExistsFilter):
regex = re.compile(regex) regex = re.compile(regex)
self._regex = regex self._regex = regex
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
try: 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: except:
self._logger.error(traceback.format_exc()) self._logger.error(traceback.format_exc())
return False return False

View File

@@ -1,17 +1,11 @@
import traceback import traceback
from .base import BaseEventFilter, EventTypeFilter from .base import BaseEventFilter, EventTypeFilter
from ..types import MessageType from ..types import MessageType
from ..context import (EventContext,
CTX_MESSAGE_TYPE,
CTX_SENDER,
CTX_FILE_SIZE,
CTX_FILE_MIME,
CTX_FILE_NAME)
from nio import AsyncClient from ..context import EventContext
from nio import MatrixRoom, Event from ..context.vars import ContextVars
from nio import RedactionEvent from nio import RedactionEvent, ReactionEvent
class MessageTypeFilter(BaseEventFilter): class MessageTypeFilter(BaseEventFilter):
""" """
@@ -19,27 +13,24 @@ class MessageTypeFilter(BaseEventFilter):
images, videos, files, etc) based on `event.source["content"]["msgtype"]` images, videos, files, etc) based on `event.source["content"]["msgtype"]`
value. value.
`types` list is stored by reference so you may modify the behavior of this `types` list is copied so you can't modify behavior of this filter
filter dynamically. dynamically.
This filter sets `CTX_MESSAGE_TYPE` variable in the context.
""" """
def __init__(self, types: list[MessageType] | MessageType, **kwargs): def __init__(self, types: list[MessageType | str] | MessageType | str, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
if isinstance(types, MessageType): if not isinstance(types, list):
types = [types] 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: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
if "msgtype" not in context.event.source["content"]: if "msgtype" not in ctx.event.source["content"]:
return False return False
msgtype = context.event.source["content"]["msgtype"] msgtype = ctx.event.source["content"]["msgtype"]
if not msgtype in [t.value for t in self._types]: return msgtype in self._types
return False
context[CTX_MESSAGE_TYPE] = MessageType(msgtype)
return True
class NewMessageFilter(BaseEventFilter): class NewMessageFilter(BaseEventFilter):
""" """
@@ -50,10 +41,10 @@ class NewMessageFilter(BaseEventFilter):
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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): class EditedMessageFilter(BaseEventFilter):
""" """
@@ -63,10 +54,10 @@ class EditedMessageFilter(BaseEventFilter):
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
return "m.new_content" in context.event.source["content"] return "m.new_content" in ctx.event.source["content"]
class RedactedMessageFilter(EventTypeFilter): class RedactedMessageFilter(EventTypeFilter):
""" """
@@ -76,7 +67,7 @@ class RedactedMessageFilter(EventTypeFilter):
super().__init__(RedactionEvent, **kwargs) super().__init__(RedactionEvent, **kwargs)
raise NotImplementedError() raise NotImplementedError()
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
raise NotImplementedError() raise NotImplementedError()
class SenderIsFilter(BaseEventFilter): class SenderIsFilter(BaseEventFilter):
@@ -88,8 +79,6 @@ class SenderIsFilter(BaseEventFilter):
`senders` list is stored by reference so you can modify behavior of this `senders` list is stored by reference so you can modify behavior of this
filter dynamically. filter dynamically.
This filter sets `CTX_SENDER` variable in the context.
""" """
def __init__(self, sender: list[str] | str, *, any_case: bool = True, **kwargs): def __init__(self, sender: list[str] | str, *, any_case: bool = True, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
@@ -98,13 +87,12 @@ class SenderIsFilter(BaseEventFilter):
self._sender = sender self._sender = sender
self._any_case = any_case self._any_case = any_case
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False 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: for s in self._sender:
if sender == s: if sender == s:
context[CTX_SENDER] = sender
return True return True
return False return False
@@ -120,32 +108,53 @@ class SenderIsBotFilter(BaseEventFilter):
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
return context.bot.get_client().user_id == context.event.sender return ctx.bot.client.user_id == ctx.event.sender
class MessageHasFile(BaseEventFilter): class MessageHasFileFilter(BaseEventFilter):
""" """
This filter returns True if the message contains file that can be This filter returns True if the message contains file that can be
downloaded. downloaded.
This filter sets `CTX_FILE_NAME`, `CTX_FILE_SIZE` and `CTX_FILE_MIME`
variables in the context (if they are present in the).
""" """
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
content: dict | None = context.event.source.get("content") content: dict | None = ctx.event.source.get("content")
if content is None: if content is None:
return False return False
# `file` if encrypted, `url` if not encrypted # `file` if encrypted, `url` if not encrypted
if "file" not in content and "url" not in content: if "file" not in content and "url" not in content:
return False return False
context[CTX_FILE_NAME] = content.get("filename") or content.get("body") return True
context[CTX_FILE_SIZE] = content["info"].get("size")
context[CTX_FILE_MIME] = content["info"].get("mimetype") 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 return True

View File

@@ -1,6 +1,7 @@
from .base import BaseEventFilter from .base import BaseEventFilter
from ..context import EventContext, CTX_ROOM_ENCRYPTED from ..context import EventContext
from ..context.vars import ContextVars
class RoomEncryptedFilter(BaseEventFilter): class RoomEncryptedFilter(BaseEventFilter):
""" """
@@ -9,11 +10,27 @@ class RoomEncryptedFilter(BaseEventFilter):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
async def __call__(self, context: EventContext) -> bool: async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(context): if not await super().__call__(ctx, vars):
return False return False
try: try:
context[CTX_ROOM_ENCRYPTED] = context.room.encrypted return ctx.room.encrypted
return context.room.encrypted
except: except:
return False return False
class RoomStateFilter(BaseEventFilter):
"""
This filter returns True if the room state matches.
"""
def __init__(self, state: str | None | list[str | None], **kwargs):
super().__init__(**kwargs)
if isinstance(state, str) or state is None:
state = [state]
self._allowed_state = state
async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool:
if not await super().__call__(ctx, vars):
return False
state = await ctx.bot.database.room_state_get(ctx.room.room_id)
return state in self._allowed_state

View File

@@ -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"""
@@ -86,20 +83,3 @@ class MessageType(Enum):
AUDIO = "m.audio" AUDIO = "m.audio"
LOCATION = "m.location" LOCATION = "m.location"
VIDEO = "m.video" 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)})"