""" 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 bump_count(bot: MatrixBot) -> int: """Bump count of reactions processed and return new value. Uses bot's database for storage.""" val = await bot.database.custom_get("reactions_processed") val = 0 if val is None else int.from_bytes(val) val += 1 await bot.database.custom_set("reactions_processed", val.to_bytes(8)) return val async def on_specific_reaction(ctx: EventContext, vars: ContextVars) -> None: """This callback is called when a specific reaction is added.""" sender = vars[CTX_REACTION].sender reaction = vars[CTX_REACTION].reaction count = await bump_count(ctx.bot) response = f"(Specific reaction) {sender}: {reaction}. Total reactions processed: {count}" 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 count = await bump_count(ctx.bot) response = f"(Generic reaction) {sender}: {reaction}. Total reactions processed: {count}" await ctx.bot.send.text( ctx.room, response ) async def on_message(ctx: EventContext, vars: ContextVars) -> None: """This callback is called when a message is received.""" await bump_count(ctx.bot) await ctx.bot.send.reaction(ctx.room, vars[CTX_ROOM_EVENT].event_id, "👀") 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) 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: await bot.run() except asyncio.CancelledError: pass if __name__ == "__main__": asyncio.run(main())