Big refactoring

- Changed event callback signature to `(ctx: EventContext, vars: ContextVars)`
- Changed event filter signature to `(ctx: EventContext, vars: ContextVars)`
- Partially fixed examples
- Refactored `src/mab/__init__.py` to be more structured
- Added support for local event context variables so that different filters don't mess with each other
- Refactored file structure for context variables
- Added support for combination of ContextVars
- `ContextVarsPopulator` does not look builders dynamically anymore; `ContextVarsPopulator.autobuilder` is used to mark function as a builder that must be automatically called
- `ContextVarsPopulator` does not required to be created anymore
- Added context variable `CTX_COMMAND`
- `MessageTypeFilter` supports message types passed as strings from now on
- `MessageHasFile` renamed to `MessageHasFileFilter`
- Added docs for context variables
This commit is contained in:
2026-10-31 20:37:57 +03:00
parent eacb0c0d25
commit d5367ebc6b
18 changed files with 329 additions and 272 deletions

View File

@@ -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 = (
"<strong>Here is the list of the commands:</strong><br>"
@@ -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 <strong>{int(time.time())}</strong>"
)
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: <code>{ctx[CTX_CMD_PREFIX]}</code><br>"
f"Verb: <code>{ctx[CTX_CMD_VERB]}</code><br>"
f"Arguments: <code>{len(ctx[CTX_CMD_ARGS])}</code><br>"
f"Prefix: <code>{vars[CTX_COMMAND].prefix}</code><br>"
f"Verb: <code>{vars[CTX_COMMAND].verb}</code><br>"
f"Arguments: <code>{len(vars[CTX_COMMAND].args)}</code><br>"
f"Arguments are:<br><ol>"
)
for arg in ctx[CTX_CMD_ARGS]:
for arg in vars[CTX_COMMAND].args:
response += f"<li><code>{html.escape(arg)}</code></li>"
response += "</ol>"
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 <code>!help</code>")

View File

@@ -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 <code>!gen 0.1 0.7 1.0</code> or send an image to blur"
)

View File

@@ -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)