Added support for file in message context variables

- Fixed file_bot example
- Added functions for extacting file data when building CTX_MESSAGE
- Added `file` variable for Message model
- Fixed RoomEvent builder inability to set room ID when it is missing in source
This commit is contained in:
2026-11-08 19:58:35 +03:00
parent b5210359b1
commit d758bdedac
4 changed files with 82 additions and 15 deletions

View File

@@ -16,18 +16,20 @@ from mab import *
from _environment import check_environment
async def on_text_message(ctx: EventContext) -> None:
async def on_text_message(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a text message arrives."""
await ctx.bot.send.text(ctx.room, "Please send a file/image/video")
await ctx.bot.send.text(ctx.room, "Please send a file/image/video/audio")
async def on_file_message(ctx: EventContext) -> None:
async def on_file_message(ctx: EventContext, vars: ContextVars) -> None:
"""This callback is called when a file arrives."""
sha = hashlib.sha256()
does_temp_exist = False
file = ctx[CTX_FILE]
if not file.size:
file.size = 0
if file.size > 1_000_000:
file = vars[CTX_MESSAGE].file
if not file:
return
if not file.filesize:
file.filesize = 0
if file.filesize > 1_000_000:
await ctx.bot.send.text(
ctx.room,
"The file is larger than 1 MB, downloading to filesystem"
@@ -48,8 +50,8 @@ async def on_file_message(ctx: EventContext) -> None:
content = await ctx.bot.download.file(ctx, path=None)
sha.update(content)
# result
response = f"SHA256 for file `{ctx[CTX_FILE].filename}`"
response += f" ({ctx[CTX_FILE].size} bytes, {ctx[CTX_FILE].filename})"
response = f"SHA256 for file `{file.filename}`"
response += f" ({file.filesize} bytes, {file.filename})"
await ctx.bot.send.file_bytes(
room=ctx.room,
data=sha.hexdigest().encode("utf-8"),
@@ -62,7 +64,7 @@ async def on_file_message(ctx: EventContext) -> None:
await ctx.bot.send.file(
room=ctx.room,
path="temp.tmp",
filename=ctx[CTX_FILE].filename,
filename=file.filename,
text="This is the file you have sent, but it was reuploaded"
)
try:
@@ -87,7 +89,7 @@ async def main() -> None:
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
on_text_message)
bot.add_callback(
~SenderIsBotFilter() & MessageHasFile() & NewMessageFilter(),
~SenderIsBotFilter() & MessageHasFileFilter() & NewMessageFilter(),
on_file_message)
# run until Ctrl+C