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
This commit is contained in:
@@ -13,9 +13,9 @@ from mab import *
|
||||
|
||||
from _environment import check_environment
|
||||
|
||||
async def on_text_message(ctx: EventContext) -> None:
|
||||
async def on_text_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||
"""This callback is called when a text message arrives."""
|
||||
await ctx.bot.send.text(ctx.room, ctx[CTX_MESSAGE].body)
|
||||
await ctx.bot.send.text(ctx.room, vars[CTX_MESSAGE].body)
|
||||
|
||||
async def main() -> None:
|
||||
"""Application entry point"""
|
||||
|
||||
@@ -24,7 +24,10 @@ async def on_file_message(ctx: EventContext) -> None:
|
||||
"""This callback is called when a file arrives."""
|
||||
sha = hashlib.sha256()
|
||||
does_temp_exist = False
|
||||
if ctx[CTX_FILE].size > 1_000_000:
|
||||
file = ctx[CTX_FILE]
|
||||
if not file.size:
|
||||
file.size = 0
|
||||
if file.size > 1_000_000:
|
||||
await ctx.bot.send.text(
|
||||
ctx.room,
|
||||
"The file is larger than 1 MB, downloading to filesystem"
|
||||
|
||||
@@ -22,7 +22,7 @@ async def on_gen_command(data: EventContext) -> None:
|
||||
"""This callback is called when `!gen R G B` command is received."""
|
||||
# convert R, G and B to floats
|
||||
try:
|
||||
r, g, b = [float(v) for v in data[CTX_CMD_ARGS]]
|
||||
r, g, b = [float(f) for f in data[CTX_MESSAGE].body.split()[1:]]
|
||||
except:
|
||||
await data.bot.send.text(data.room, "Invalid arguments")
|
||||
return
|
||||
|
||||
@@ -3,6 +3,7 @@ from .types import MatrixBotConfig
|
||||
from .bot import MatrixBot
|
||||
|
||||
from .context import EventContext
|
||||
from .context.vars import ContextVars
|
||||
from .context.keys import *
|
||||
|
||||
from .filters import *
|
||||
@@ -11,7 +11,8 @@ from nio.events.room_events import Event as RoomEvent
|
||||
|
||||
from ._storage import Storage
|
||||
from ..types import MatrixBotConfig
|
||||
from ..context import EventContext, ContextVarsPopulator
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars, ContextVarsPopulator
|
||||
from ..filters.base import BaseEventFilter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -32,7 +33,7 @@ class Callbacks:
|
||||
filter: BaseEventFilter
|
||||
"""Filter to use for matching"""
|
||||
|
||||
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None
|
||||
"""Callback that will be called if the filter matches"""
|
||||
|
||||
stop_matching: bool
|
||||
@@ -50,20 +51,21 @@ class Callbacks:
|
||||
if self._config is None or self._client is None:
|
||||
raise RuntimeError("Callbacks were not set up")
|
||||
# build the event context
|
||||
event_data = EventContext(
|
||||
event_context = 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)
|
||||
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
|
||||
try:
|
||||
if not await callback_info.filter(event_data):
|
||||
if not await callback_info.filter(event_context):
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
@@ -75,12 +77,12 @@ class Callbacks:
|
||||
if callback_info.callback is None:
|
||||
self._logger.critical(
|
||||
f"Filter {repr(callback_info.filter)} has no callback. "
|
||||
f"`room` type is `{type(event_data.room)}`. "
|
||||
f"`event` type is `{type(event_data.event)}`."
|
||||
f"`room` type is `{type(event_context.room)}`. "
|
||||
f"`event` type is `{type(event_context.event)}`."
|
||||
)
|
||||
continue
|
||||
# create the coroutine
|
||||
cor = callback_info.callback(event_data)
|
||||
cor = callback_info.callback(event_context, event_vars)
|
||||
# multitasking
|
||||
if self._config.enable_multitasking_callbacks:
|
||||
t = asyncio.create_task(cor)
|
||||
@@ -150,7 +152,7 @@ class Callbacks:
|
||||
def add_room_event_callback(
|
||||
self,
|
||||
filter: BaseEventFilter,
|
||||
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None,
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
|
||||
*,
|
||||
stop_matching: bool = True) -> None:
|
||||
"""
|
||||
|
||||
@@ -8,6 +8,7 @@ from nio import AsyncClient, MatrixRoom, Event
|
||||
from ..filters.base import BaseEventFilter
|
||||
from ..types import *
|
||||
from ..context import EventContext
|
||||
from ..context.vars import ContextVars
|
||||
|
||||
from ._validation import Validator
|
||||
from ._storage import Storage
|
||||
@@ -49,7 +50,7 @@ class MatrixBot:
|
||||
|
||||
def add_callback(self,
|
||||
filter: BaseEventFilter,
|
||||
callback: Callable[[EventContext], Coroutine[Any, Any, None]] | None,
|
||||
callback: Callable[[EventContext, ContextVars], Coroutine[Any, Any, None]] | None,
|
||||
*,
|
||||
stop_matching: bool = True) -> None:
|
||||
"""
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
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
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from ..bot import MatrixBot
|
||||
from .keys import _ContextDataKey
|
||||
|
||||
@dataclass
|
||||
class EventContext:
|
||||
@@ -23,133 +16,3 @@ class EventContext:
|
||||
|
||||
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()
|
||||
@@ -2,7 +2,6 @@
|
||||
# IMPORTS FOR VARIABLE VALUE TYPES
|
||||
#
|
||||
from .vars.message.types import Message
|
||||
from .vars.file.types import File
|
||||
|
||||
#
|
||||
# VARIABLE KEY TYPE
|
||||
@@ -31,7 +30,3 @@ class _ContextDataKey[T]:
|
||||
CTX_MESSAGE = _ContextDataKey[Message]("CTX_MESSAGE")
|
||||
"""Minimum set of fields required to describe a message. The variable is set
|
||||
when the event is a message."""
|
||||
|
||||
CTX_FILE = _ContextDataKey[File]("CTX_FILE")
|
||||
"""Minimum set of fields required to describe a file. The variable is set when
|
||||
you can download a file attached to the message."""
|
||||
@@ -0,0 +1,143 @@
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any, Callable, Coroutine
|
||||
from types import ModuleType
|
||||
import inspect
|
||||
import importlib
|
||||
import pkgutil
|
||||
import traceback
|
||||
|
||||
from .. import EventContext
|
||||
import mab.context.vars
|
||||
if TYPE_CHECKING:
|
||||
from ..keys import _ContextDataKey
|
||||
|
||||
class ContextVars:
|
||||
"""This class implements context variable storage."""
|
||||
|
||||
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 ContextVars using dynamically detected builders.
|
||||
|
||||
What is a builder?
|
||||
1. Synchronous or asynchronous function
|
||||
2. Takes exactly 2 positional arguments: `EventContext` and `ContextVars`
|
||||
3. A member of module `mab.context.vars.<subpackage_name>.builders`
|
||||
4. `mab.context.vars.<subpackage_name>.__init__` exists
|
||||
4. Function name starts with `autobuild_`
|
||||
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) != 2:
|
||||
return False
|
||||
return all(p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD) for p in params.values())
|
||||
|
||||
@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("autobuild_")]
|
||||
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, ContextVars], None]] = []
|
||||
self._async_builders: list[Callable[[EventContext, ContextVars], 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, vars: ContextVars) -> None:
|
||||
"""Populate context variables using sync builders.
|
||||
|
||||
Args:
|
||||
- vars - ContextVars to set variables in
|
||||
"""
|
||||
for builder in self._sync_builders:
|
||||
try:
|
||||
builder(context, vars)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
async def async_populate(self, context: EventContext, vars: ContextVars) -> None:
|
||||
"""Populate context variables using async builders.
|
||||
|
||||
Args:
|
||||
- vars - ContextVars to set variables in
|
||||
"""
|
||||
for builder in self._async_builders:
|
||||
try:
|
||||
await builder(context, vars)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
@@ -1,24 +0,0 @@
|
||||
from ... import EventContext
|
||||
from ...keys import *
|
||||
|
||||
from .types import File
|
||||
|
||||
def build_file_info(context: EventContext) -> None:
|
||||
# check if basic fields are missing
|
||||
source = context.event.source
|
||||
if "content" not in source:
|
||||
return
|
||||
content: dict = source["content"]
|
||||
if "body" not in content or "msgtype" not in content:
|
||||
return
|
||||
# no file
|
||||
if "url" not in content and "file" not in content:
|
||||
return
|
||||
# create the variable
|
||||
context[CTX_FILE] = File(
|
||||
is_encrypted="file" in content,
|
||||
url=content.get("url") or content["file"]["url"],
|
||||
filename=content.get("filename", content["body"]),
|
||||
mimetype=content["info"]["mimetype"],
|
||||
size=content["info"]["size"]
|
||||
)
|
||||
@@ -1,19 +0,0 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
class File(BaseModel):
|
||||
"""This model defines both encrypted and non-encrypted file."""
|
||||
|
||||
is_encrypted: bool
|
||||
"""Whether the file is encrypted."""
|
||||
|
||||
url: str
|
||||
"""URL of the file. Must start with `mxc://` if encrypted."""
|
||||
|
||||
filename: str
|
||||
"""The name of the file."""
|
||||
|
||||
mimetype: str
|
||||
"""Mimetype of the file."""
|
||||
|
||||
size: int
|
||||
"""File size in bytes."""
|
||||
@@ -1,9 +1,10 @@
|
||||
from ... import EventContext
|
||||
from .. import ContextVars
|
||||
from ...keys import *
|
||||
|
||||
from .types import Message
|
||||
|
||||
def build_message(context: EventContext) -> None:
|
||||
def autobuild_message(context: EventContext, vars: ContextVars) -> None:
|
||||
source = context.event.source
|
||||
if "content" not in source:
|
||||
return
|
||||
@@ -16,4 +17,4 @@ def build_message(context: EventContext) -> None:
|
||||
formatted_body=content.get("formatted_body"),
|
||||
msgtype=content.get("msgtype", "Missing `msgtype`")
|
||||
)
|
||||
context[CTX_MESSAGE] = res
|
||||
vars[CTX_MESSAGE] = res
|
||||
Reference in New Issue
Block a user