1 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
18 changed files with 660 additions and 232 deletions

View File

@@ -4,6 +4,11 @@
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.
> [!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
The library supports the following features:
@@ -23,7 +28,7 @@ install the latest stable version of the library:
```bash
apt install libmagic1-dev libolm-dev
python -m pip install git+https://git.tyukalov.su/nikita/mab@v0.7.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`
@@ -58,7 +63,6 @@ of creating a bot:
import asyncio
from mab import *
# Run until Ctrl+C
async def main():
# Create the config for the bot object
bot_config = MatrixBotConfig(
@@ -76,16 +80,10 @@ async def main():
asyncio.run(main())
```
To reduce amount of `if`s in your code, **filters** concept is introduced. When
To reduce amount of `if`s in your code, **filter** concept is introduced. When
you add a callback to the instance of the bot, you also provide a filter object.
Filters are created like that:
```python
# Filter that is True for new message
new_message = NewMessageFilter()
# Filter that is True for message sent not by the user we are logged in as
sent_by_user = ~SenderIsBotFilter()
# Filter that is True for users in `admins_list`
admins_list = [
"@server-admin:matrix.example.org",
@@ -113,11 +111,34 @@ admin_list = [
]
# Define the filter
the_filter = (
MessageReactionFilter()
& ~SenderIsBotFilter()
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

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

@@ -131,9 +131,8 @@ async def main() -> None:
on_args_command: BodyCommandFilter("args", min_args=1, max_args=5),
}
for callback, filter in COMMANDS.items():
f = ~SenderIsBotFilter() & filter
bot.add_callback(f, callback)
bot.add_callback(~SenderIsBotFilter() & NewMessageFilter(), invalid_usage)
bot.callbacks.add_callback(filter, callback)
bot.callbacks.add_callback(BodyExistsFilter(), invalid_usage)
# run until Ctrl+C
try:

View File

@@ -29,9 +29,7 @@ async def main() -> None:
storage_directory="session_storage"
)
bot = MatrixBot(config)
bot.add_callback(
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
on_text_message)
bot.callbacks.add_callback(MessageTypeFilter(MessageType.TEXT), on_text_message)
# run until Ctrl+C
try:

View File

@@ -85,12 +85,8 @@ async def main() -> None:
storage_directory="session_storage"
)
bot = MatrixBot(config)
bot.add_callback(
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
on_text_message)
bot.add_callback(
~SenderIsBotFilter() & MessageHasFileFilter() & NewMessageFilter(),
on_file_message)
bot.callbacks.add_callback(MessageTypeFilter(MessageType.TEXT), on_text_message)
bot.callbacks.add_callback(MessageHasFileFilter(), on_file_message)
# run until Ctrl+C
try:

View File

@@ -99,26 +99,12 @@ async def main() -> None:
max_args=3
)
# callback for message that
# 1. are sent not by this bot
# 2. do match the command filter
bot.add_callback(
~SenderIsBotFilter() & command_filter,
on_gen_command)
# callback for message that match the command filter
bot.callbacks.add_callback(command_filter, on_gen_command)
# callback for new image message
bot.add_callback(
~SenderIsBotFilter() & MessageTypeFilter(MessageType.IMAGE) & NewMessageFilter(),
on_image
)
# callback for message that
# 1. are sent not by this bot
# 2. are new messages (not edits)
bot.add_callback(
~SenderIsBotFilter() & BodyExistsFilter() & NewMessageFilter(),
on_wrong_message
)
bot.callbacks.add_callback(MessageTypeFilter(MessageType.IMAGE), on_image)
# callback for message that contain body
bot.callbacks.add_callback(BodyExistsFilter(), on_wrong_message)
# run until Ctrl+C
try:

View File

@@ -16,10 +16,10 @@ from _environment import check_environment
async def bump_count(bot: MatrixBot) -> int:
"""Bump count of reactions processed and return new value. Uses bot's
database for storage."""
val = await bot.load_value("reactions_processed")
val = await bot.database.custom_get("reactions_processed")
val = 0 if val is None else int.from_bytes(val)
val += 1
await bot.save_value("reactions_processed", val.to_bytes(8))
await bot.database.custom_set("reactions_processed", val.to_bytes(8))
return val
async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None:
@@ -61,15 +61,9 @@ async def main() -> None:
storage_directory="session_storage"
)
bot = MatrixBot(config)
bot.add_callback(
~SenderIsBotFilter() & MessageReactionFilter(reaction=["❤️", "👍"]),
on_specific_reaction)
bot.add_callback(
~SenderIsBotFilter() & MessageReactionFilter(),
on_reaction)
bot.add_callback(
~SenderIsBotFilter() & NewMessageFilter(),
on_message)
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:

View File

@@ -144,89 +144,53 @@ async def main() -> None:
bot = MatrixBot(config)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("create")
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("create"),
on_cmd_create
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("leave")
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("leave"),
on_cmd_leave
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("forget")
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("forget"),
on_cmd_forget
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("join", min_args=1)
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("join", min_args=1),
on_cmd_join
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("invite", min_args=2)
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("invite", min_args=2),
on_cmd_invite
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("kick", min_args=2)
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("kick", min_args=2),
on_cmd_kick
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("ban", min_args=2)
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("ban", min_args=2),
on_cmd_ban
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("unban", min_args=2)
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("unban", min_args=2),
on_cmd_unban
)
#
fitler = (
~SenderIsBotFilter()
& BodyCommandFilter("members", min_args=1)
)
bot.add_callback(
fitler,
bot.callbacks.add_callback(
BodyCommandFilter("members", min_args=1),
on_cmd_members
)
#
bot.add_callback(
~SenderIsBotFilter() & NewMessageFilter() & BodyExistsFilter(),
bot.callbacks.add_callback(
BodyExistsFilter(),
on_help_message
)

View File

@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "mab"
version = "0.7.1"
version = "0.8.0"
authors = [
{ name = "Tyukalov Nikita", email = "nikita@tyukalov.su" }
]

View File

@@ -9,6 +9,9 @@ from .filters import *
from .context import EventContext
from .context.vars import ContextVars
# Branches
from .branch import Branch, BranchCallback
# Context variables
from .context.vars.command import *
from .context.vars.message import *

View File

@@ -16,6 +16,9 @@ from ..context import EventContext
from ..context.vars import ContextVars, ContextVarsPopulator
from ..filters.base import BaseEventFilter
from ..branch import Branch, BranchCallback, _BranchStopException
from ..filters import SenderIsBotFilter, NewMessageFilter, MessageReactionFilter
if TYPE_CHECKING:
from .bot import MatrixBot
@@ -52,7 +55,7 @@ class Callbacks:
if not isinstance(resp, SyncResponse):
continue
for room_id in resp.rooms.leave:
await self._db.join_timestamp_remove(room_id)
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."""
@@ -79,6 +82,15 @@ class Callbacks:
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,
room: MatrixRoom,
event: RoomEvent) -> None:
@@ -88,11 +100,11 @@ class Callbacks:
if self._config is None or self._client is None:
raise RuntimeError("Callbacks were not set up")
# update join time if needed
joined_timestamp = await self._db.join_timestamp_get(room.room_id)
joined_timestamp = await self._db._join_timestamp_get(room.room_id)
if joined_timestamp is None:
joined_timestamp = await self._get_room_join_timestamp(room.room_id)
if joined_timestamp is not None:
await self._db.join_timestamp_set(room.room_id, joined_timestamp)
await self._db._join_timestamp_set(room.room_id, joined_timestamp)
else:
return
# do not handle the event if it happened before we joined
@@ -107,48 +119,14 @@ class Callbacks:
event_vars = ContextVars()
self._context_vars_populator.sync_populate(event_context, event_vars)
await self._context_vars_populator.async_populate(event_context, event_vars)
# check all filters
for callback_info in self._filters:
if not isinstance(callback_info, self._FilterBasedCallback):
continue
local_event_vars = ContextVars()
try:
if not await callback_info.filter(event_context, local_event_vars):
continue
except asyncio.CancelledError:
raise
except:
self._logger.error(traceback.format_exc())
continue
try:
# dump argument types
if callback_info.callback is None:
self._logger.critical(
f"Filter {repr(callback_info.filter)} has no callback. "
f"`room` type is `{type(event_context.room)}`. "
f"`event` type is `{type(event_context.event)}`."
)
continue
# create the coroutine
cor = callback_info.callback(
event_context,
event_vars + local_event_vars
)
# multitasking
if self._config.enable_multitasking_callbacks:
t = asyncio.create_task(cor)
t.add_done_callback(self._multitasking_set.discard)
self._multitasking_set.add(t)
# no multitasking
else:
await cor
except asyncio.CancelledError:
raise
except:
self._logger.error(traceback.format_exc())
if callback_info.stop_matching:
break
# check all branches
cor = self._event_branch_executor(event_context, event_vars)
if self._config.enable_multitasking_callbacks:
t = asyncio.create_task(cor)
t.add_done_callback(self._multitasking_set.discard)
self._multitasking_set.add(t)
else:
await cor
async def _callback_autojoin(self,
room: MatrixInvitedRoom,
@@ -198,33 +176,37 @@ class Callbacks:
self._db = db
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._client: AsyncClient | None = None
self._filters: list = []
self._multitasking_set: set[asyncio.Task] = set()
def add_room_event_callback(
self,
filter: BaseEventFilter,
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
*,
stop_matching: bool = True) -> None:
"""
Add filter-based callback.
def add_callback(self, filter: BaseEventFilter, callback: BranchCallback | None) -> None:
"""Register a callback for default branch. Execution of the rest of
callbacks will not happen if this callback is executed. Use `add_branch`
if you want to modify this behavior.
Args:
- filter - filter to use for the callback
- callback - the callback that must be called if the filter matches
- stop_matching - whether to stop matching if the filter matches
- filter - filter for the callback
- callback - callback to add
"""
callback_info = self._FilterBasedCallback(
filter=filter,
callback=callback,
stop_matching=stop_matching
)
self._filters.append(callback_info)
self._default_branch.add_callback(filter, callback)
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:
"""

View File

@@ -37,8 +37,8 @@ class ClientAuth:
if self._full_matrix_username is None:
raise RuntimeError("ClientAuth is not set up")
self._logger.debug("Trying to log in using session data from disk...")
access_token = await self._db.prop_get("access_token")
device_id = await self._db.prop_get("device_id")
access_token = await self._db._prop_get("access_token")
device_id = await self._db._prop_get("device_id")
if not isinstance(access_token, str) or not isinstance(device_id, str):
self._logger.error("Can't read session data from database")
raise RuntimeError("Can't read session data from database")
@@ -81,8 +81,8 @@ class ClientAuth:
result = await client.login(password=password)
if type(result) is LoginResponse:
self._logger.debug("Logged in using password")
await self._db.prop_set("access_token", result.access_token)
await self._db.prop_set("device_id", result.device_id)
await self._db._prop_set("access_token", result.access_token)
await self._db._prop_set("device_id", result.device_id)
elif type(result) is LoginError:
self._logger.error(f"Can't log in using password: '{result.message}'")
raise RuntimeError(result.message)

View File

@@ -26,7 +26,7 @@ class ClientManager:
await self._client.close()
self._logger.debug("Dumping 'next_batch' value...")
if self._last_next_batch is not None:
await self._db.prop_set("next_batch", self._last_next_batch)
await self._db._prop_set("next_batch", self._last_next_batch)
async def _cancellable_sync_forever(self, *args, **kwargs) -> Any:
"""
@@ -73,7 +73,7 @@ class ClientManager:
self._logger.debug("Syncing forever...")
await self._cancellable_sync_forever(
timeout=self._config.client_sync_period_ms,
since=(await self._db.prop_get("next_batch")),
since=(await self._db._prop_get("next_batch")),
full_state=True
)
@@ -90,7 +90,7 @@ class ClientManager:
delta_time = current_time - self._last_next_batch_write_time
if delta_time >= self._config.client_next_batch_dump_period_s:
try:
await self._db.prop_set("next_batch", self._last_next_batch)
await self._db._prop_set("next_batch", self._last_next_batch)
self._last_next_batch_write_time = current_time
except:
self._logger.error(traceback.format_exc())

View File

@@ -9,7 +9,7 @@ from ..types import MatrixBotConfig
class _Database:
"""Database interface"""
SCHEMA_VERSION = 3
SCHEMA_VERSION = 4
"""Version of the database schema"""
async def _create_tables(self) -> None:
@@ -34,6 +34,12 @@ class _Database:
"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")
@@ -48,7 +54,7 @@ class _Database:
self._logger = logging.getLogger(f"mab.{self.__class__.__name__}")
self._logger.setLevel(log_level)
async def setup(self, config: MatrixBotConfig):
async def _setup(self, config: MatrixBotConfig):
"""Setup the database connection."""
if self._conn is not None:
raise RuntimeError("The connection already exists")
@@ -65,7 +71,7 @@ class _Database:
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
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")
@@ -77,9 +83,9 @@ class _Database:
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)
await self._prop_set("schema_version", self.SCHEMA_VERSION)
async def close(self) -> None:
async def _close(self) -> None:
"""Close the database connection."""
if self._conn is None:
raise RuntimeError("No connection exists")
@@ -88,7 +94,7 @@ class _Database:
self._conn = None
self._logger.debug(f"Database connection is closed")
async def prop_get(self, name: str) -> Any | None:
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")
@@ -99,7 +105,7 @@ class _Database:
return None
return row["value"]
async def prop_set(self, name: str, value: Any) -> None:
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")
@@ -108,7 +114,7 @@ class _Database:
await cursor.fetchall()
self._logger.debug(f"Updated property `{name}`")
async def user_kv_get(self, key: str) -> bytes | None:
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:
@@ -120,7 +126,7 @@ class _Database:
return None
return row["value"]
async def user_kv_set(self, key: str, value: bytes | None) -> bytes | None:
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:
@@ -137,7 +143,34 @@ class _Database:
self._logger.debug(f"Removed user key-value `{key}`")
return value
async def join_timestamp_get(self, room_id: str) -> int | None:
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")
@@ -147,7 +180,7 @@ class _Database:
return None
return row["timestamp"]
async def join_timestamp_set(self, room_id: str, timestamp: int) -> None:
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")
@@ -156,7 +189,7 @@ class _Database:
await cursor.fetchall()
self._logger.debug(f"Updated join timestamp for room `{room_id}`")
async def join_timestamp_remove(self, room_id: str) -> None:
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")

View File

@@ -9,6 +9,7 @@ from ..filters.base import BaseEventFilter
from ..types import *
from ..context import EventContext
from ..context.vars import ContextVars
from ..branch import Branch, BranchCallback
from ._validation import Validator
from ._database import _Database
@@ -49,27 +50,6 @@ class MatrixBot:
self._logger.error(f"Couldn't validate bot config: {e}")
raise
def add_callback(self,
filter: BaseEventFilter,
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
*,
stop_matching: bool = True) -> None:
"""
Add filter-based callback.
Args:
- filter - filter to use for the callback
- callback - the callback that must be called if the filter matches.
Use `None` to log the type of the Event that will
happen for specified filter.
- stop_matching - whether to stop matching if the filter matches
"""
self._callbacks.add_room_event_callback(
filter=filter,
callback=callback,
stop_matching=stop_matching
)
async def start(self) -> None:
"""
Start client operation in background. This method can be called
@@ -80,7 +60,7 @@ class MatrixBot:
raise RuntimeError("The bot was already started")
self._was_started = True
await self._client_manager.setup(self._config)
await self._database.setup(self._config)
await self._database._setup(self._config)
await self._client_auth.setup(self._config)
await self._client_uploader.setup(
self._config,
@@ -112,7 +92,7 @@ class MatrixBot:
bot to completely stop.
"""
await self._client_manager.stop()
await self._database.close()
await self._database._close()
async def run(self) -> None:
"""
@@ -128,23 +108,15 @@ class MatrixBot:
finally:
await self.stop()
async def save_value(self, key: str, value: bytes | None) -> bytes | None:
"""Save key-value pair to the database. Save `None` to remove the key.
Returns `value`.
@property
def database(self) -> _Database:
"""Get built-in Database."""
return self._database
Please use this feature for simple bots only. Prefer your own database
for higher efficiency.
"""
return await self._database.user_kv_set(key, value)
async def load_value(self, key: str) -> bytes | None:
"""Load key-value pair from the database. Returns `None` if the key
does not exist.
Please use this feature for simple bots only. Prefer your own database
for higher efficiency.
"""
return await self._database.user_kv_get(key)
@property
def callbacks(self) -> Callbacks:
"""Get Callbacks."""
return self._callbacks
@property
def client(self) -> AsyncClient:

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

@@ -17,3 +17,20 @@ class RoomEncryptedFilter(BaseEventFilter):
return ctx.room.encrypted
except:
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