Files
mab/examples/reaction_bot.py
nikita b99b2fa9bf Added user key-value pairs in bot database. v0.7.1
- Bumped patch number
- Added user key-value pairs to the built-in database
- Updated reaction_bot example to use key-value pairs storage
- Database schema version is 3 now (added a table for user kv pairs)
2026-12-05 23:30:34 +03:00

81 lines
2.5 KiB
Python

"""
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.load_value("reactions_processed")
val = 0 if val is None else int.from_bytes(val)
val += 1
await bot.save_value("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.add_callback(
~SenderIsBotFilter() & MessageReactionFilter(reaction=["❤️", "👍"]),
on_specific_reaction)
bot.add_callback(
~SenderIsBotFilter() & MessageReactionFilter(),
on_reaction)
bot.add_callback(
~SenderIsBotFilter() & NewMessageFilter(),
on_message)
# run until Ctrl+C
try:
await bot.run()
except asyncio.CancelledError:
pass
if __name__ == "__main__":
asyncio.run(main())