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:
@@ -16,18 +16,20 @@ from mab import *
|
|||||||
|
|
||||||
from _environment import check_environment
|
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."""
|
"""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."""
|
"""This callback is called when a file arrives."""
|
||||||
sha = hashlib.sha256()
|
sha = hashlib.sha256()
|
||||||
does_temp_exist = False
|
does_temp_exist = False
|
||||||
file = ctx[CTX_FILE]
|
file = vars[CTX_MESSAGE].file
|
||||||
if not file.size:
|
if not file:
|
||||||
file.size = 0
|
return
|
||||||
if file.size > 1_000_000:
|
if not file.filesize:
|
||||||
|
file.filesize = 0
|
||||||
|
if file.filesize > 1_000_000:
|
||||||
await ctx.bot.send.text(
|
await ctx.bot.send.text(
|
||||||
ctx.room,
|
ctx.room,
|
||||||
"The file is larger than 1 MB, downloading to filesystem"
|
"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)
|
content = await ctx.bot.download.file(ctx, path=None)
|
||||||
sha.update(content)
|
sha.update(content)
|
||||||
# result
|
# result
|
||||||
response = f"SHA256 for file `{ctx[CTX_FILE].filename}`"
|
response = f"SHA256 for file `{file.filename}`"
|
||||||
response += f" ({ctx[CTX_FILE].size} bytes, {ctx[CTX_FILE].filename})"
|
response += f" ({file.filesize} bytes, {file.filename})"
|
||||||
await ctx.bot.send.file_bytes(
|
await ctx.bot.send.file_bytes(
|
||||||
room=ctx.room,
|
room=ctx.room,
|
||||||
data=sha.hexdigest().encode("utf-8"),
|
data=sha.hexdigest().encode("utf-8"),
|
||||||
@@ -62,7 +64,7 @@ async def on_file_message(ctx: EventContext) -> None:
|
|||||||
await ctx.bot.send.file(
|
await ctx.bot.send.file(
|
||||||
room=ctx.room,
|
room=ctx.room,
|
||||||
path="temp.tmp",
|
path="temp.tmp",
|
||||||
filename=ctx[CTX_FILE].filename,
|
filename=file.filename,
|
||||||
text="This is the file you have sent, but it was reuploaded"
|
text="This is the file you have sent, but it was reuploaded"
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
@@ -87,7 +89,7 @@ async def main() -> None:
|
|||||||
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
|
~SenderIsBotFilter() & BodyExistsFilter() & MessageTypeFilter(MessageType.TEXT),
|
||||||
on_text_message)
|
on_text_message)
|
||||||
bot.add_callback(
|
bot.add_callback(
|
||||||
~SenderIsBotFilter() & MessageHasFile() & NewMessageFilter(),
|
~SenderIsBotFilter() & MessageHasFileFilter() & NewMessageFilter(),
|
||||||
on_file_message)
|
on_file_message)
|
||||||
|
|
||||||
# run until Ctrl+C
|
# run until Ctrl+C
|
||||||
|
|||||||
@@ -3,6 +3,34 @@ from .. import ContextVars, ContextVarsPopulator
|
|||||||
|
|
||||||
from . import *
|
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
|
@ContextVarsPopulator.autobuilder
|
||||||
def _build_message(ctx: EventContext, vars: ContextVars) -> None:
|
def _build_message(ctx: EventContext, vars: ContextVars) -> None:
|
||||||
"""This builder creates a CTX_MESSAGE variable for any message."""
|
"""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":
|
if source["type"] != "m.room.message":
|
||||||
return
|
return
|
||||||
content: dict = source["content"]
|
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
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
from typing import Literal
|
from typing import Literal
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, SkipValidation
|
||||||
|
|
||||||
class Message(BaseModel):
|
class Message(BaseModel):
|
||||||
"""This model describes message of any kind and is being used as base
|
"""This model describes message of any kind and is being used as base
|
||||||
@@ -17,3 +17,38 @@ class Message(BaseModel):
|
|||||||
|
|
||||||
formatted_body: str | None = None
|
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."""
|
||||||
@@ -11,7 +11,7 @@ def _build_room_event(ctx: EventContext, vars: ContextVars) -> None:
|
|||||||
content=ev.source["content"],
|
content=ev.source["content"],
|
||||||
event_id=ev.event_id,
|
event_id=ev.event_id,
|
||||||
origin_server_ts=ev.source["origin_server_ts"],
|
origin_server_ts=ev.source["origin_server_ts"],
|
||||||
room_id=ev.source["room_id"],
|
room_id=ctx.room.room_id,
|
||||||
sender=ev.sender,
|
sender=ev.sender,
|
||||||
type=ev.source["type"]
|
type=ev.source["type"]
|
||||||
)
|
)
|
||||||
Reference in New Issue
Block a user