Files
mab/examples/branch_bot.py
nikita 4dae739cfe Added branches system, updated database, v0.8.0
- Updated to v0.8.0
- Added note about rate limitting to README
- Updated examples to work with new callback system
- Updated README to describe new callback system correctly
- Added branch_bot.py example
- Updated database so internal functions are prefixed with underscore now
- Replaced MatrixBot.add_room_event_callback with MatrixBot.add_callback
- Database schema version is 4 now
- Added room state to database to simplify user code
- Added RoomStateFilter
2026-12-06 21:24:05 +03:00

138 lines
4.8 KiB
Python

"""
This example implements Matrix bot that demonstates branches and room states.
It uses environment variables to specify authorization data. Use Ctrl+C to stop
the bot.
"""
import asyncio
import os
import logging
import hashlib
from mab import *
from _environment import check_environment
from _image_generator import generate_image
#
# HELP MESSAGES
#
async def msg_on_upper(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to convert to upper case")
async def msg_on_sha256(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to find SHA256 for")
async def msg_on_count(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to count symbols in")
async def msg_on_image(ctx: EventContext, vars: ContextVars) -> None:
await ctx.bot.send.text(ctx.room, "Please send text to convert to a random image")
async def msg_on_help(ctx: EventContext, vars: ContextVars) -> None:
TEXT = "Please choose the action to do:\n"
for state in STATES:
TEXT += f"\n{state} - {STATES[state][0]}"
event_id = await ctx.bot.send.text(ctx.room, TEXT)
for state in STATES:
await ctx.bot.send.reaction(ctx.room, event_id, state)
#
# CALLBACKS
#
async def on_upper(ctx: EventContext, vars: ContextVars) -> None:
"""🔠"""
await ctx.bot.send.text(ctx.room, vars[CTX_MESSAGE].body.upper())
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await asyncio.sleep(0.5)
await msg_on_help(ctx, vars)
async def on_sha256(ctx: EventContext, vars: ContextVars) -> None:
"""🔮"""
res = hashlib.sha256(vars[CTX_MESSAGE].body.encode("utf-8")).hexdigest()
await ctx.bot.send.text(ctx.room, res)
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await asyncio.sleep(0.5)
await msg_on_help(ctx, vars)
async def on_count(ctx: EventContext, vars: ContextVars) -> None:
"""🔍"""
await ctx.bot.send.text(ctx.room, f"The length is {len(vars[CTX_MESSAGE].body)}")
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await asyncio.sleep(0.5)
await msg_on_help(ctx, vars)
async def on_image(ctx: EventContext, vars: ContextVars) -> None:
"""🖼"""
inputs = [a.strip() for a in vars[CTX_MESSAGE].body.split("\n") if a.strip()]
for i in inputs:
await ctx.bot.send.image_bytes(
ctx.room,
generate_image(i),
"generated.jpg",
text=i
)
await asyncio.sleep(0.5)
await ctx.bot.database.room_state_set(ctx.room.room_id, None)
await msg_on_help(ctx, vars)
async def on_invalid(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a room with unset state appears."""
await msg_on_help(ctx, vars)
async def on_reaction(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a reaction is added to some message."""
state = vars[CTX_REACTION].reaction
if state not in STATES:
await msg_on_help(ctx, vars)
return
await ctx.bot.database.room_state_set(ctx.room.room_id, state)
await STATES[state][2](ctx, vars)
#
# STATES DATA
#
STATES = {
"🔠": ("Convert the text to upper case", on_upper, msg_on_upper),
"🔮": ("Find SHA256 for the text", on_sha256, msg_on_sha256),
"🔍": ("Count the symbols in the message", on_count, msg_on_count),
"🖼": ("Convert the text to a random image", on_image, msg_on_image),
}
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)
# create the root branch
branch_root = Branch(~SenderIsBotFilter() & NewMessageFilter())
# callbacks for state transitions
for state in STATES:
branch_root.add_callback(MessageReactionFilter(reaction=state), on_reaction)
# callbacks for active states
for state in STATES:
branch = Branch(RoomStateFilter(state))
branch.add_callback(MessageTypeFilter(MessageType.TEXT), STATES[state][1])
branch.add_callback(BaseEventFilter(), STATES[state][2])
branch_root.add_branch(branch)
# callback that fires for unhandled events (must be the last one added!)
branch_root.add_callback(BaseEventFilter(), on_invalid)
# register the root branch
bot.callbacks.add_branch(branch_root)
# run until Ctrl+C
try:
await bot.run()
except asyncio.CancelledError:
pass
if __name__ == "__main__":
asyncio.run(main())