diff --git a/examples/reaction_bot.py b/examples/reaction_bot.py new file mode 100644 index 0000000..ffd7446 --- /dev/null +++ b/examples/reaction_bot.py @@ -0,0 +1,62 @@ +""" +This example implements Matrix bot that works with reactions. + +It uses environment variables to specify authorization data. Use Ctrl+C to stop +the bot. +""" + +import asyncio +import os +import logging + +from mab import * + +from _environment import check_environment + +async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None: + """This callback is called when a reaction is added.""" + sender = vars[CTX_REACTION].sender + reaction = vars[CTX_REACTION].reaction + response = f"(Specific reaction) {sender}: {reaction}" + await ctx.bot.send.text( + ctx.room, + response + ) + +async def on_reaction(ctx: EventContext, vars: ContextVars) -> None: + """This callback is called when a reaction is added.""" + sender = vars[CTX_REACTION].sender + reaction = vars[CTX_REACTION].reaction + response = f"(Generic reaction) {sender}: {reaction}" + await ctx.bot.send.text( + ctx.room, + response + ) + +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["MATRIX_HOMESERVER"], + matrix_username_localpart=os.environ["MATRIX_USERNAME"], + storage_directory="session_storage" + ) + bot = MatrixBot(config) + bot.add_callback( + ~SenderIsBotFilter() & MessageReactionFilter(reaction=["❤️", "👍"]), + on_specific_reaction) + bot.add_callback( + ~SenderIsBotFilter() & MessageReactionFilter(), + on_reaction) + + # run until Ctrl+C + try: + await bot.run() + except asyncio.CancelledError: + pass + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/src/mab/__init__.py b/src/mab/__init__.py index 1fceb92..a4f635c 100644 --- a/src/mab/__init__.py +++ b/src/mab/__init__.py @@ -12,4 +12,5 @@ from .context.vars import ContextVars # Context variables from .context.vars.command import * from .context.vars.message import * +from .context.vars.reaction import * from .context.vars.room_event import * \ No newline at end of file diff --git a/src/mab/context/vars/reaction/__init__.py b/src/mab/context/vars/reaction/__init__.py new file mode 100644 index 0000000..6c74969 --- /dev/null +++ b/src/mab/context/vars/reaction/__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/reaction/builders.py b/src/mab/context/vars/reaction/builders.py new file mode 100644 index 0000000..9a5a93e --- /dev/null +++ b/src/mab/context/vars/reaction/builders.py @@ -0,0 +1,18 @@ +from ... import EventContext +from .. import ContextVars, ContextVarsPopulator + +from . import * +import json + +@ContextVarsPopulator.autobuilder +def _build_reaction(ctx: EventContext, vars: ContextVars) -> None: + """This builder creates a CTX_MESSAGE variable for any message.""" + source = ctx.event.source + if source.get("type") != "m.reaction": + return + res = Reaction( + message_id=source["content"]["m.relates_to"]["event_id"], + reaction=source["content"]["m.relates_to"]["key"], + sender=source["sender"] + ) + vars[CTX_REACTION] = res \ No newline at end of file diff --git a/src/mab/context/vars/reaction/keys.py b/src/mab/context/vars/reaction/keys.py new file mode 100644 index 0000000..8d6e90a --- /dev/null +++ b/src/mab/context/vars/reaction/keys.py @@ -0,0 +1,6 @@ +from .types import * +from .. import ContextVarKey + +CTX_REACTION = ContextVarKey[Reaction]("CTX_REACTION") +"""Variable that describes the reaction. It exists when the event is a new +reaction.""" \ No newline at end of file diff --git a/src/mab/context/vars/reaction/types.py b/src/mab/context/vars/reaction/types.py new file mode 100644 index 0000000..5f2961e --- /dev/null +++ b/src/mab/context/vars/reaction/types.py @@ -0,0 +1,13 @@ +from pydantic import BaseModel + +class Reaction(BaseModel): + """A reaction to a message""" + + message_id: str + """Event ID for the message this reaction is added to.""" + + reaction: str + """The reaction (emoji).""" + + sender: str + """Fully qualified username of the reactor.""" \ No newline at end of file diff --git a/src/mab/filters/message.py b/src/mab/filters/message.py index 2cfb63b..8058c67 100644 --- a/src/mab/filters/message.py +++ b/src/mab/filters/message.py @@ -5,7 +5,7 @@ from ..types import MessageType from ..context import EventContext from ..context.vars import ContextVars -from nio import RedactionEvent +from nio import RedactionEvent, ReactionEvent class MessageTypeFilter(BaseEventFilter): """ @@ -130,4 +130,31 @@ class MessageHasFileFilter(BaseEventFilter): # `file` if encrypted, `url` if not encrypted if "file" not in content and "url" not in content: return False - return True \ No newline at end of file + return True + +class MessageReactionFilter(EventTypeFilter): + """ + This filter returns True if the event is a new reaction added to the + message. Additionals checks are supported if you pass `sender` and + `reaction` when initializing the filter. They are checked case-sensetively + and stored by reference so you may modify behavior of this filter + dynamically. + """ + def __init__(self, *, sender: list[str] | str = [], reaction: list[str] | str = [], **kwargs): + super().__init__(ReactionEvent, **kwargs) + if isinstance(sender, str): + sender = [sender] + if isinstance(reaction, str): + reaction = [reaction] + self._sender = sender + self._reaction = reaction + + async def __call__(self, ctx: EventContext, vars: ContextVars) -> bool: + if not await super().__call__(ctx, vars): + return False + sender = ctx.event.sender + if self._sender and sender not in self._sender: + return False + if self._reaction and ctx.event.key not in self._reaction: # type: ignore + return False + return True