diff --git a/docs/ContextVariables.md b/docs/ContextVariables.md new file mode 100644 index 0000000..60bb376 --- /dev/null +++ b/docs/ContextVariables.md @@ -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 \ No newline at end of file diff --git a/examples/command_bot.py b/examples/command_bot.py index f960def..8419124 100644 --- a/examples/command_bot.py +++ b/examples/command_bot.py @@ -16,7 +16,7 @@ from mab import * 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_MESSAGE = ( "Here is the list of the commands:
" @@ -31,14 +31,14 @@ async def on_help_command(ctx: EventContext) -> None: ) await ctx.bot.send.text(ctx.room, HELP_MESSAGE) -async def on_time_command(ctx: EventContext) -> None: +async def on_time_command(ctx: EventContext, vars: ContextVars) -> None: """!time""" await ctx.bot.send.text( ctx.room, f"Current UNIX timestamp is {int(time.time())}" ) -async def on_raise_command(ctx: EventContext) -> None: +async def on_raise_command(ctx: EventContext, vars: ContextVars) -> None: """!raise""" await ctx.bot.send.text( ctx.room, @@ -46,7 +46,7 @@ async def on_raise_command(ctx: EventContext) -> None: ) raise RuntimeError() -async def on_assert_command(ctx: EventContext) -> None: +async def on_assert_command(ctx: EventContext, vars: ContextVars) -> None: """!assert""" await ctx.bot.send.text( ctx.room, @@ -54,10 +54,10 @@ async def on_assert_command(ctx: EventContext) -> None: ) assert False -async def on_mul_command(ctx: EventContext) -> None: +async def on_mul_command(ctx: EventContext, vars: ContextVars) -> None: """!mul""" try: - numbers = [float(v) for v in ctx[CTX_CMD_ARGS]] + numbers = [float(v) for v in vars[CTX_COMMAND].args] v = numbers[0] for n in numbers[1:]: v *= n @@ -67,16 +67,16 @@ async def on_mul_command(ctx: EventContext) -> None: except Exception as 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""" try: response = ( - f"Prefix: {ctx[CTX_CMD_PREFIX]}
" - f"Verb: {ctx[CTX_CMD_VERB]}
" - f"Arguments: {len(ctx[CTX_CMD_ARGS])}
" + f"Prefix: {vars[CTX_COMMAND].prefix}
" + f"Verb: {vars[CTX_COMMAND].verb}
" + f"Arguments: {len(vars[CTX_COMMAND].args)}
" f"Arguments are:
    " ) - for arg in ctx[CTX_CMD_ARGS]: + for arg in vars[CTX_COMMAND].args: response += f"
  1. {html.escape(arg)}
  2. " response += "
" await ctx.bot.send.text( @@ -89,7 +89,7 @@ async def on_args_command(ctx: EventContext) -> None: 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.""" await ctx.bot.send.text(ctx.room, "Use !help") diff --git a/examples/image_bot.py b/examples/image_bot.py index 92bc509..1af8ae3 100644 --- a/examples/image_bot.py +++ b/examples/image_bot.py @@ -18,15 +18,15 @@ from mab import * 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.""" # convert R, G and B to floats try: - r, g, b = [float(f) for f in data[CTX_MESSAGE].body.split()[1:]] + r, g, b = [float(f) for f in vars[CTX_COMMAND].args] except: - await data.bot.send.text(data.room, "Invalid arguments") + await ctx.bot.send.text(ctx.room, "Invalid arguments") 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 img = Image.new("RGB", (16, 16)) for x in range(img.width): @@ -44,9 +44,9 @@ async def on_gen_command(data: EventContext) -> None: buf.seek(0) buf = buf.read() # 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.""" # download s = time.time() @@ -73,10 +73,10 @@ async def on_image(ctx: EventContext) -> None: 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.""" - await data.bot.send.text( - data.room, + await ctx.bot.send.text( + ctx.room, "Text me something like !gen 0.1 0.7 1.0 or send an image to blur" ) diff --git a/examples/room_bot.py b/examples/room_bot.py index d867f60..6e315f7 100644 --- a/examples/room_bot.py +++ b/examples/room_bot.py @@ -15,7 +15,7 @@ from mab import * from _environment import check_environment -async def on_help_message(ctx: EventContext) -> None: +async def on_help_message(ctx: EventContext, vars: ContextVars) -> None: """Help message""" RESPONSE = ( "Here's how you use the bot:" @@ -32,8 +32,9 @@ async def on_help_message(ctx: EventContext) -> None: ) await ctx.bot.send.text(ctx.room, RESPONSE, is_html=False) -async def on_cmd_create(ctx: EventContext) -> None: +async def on_cmd_create(ctx: EventContext, vars: ContextVars) -> None: """!create""" + raise NotImplementedError() await ctx.bot.rooms.create() alias = "".join([random.choice("abcdefghj") for i in range(10)]) name = alias.capitalize() @@ -43,19 +44,19 @@ async def on_cmd_create(ctx: EventContext) -> None: alias=alias, name=name, topic=topic, - invite_list=[ctx[CTX_SENDER]] + invite_list=[vars[CTX_EVENT]] ) 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) -> None: +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) -> None: +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) @@ -63,64 +64,64 @@ async def on_cmd_forget(ctx: EventContext) -> None: await asyncio.sleep(1) await ctx.bot.rooms.forget(ctx.room) -async def on_cmd_join(ctx: EventContext) -> None: +async def on_cmd_join(ctx: EventContext, vars: ContextVars) -> None: """!join""" try: - room_id = ctx[CTX_CMD_ARGS][0] + 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) -> None: +async def on_cmd_invite(ctx: EventContext, vars: ContextVars) -> None: """!invite""" try: - room_id = ctx[CTX_CMD_ARGS][0] - user_id = ctx[CTX_CMD_ARGS][1] + 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) -> None: +async def on_cmd_kick(ctx: EventContext, vars: ContextVars) -> None: """!kick""" try: - room_id = ctx[CTX_CMD_ARGS][0] - user_id = ctx[CTX_CMD_ARGS][1] + 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) -> None: +async def on_cmd_ban(ctx: EventContext, vars: ContextVars) -> None: """!ban""" try: - room_id = ctx[CTX_CMD_ARGS][0] - user_id = ctx[CTX_CMD_ARGS][1] + 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) -> None: +async def on_cmd_unban(ctx: EventContext, vars: ContextVars) -> None: """!unban""" try: - room_id = ctx[CTX_CMD_ARGS][0] - user_id = ctx[CTX_CMD_ARGS][1] + 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) -> None: +async def on_cmd_members(ctx: EventContext, vars: ContextVars) -> None: """!members""" try: - room_id = ctx[CTX_CMD_ARGS][0] + 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) diff --git a/src/mab/__init__.py b/src/mab/__init__.py index f44245c..fe24a56 100644 --- a/src/mab/__init__.py +++ b/src/mab/__init__.py @@ -1,9 +1,14 @@ +# Bot and its config types +from .bot import MatrixBot from .types import MatrixBotConfig -from .bot import MatrixBot +# Introduce all filters into mab namespace +from .filters import * +# Types for callback arguments from .context import EventContext from .context.vars import ContextVars -from .context.keys import * -from .filters import * \ No newline at end of file +# Context variables +from .context.vars.command import * +from .context.vars.message import * \ No newline at end of file diff --git a/src/mab/bot/_callbacks.py b/src/mab/bot/_callbacks.py index afa4b72..a49f311 100644 --- a/src/mab/bot/_callbacks.py +++ b/src/mab/bot/_callbacks.py @@ -64,8 +64,9 @@ class Callbacks: 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): + if not await callback_info.filter(event_context, local_event_vars): continue except asyncio.CancelledError: raise @@ -82,7 +83,10 @@ class Callbacks: ) continue # create the coroutine - cor = callback_info.callback(event_context, event_vars) + cor = callback_info.callback( + event_context, + event_vars + local_event_vars + ) # multitasking if self._config.enable_multitasking_callbacks: t = asyncio.create_task(cor) diff --git a/src/mab/context/keys.py b/src/mab/context/keys.py deleted file mode 100644 index 3799ece..0000000 --- a/src/mab/context/keys.py +++ /dev/null @@ -1,32 +0,0 @@ -# -# 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 describe a message. The variable is set -when the event is a message.""" \ No newline at end of file diff --git a/src/mab/context/vars/__init__.py b/src/mab/context/vars/__init__.py index 9a5e94c..29a57a0 100644 --- a/src/mab/context/vars/__init__.py +++ b/src/mab/context/vars/__init__.py @@ -1,142 +1,122 @@ from typing import Any -from typing import TYPE_CHECKING, Any, Callable, Coroutine -from types import ModuleType import inspect -import importlib -import pkgutil import traceback +import logging from .. import EventContext -import mab.context.vars -if TYPE_CHECKING: - from ..keys import _ContextDataKey + +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 __setitem__[T](self, key: _ContextDataKey[T], value: T | None) -> None: - """Set a value inside the context data storage. `None` removes it""" + def _raw(self) -> dict[ContextVarKey, Any]: + """Get raw context data storage.""" if not hasattr(self, "_datastore"): - self._datastore: dict[_ContextDataKey, Any] = {} - if value is None: - del self._datastore[key] - else: - self._datastore[key] = value + self._datastore: dict[ContextVarKey, Any] = {} + return self._datastore - def __getitem__[T](self, key: _ContextDataKey[T]) -> T: + 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 not hasattr(self, "_datastore") or key not in self._datastore: + if key not in self._raw(): raise RuntimeError(f"Context does not contain {repr(key)}") - return self._datastore[key] + return self._raw()[key] - def __contains__[T](self, key: _ContextDataKey[T]) -> bool: + def __contains__[T](self, key: ContextVarKey[T]) -> bool: """Check if context data storage contains the value""" - if not hasattr(self, "_datastore"): - return False - if key not in self._datastore: + 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 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..builders` - 4. `mab.context.vars..__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. + """This class populates ContextVars using builders decorated with + `autobuilder`. """ + _LOGGER = logging.getLogger("ContextVarsPopulator") + _sync_builders = [] + _async_builders = [] - @staticmethod - def _is_builder_signature_valid(builder) -> bool: - """Check if builder signature is valid. + @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: - - builder - function to check - - Returns: - - True if the signature is valid + - func - function to add as an autobuilder """ - 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) + 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 ] - 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]) + 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 - 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: + @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 self._sync_builders: + for builder in cls._sync_builders: try: builder(context, vars) except: traceback.print_exc() - async def async_populate(self, context: EventContext, vars: ContextVars) -> None: + @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 self._async_builders: + for builder in cls._async_builders: try: await builder(context, vars) except: diff --git a/src/mab/context/vars/command/__init__.py b/src/mab/context/vars/command/__init__.py new file mode 100644 index 0000000..c88da9b --- /dev/null +++ b/src/mab/context/vars/command/__init__.py @@ -0,0 +1,2 @@ +from .types import * +from .keys import * \ No newline at end of file diff --git a/src/mab/context/vars/command/keys.py b/src/mab/context/vars/command/keys.py new file mode 100644 index 0000000..ac1244c --- /dev/null +++ b/src/mab/context/vars/command/keys.py @@ -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`.""" \ No newline at end of file diff --git a/src/mab/context/vars/command/types.py b/src/mab/context/vars/command/types.py new file mode 100644 index 0000000..229d656 --- /dev/null +++ b/src/mab/context/vars/command/types.py @@ -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""" \ No newline at end of file diff --git a/src/mab/context/vars/message/__init__.py b/src/mab/context/vars/message/__init__.py index e69de29..6c74969 100644 --- a/src/mab/context/vars/message/__init__.py +++ b/src/mab/context/vars/message/__init__.py @@ -0,0 +1,3 @@ +from .types import * +from .keys import * +from . import builders \ No newline at end of file diff --git a/src/mab/context/vars/message/builders.py b/src/mab/context/vars/message/builders.py index 563fb50..bb90579 100644 --- a/src/mab/context/vars/message/builders.py +++ b/src/mab/context/vars/message/builders.py @@ -1,10 +1,10 @@ from ... import EventContext -from .. import ContextVars -from ...keys import * +from .. import ContextVars, ContextVarsPopulator -from .types import Message +from . import * -def autobuild_message(context: EventContext, vars: ContextVars) -> None: +@ContextVarsPopulator.autobuilder +def _build_message(context: EventContext, vars: ContextVars) -> None: source = context.event.source if "content" not in source: return diff --git a/src/mab/context/vars/message/keys.py b/src/mab/context/vars/message/keys.py new file mode 100644 index 0000000..4898b84 --- /dev/null +++ b/src/mab/context/vars/message/keys.py @@ -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.""" \ No newline at end of file diff --git a/src/mab/filters/base.py b/src/mab/filters/base.py index 64146f5..92b05df 100644 --- a/src/mab/filters/base.py +++ b/src/mab/filters/base.py @@ -3,9 +3,10 @@ import logging from typing import Type from ..context import EventContext +from ..context.vars import ContextVars class BaseEventFilter(ABC): - """Base class for all message filters""" + """Base class for all message filters. Always returns True.""" _logger = logging.Logger("EventFilter") def __init__(self, **kwargs): @@ -63,37 +64,37 @@ class BaseEventFilter(ABC): """ 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 - filter operates according to its description. This method must not raise - exceptions. In case of exception it should log it using `self._logger` - and return False - + This method checks if the event from `ctx` matches filter-specific + criteria. The filter may add variables to `vars`. If the callback will + be called then these variables will be added to the final context + variables. This function should return True if criteria is matched. + False must be returned otherwise. + Args: - - context - event context; your derived classes may add variables - to it (see `message.MessageTypeFilter` implementation - for reference) - + - ctx - context to filter + - vars - variables object that may be modified by the filter + Returns: - - True if the event satisfies this filter - - False if the event does not satisfy this filter + - True if the context matches the criteria + - False if the context does not match the criteria """ return True 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): super().__init__(**kwargs) self._type = type - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False - return isinstance(context.event, self._type) + return isinstance(ctx.event, self._type) class CompoundEventFilter(BaseEventFilter): - """Event filter that consists of multiple filters""" + """Event filter that consists of multiple filters.""" OPERATOR_AND = "and" OPERATOR_OR = "or" OPERATOR_XOR = "xor" @@ -141,10 +142,10 @@ class CompoundEventFilter(BaseEventFilter): expression = f"~{reprs[0]}" return f"({expression})" - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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: return all(evaluated) elif self._operator == self.OPERATOR_OR: diff --git a/src/mab/filters/body.py b/src/mab/filters/body.py index 1108321..17989b3 100644 --- a/src/mab/filters/body.py +++ b/src/mab/filters/body.py @@ -1,43 +1,42 @@ import re import traceback from .message import NewMessageFilter + from ..context import EventContext +from ..context.vars import ContextVars + +from ..context.vars.command import CTX_COMMAND, Command class BodyExistsFilter(NewMessageFilter): """ This filter returns True if all conditions are met: 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 - If this filter matches, you can access `event.body` and it stores - unformatted text of the message. - - 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. + If `event.body` value equals to filename (if it is present, of course) then + this filter will return False 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, videos, files, etc. - - This filter sets `CTX_BODY` context variable. """ def __init__(self, *, ignore_filename_in_body: bool = True, **kwargs): super().__init__(**kwargs) self._ignore_filename_in_body = ignore_filename_in_body - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False - if not hasattr(context.event, "body"): + if not hasattr(ctx.event, "body"): return False - if not isinstance(context.event.body, str): # type: ignore + if not isinstance(ctx.event.body, str): # type: ignore return False - if not context.event.body.strip(): # type: ignore + if not ctx.event.body.strip(): # type: ignore return False if self._ignore_filename_in_body: - content = context.event.source["content"] - if "filename" in content and content["filename"] == context.event.body: # type: ignore + content = ctx.event.source["content"] + if "filename" in content and content["filename"] == ctx.event.body: # type: ignore return False return True @@ -61,10 +60,10 @@ class BodyContainsFilter(BodyExistsFilter): self._any_case = any_case self._needle = needle - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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: if n in body: return True @@ -90,10 +89,10 @@ class BodyStartsWithFilter(BodyExistsFilter): self._any_case = any_case self._substring = substring - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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: if body.startswith(s): return True @@ -119,10 +118,10 @@ class BodyEndsWithFilter(BodyExistsFilter): self._any_case = any_case self._substring = substring - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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: if body.endswith(s): return True @@ -145,10 +144,7 @@ class BodyCommandFilter(BodyExistsFilter): store all verbs in lower case. This filter will not match any verbs that use mixed case of upper case. - This filter sets the following context variables: - - `CTX_CMD_PREFIX` - prefix that was used - - `CTX_CMD_VERB` - verb that was used - - `CTX_CMD_ARGS` - arguments that were passed + This filter sets CTX_COMMAND context variable if it returns True. """ def __init__(self, verbs: str | list[str], min_args: int = 0, max_args: int | None = None, prefix: str = "!", **kwargs): super().__init__(**kwargs) @@ -159,10 +155,10 @@ class BodyCommandFilter(BodyExistsFilter): self._max_args = max_args self._prefix = prefix - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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 if args_count < self._min_args: return False @@ -173,6 +169,11 @@ class BodyCommandFilter(BodyExistsFilter): cmd = parts[0][len(self._prefix):].lower() for verb in self._verbs: if cmd == verb: + vars[CTX_COMMAND] = Command( + prefix=self._prefix, + verb=cmd, + args=parts[1:] + ) return True return False @@ -186,11 +187,11 @@ class BodyRegexFilter(BodyExistsFilter): regex = re.compile(regex) self._regex = regex - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False 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: self._logger.error(traceback.format_exc()) return False \ No newline at end of file diff --git a/src/mab/filters/message.py b/src/mab/filters/message.py index ef46c83..2cfb63b 100644 --- a/src/mab/filters/message.py +++ b/src/mab/filters/message.py @@ -1,7 +1,9 @@ import traceback from .base import BaseEventFilter, EventTypeFilter from ..types import MessageType + from ..context import EventContext +from ..context.vars import ContextVars from nio import RedactionEvent @@ -11,26 +13,24 @@ class MessageTypeFilter(BaseEventFilter): images, videos, files, etc) based on `event.source["content"]["msgtype"]` value. - `types` list is stored by reference so you may modify the behavior of this - filter dynamically. - - This filter sets `CTX_MESSAGE_TYPE` variable in the context. + `types` list is copied so you can't modify behavior of this filter + dynamically. """ - def __init__(self, types: list[MessageType] | MessageType, **kwargs): + def __init__(self, types: list[MessageType | str] | MessageType | str, **kwargs): super().__init__(**kwargs) - if isinstance(types, MessageType): + if not isinstance(types, list): 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: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False - if "msgtype" not in context.event.source["content"]: + if "msgtype" not in ctx.event.source["content"]: return False - msgtype = context.event.source["content"]["msgtype"] - if not msgtype in [t.value for t in self._types]: - return False - return True + msgtype = ctx.event.source["content"]["msgtype"] + return msgtype in self._types class NewMessageFilter(BaseEventFilter): """ @@ -41,10 +41,10 @@ class NewMessageFilter(BaseEventFilter): def __init__(self, **kwargs): super().__init__(**kwargs) - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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): """ @@ -54,10 +54,10 @@ class EditedMessageFilter(BaseEventFilter): def __init__(self, **kwargs): super().__init__(**kwargs) - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False - return "m.new_content" in context.event.source["content"] + return "m.new_content" in ctx.event.source["content"] class RedactedMessageFilter(EventTypeFilter): """ @@ -67,7 +67,7 @@ class RedactedMessageFilter(EventTypeFilter): super().__init__(RedactionEvent, **kwargs) raise NotImplementedError() - async def __call__(self, context: EventContext) -> bool: + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: raise NotImplementedError() class SenderIsFilter(BaseEventFilter): @@ -79,8 +79,6 @@ class SenderIsFilter(BaseEventFilter): `senders` list is stored by reference so you can modify behavior of this filter dynamically. - - This filter sets `CTX_SENDER` variable in the context. """ def __init__(self, sender: list[str] | str, *, any_case: bool = True, **kwargs): super().__init__(**kwargs) @@ -89,10 +87,10 @@ class SenderIsFilter(BaseEventFilter): self._sender = sender self._any_case = any_case - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): 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: if sender == s: return True @@ -110,26 +108,23 @@ class SenderIsBotFilter(BaseEventFilter): def __init__(self, **kwargs): super().__init__(**kwargs) - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False - return context.bot.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 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): super().__init__(**kwargs) - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False - content: dict | None = context.event.source.get("content") + content: dict | None = ctx.event.source.get("content") if content is None: return False # `file` if encrypted, `url` if not encrypted diff --git a/src/mab/filters/room.py b/src/mab/filters/room.py index 3ffe955..d189975 100644 --- a/src/mab/filters/room.py +++ b/src/mab/filters/room.py @@ -1,6 +1,7 @@ from .base import BaseEventFilter from ..context import EventContext +from ..context.vars import ContextVars class RoomEncryptedFilter(BaseEventFilter): """ @@ -9,10 +10,10 @@ class RoomEncryptedFilter(BaseEventFilter): def __init__(self): super().__init__() - async def __call__(self, context: EventContext) -> bool: - if not await super().__call__(context): + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): return False try: - return context.room.encrypted + return ctx.room.encrypted except: return False \ No newline at end of file