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

View File

@@ -3,6 +3,34 @@ from .. import ContextVars, ContextVarsPopulator
from . import *
def _file_extractor_none(source: dict):
"""File extractor for messages that contain no file."""
return None
def _file_extractor_generic(source: dict):
"""File extractor for generic msgtype"""
content = source["content"]
# we can continue only if either of them is present
if ("file" not in content) == ("url" not in content):
return None
file = MessageFile()
file.filename = content.get("filename") or content.get("body")
info = content.get("info")
if info:
file.filesize = info.get("size")
file.mimetype = info.get("mimetype")
return file
def _get_file_extractor(source: dict):
"""This function returns function that will generate MessageFile."""
return {
"m.image": _file_extractor_generic,
"m.file": _file_extractor_generic,
"m.audio": _file_extractor_generic,
"m.video": _file_extractor_generic,
}.get(source["content"]["msgtype"], _file_extractor_none)
@ContextVarsPopulator.autobuilder
def _build_message(ctx: EventContext, vars: ContextVars) -> None:
"""This builder creates a CTX_MESSAGE variable for any message."""
@@ -10,4 +38,6 @@ def _build_message(ctx: EventContext, vars: ContextVars) -> None:
if source["type"] != "m.room.message":
return
content: dict = source["content"]
vars[CTX_MESSAGE] = Message.model_validate(content)
msg = Message.model_validate(content)
msg.file = _get_file_extractor(source)(source)
vars[CTX_MESSAGE] = msg

View File

@@ -1,5 +1,5 @@
from typing import Literal
from pydantic import BaseModel
from pydantic import BaseModel, SkipValidation
class Message(BaseModel):
"""This model describes message of any kind and is being used as base
@@ -16,4 +16,39 @@ class Message(BaseModel):
"""Format of the formatted_body content"""
formatted_body: str | None = None
"""Formatted body of the message, present if `format` is not None"""
"""Formatted body of the message, present if `format` is not None"""
file: SkipValidation[MessageFile | None] = None
"""The file attached to the message."""
class MessageFile(BaseModel):
"""This model describes a file attached to the message. Fields of this
model should be used to get some basic info about the file and should not
be used to download the file itself."""
filename: str | None = None
"""The original filename of the uploaded file."""
filesize: int | None = None
"""The size of the file in bytes."""
mimetype: str | None = None
"""The mimetype of the file."""
thumbnail: MessageFileThumbnail | None = None
"""The thumbnail of the file."""
class MessageFileThumbnail(BaseModel):
"""This model describes the thumbnail of the file."""
width: int | None = None
"""The width of the thumbnail."""
height: int | None = None
"""The height of the thumbnail."""
mimetype: str | None = None
"""The mimetype of the thumbnail."""
size: int | None = None
"""The size of the thumbnail in bytes."""

View File

@@ -11,7 +11,7 @@ def _build_room_event(ctx: EventContext, vars: ContextVars) -> None:
content=ev.source["content"],
event_id=ev.event_id,
origin_server_ts=ev.source["origin_server_ts"],
room_id=ev.source["room_id"],
room_id=ctx.room.room_id,
sender=ev.sender,
type=ev.source["type"]
)