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
This commit is contained in:
2026-10-18 15:29:12 +03:00
parent afcd3f53f4
commit 17031500e9
17 changed files with 319 additions and 188 deletions

View File

@@ -15,7 +15,7 @@ from _environment import check_environment
async def on_text_message(ctx: EventContext) -> None: async def on_text_message(ctx: EventContext) -> 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, ctx[CTX_MESSAGE].body)
async def main() -> None: async def main() -> None:
"""Application entry point""" """Application entry point"""

View File

@@ -1,57 +1,8 @@
from . import bot from .types import MatrixBotConfig
from . import types
from .types import MatrixBotConfig, MessageType
from .context import *
from .bot import MatrixBot from .bot import MatrixBot
from .filters.base import * from .context import EventContext
from .filters.message import * from .context.keys import *
from .filters.body import *
__all__ = [ from .filters import *
# module names
"bot",
"types",
# .types
"MatrixBotConfig",
"MessageType",
# .context
"EventContext",
"CTX_BODY",
"CTX_MESSAGE_TYPE",
"CTX_SENDER",
"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

@@ -11,7 +11,7 @@ from nio.events.room_events import Event as RoomEvent
from ._storage import Storage from ._storage import Storage
from ..types import MatrixBotConfig from ..types import MatrixBotConfig
from ..context import EventContext from ..context import EventContext, ContextVarsPopulator
from ..filters.base import BaseEventFilter from ..filters.base import BaseEventFilter
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -49,14 +49,19 @@ 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")
# build the event context
event_data = EventContext(
room=room,
event=event,
bot=self._matrix_bot
)
self._context_vars_populator.sync_populate(event_data)
await self._context_vars_populator.async_populate(event_data)
# check all filters
for callback_info in self._filters: for callback_info in self._filters:
if not isinstance(callback_info, self._FilterBasedCallback): if not isinstance(callback_info, self._FilterBasedCallback):
continue continue
event_data = EventContext(
room=room,
event=event,
bot=self._matrix_bot
)
try: try:
if not await callback_info.filter(event_data): if not await callback_info.filter(event_data):
continue continue
@@ -135,6 +140,7 @@ class Callbacks:
self._logger = logging.getLogger("Callbacks") self._logger = logging.getLogger("Callbacks")
self._storage = storage self._storage = storage
self._matrix_bot = matrix_bot self._matrix_bot = matrix_bot
self._context_vars_populator = ContextVarsPopulator()
self._config: MatrixBotConfig | None = None self._config: MatrixBotConfig | None = None
self._client: AsyncClient | None = None self._client: AsyncClient | None = None

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

155
src/mab/context/__init__.py Normal file
View File

@@ -0,0 +1,155 @@
from dataclasses import dataclass
from nio import MatrixRoom, Event
from types import ModuleType
from typing import TYPE_CHECKING, Any, Callable, Coroutine
import inspect
import importlib
import pkgutil
import traceback
import mab.context.vars
if TYPE_CHECKING:
from ..bot import MatrixBot
from .keys import _ContextDataKey
@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
class ContextVarsPopulator:
"""This class populates context variables using dynamically detected
builders.
What is a builder?
1. Synchronous or asynchronous function
2. Takes exactly one positional argument of type `EventContext`
3. A member of module `mab.context.vars.<subpackage_name>.builders`
4. `mab.context.vars.<subpackage_name>.__init__` exists
4. Function name starts with `build_`
5. Returns `None`
Builders are looked for dynamically because it drastically decreases amount
of boilerplate code and makes builder definition a kind of single source of
truth.
"""
@staticmethod
def _is_builder_signature_valid(builder) -> bool:
"""Check if builder signature is valid.
Args:
- builder - function to check
Returns:
- True if the signature is valid
"""
params = inspect.signature(builder).parameters
if len(params) != 1:
return False
p = tuple(params.values())[0]
return p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
@staticmethod
def _get_builder_modules() -> list[ModuleType]:
"""Get all known modules for glob `mab.context.vars.*.builders`.
Imports modules during the search."""
walk_result = pkgutil.walk_packages(
mab.context.vars.__path__,
f"{mab.context.vars.__name__}."
)
walk_result = [i for i in walk_result if i.name.endswith(".builders") and not i.ispkg]
builder_modules = []
for module_info in walk_result:
builder_modules.append(
importlib.import_module(module_info.name)
)
return builder_modules
@staticmethod
def _get_builders_of_module(module: ModuleType) -> tuple[list, list]:
"""Get all builders of the module.
Returns:
- a tuple of:
0. list of sync builders
1. list of async builders
"""
predicates = [
lambda x: inspect.isfunction(x) and not inspect.iscoroutinefunction(x),
lambda x: inspect.iscoroutinefunction(x)
]
result = [[], []]
for i, predicate in enumerate(predicates):
members = inspect.getmembers(module, predicate)
result[i] = [m[1] for m in members if m[0].startswith("build_")]
return (result[0], result[1])
def __init__(self) -> None:
"""Initialize the populator. Builders are looked up during this
function call."""
self._modules = self._get_builder_modules()
self._sync_builders: list[Callable[[EventContext], None]] = []
self._async_builders: list[Callable[[EventContext], Coroutine[None, None, None]]] = []
for m in self._modules:
sync_builders, async_builders = self._get_builders_of_module(m)
self._sync_builders += sync_builders
self._async_builders += async_builders
def sync_populate(self, context: EventContext) -> None:
"""Populate context variables using sync builders.
Args:
- context - context to set variables in
"""
for builder in self._sync_builders:
try:
builder(context)
except:
traceback.print_exc()
async def async_populate(self, context: EventContext) -> None:
"""Populate context variables using async builders.
Args:
- context - context to set variables in
"""
for builder in self._async_builders:
try:
await builder(context)
except:
traceback.print_exc()

31
src/mab/context/keys.py Normal file
View File

@@ -0,0 +1,31 @@
#
# IMPORTS FOR VARIABLE VALUE TYPES
#
from .vars.message.types import Message
#
# VARIABLE KEY TYPE
#
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)})"
#
# VARIABLE KEYS
#
CTX_MESSAGE = _ContextDataKey[Message]("CTX_MESSAGE")
"""Minimum set of fields required to create a message"""

View File

View File

View File

@@ -0,0 +1,41 @@
"""
This file is dynamically analyzed when `mab` is imported. All functions with
names starting with `build_` are added to the list of so called "builders".
Builder is a function that tries to add new context variable to the
`EventContext`. One builder can add only one context variable.
When a matrix event arrives and it is being prepared for routing through the
filters system, it is being passed to all existing builders as their one and
only argument - `context`.
The builder may return:
1. `None`. In this case nothing happens. The builder should return `None` if it
is unable to create new context variable.
2. `tuple[ContextDataKey[T], T]`. In this case the returned values will be used
by routing system to add a new variable to the context. The first element is
used as a key, the second element is used as a value.
IMPORTANT: You should not modify the `context`! You should return the tuple
described above if you want to add a variable!
"""
from ... import EventContext
from ...keys import *
from .types import Message
async def build_message(context: EventContext) -> None:
source = context.event.source
if "content" not in source:
return None
content: dict = source["content"]
if "body" not in content or "msgtype" not in content:
return None
res = Message(
body=content.get("body", "Missing `body`"),
format=content.get("format"),
formatted_body=content.get("formatted_body"),
msgtype=content.get("msgtype", "Missing `msgtype`")
)
context[CTX_MESSAGE] = res

View File

@@ -0,0 +1,17 @@
from pydantic import BaseModel
class Message(BaseModel):
"""This model defines the most important fields of the message. Custom
fields must be accessed using raw matrix-nio event."""
msgtype: str
"""It identifies the type of message being sent"""
body: str
"""Unformatted (or fallback) body of the message"""
format: str | None
"""Format of the formatted_body content"""
formatted_body: str | None
"""Formatted body of the message, present if `format` is not None"""

View File

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

View File

@@ -2,7 +2,7 @@ from abc import ABC
import logging import logging
from typing import Type from typing import Type
from ..context import EventContext, CTX_SENDER from ..context import EventContext
class BaseEventFilter(ABC): class BaseEventFilter(ABC):
"""Base class for all message filters""" """Base class for all message filters"""
@@ -79,7 +79,6 @@ class BaseEventFilter(ABC):
- True if the event satisfies this filter - True if the event satisfies this filter
- False if the event does not satisfy this filter - False if the event does not satisfy this filter
""" """
context[CTX_SENDER] = context.event.sender
return True return True
class EventTypeFilter(BaseEventFilter): class EventTypeFilter(BaseEventFilter):

View File

@@ -2,12 +2,6 @@ import re
import traceback import traceback
from .message import NewMessageFilter from .message import NewMessageFilter
from ..context import EventContext from ..context import EventContext
from ..context import (
CTX_BODY,
CTX_CMD_PREFIX,
CTX_CMD_VERB,
CTX_CMD_ARGS
)
class BodyExistsFilter(NewMessageFilter): class BodyExistsFilter(NewMessageFilter):
""" """
@@ -45,7 +39,6 @@ class BodyExistsFilter(NewMessageFilter):
content = context.event.source["content"] content = context.event.source["content"]
if "filename" in content and content["filename"] == context.event.body: # type: ignore if "filename" in content and content["filename"] == context.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):
@@ -180,9 +173,6 @@ 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
context[CTX_CMD_VERB] = verb
context[CTX_CMD_ARGS] = parts[1:]
return True return True
return False return False

View File

@@ -1,11 +1,7 @@
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, from ..context import EventContext
CTX_MESSAGE_TYPE,
CTX_FILE_SIZE,
CTX_FILE_MIME,
CTX_FILE_NAME)
from nio import RedactionEvent from nio import RedactionEvent
@@ -34,7 +30,6 @@ class MessageTypeFilter(BaseEventFilter):
msgtype = context.event.source["content"]["msgtype"] msgtype = context.event.source["content"]["msgtype"]
if not msgtype in [t.value for t in self._types]: if not msgtype in [t.value for t in self._types]:
return False return False
context[CTX_MESSAGE_TYPE] = MessageType(msgtype)
return True return True
class NewMessageFilter(BaseEventFilter): class NewMessageFilter(BaseEventFilter):
@@ -140,7 +135,4 @@ class MessageHasFile(BaseEventFilter):
# `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")
context[CTX_FILE_SIZE] = content["info"].get("size")
context[CTX_FILE_MIME] = content["info"].get("mimetype")
return True return True

View File

@@ -1,6 +1,6 @@
from .base import BaseEventFilter from .base import BaseEventFilter
from ..context import EventContext, CTX_ROOM_ENCRYPTED from ..context import EventContext
class RoomEncryptedFilter(BaseEventFilter): class RoomEncryptedFilter(BaseEventFilter):
""" """
@@ -13,7 +13,6 @@ class RoomEncryptedFilter(BaseEventFilter):
if not await super().__call__(context): if not await super().__call__(context):
return False return False
try: try:
context[CTX_ROOM_ENCRYPTED] = context.room.encrypted
return context.room.encrypted return context.room.encrypted
except: except:
return False return False

50
src/mab/models/file.py Normal file
View File

@@ -0,0 +1,50 @@
from pydantic import BaseModel
class JwkKey(BaseModel):
"""Encryption key data."""
alg: str
"""Algorithm. Must be A256CTR."""
ext: bool
"""Extractable. Must be true."""
k: str
"""The key, encoded as URL-safe unpadded Base64."""
key_ops: list[str]
"""Key operations. Must at least contain encrypt and decrypt."""
kty: str
"""Key type. Must be oct."""
class Encryption(BaseModel):
"""Encryption information for files. `url` is stored in `File` model!"""
hashes: list[str]
"""A map from an algorithm name to a hash of the ciphertext."""
iv: list[str]
"""The 128-bit unique counter block used by AES-CTR, encoded as unpadded
Base64."""
key: JwkKey
"""A JSON Web Key object."""
v: str
"""Version of encrypted attachments's protocol. Must be v2."""
class File(BaseModel):
"""This model defines both encrypted and non-encrypted file."""
encryption: Encryption | None
"""Encryption data if encryption is used."""
url: str
"""URL of the file. Must start with `mxc://` if encrypted."""
filename: str | None
"""The name of the file. May be absent."""

View File

@@ -86,20 +86,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)})"