From 2199de47f95f6e58dfa3f401e4c285a31a08bba5 Mon Sep 17 00:00:00 2001 From: Christian Gick Date: Wed, 18 Feb 2026 22:35:21 +0200 Subject: [PATCH] fix: Handle encrypted image upload for Matrix rooms (MAT-9) Upload with encrypt=True and filesize param. Handle UploadError gracefully. Use m.file encrypted format when encryption keys returned. Co-Authored-By: Claude Opus 4.6 --- bot.py | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/bot.py b/bot.py index c7705bf..fd7c0f4 100644 --- a/bot.py +++ b/bot.py @@ -974,20 +974,39 @@ class Bot: async def _send_image(self, room_id: str, image_bytes: bytes, mime_type: str, filename: str): """Upload image to Matrix homeserver and send as m.image event.""" - upload_resp, _ = await self.client.upload( + from nio import UploadResponse + upload_resp, maybe_keys = await self.client.upload( data_provider=io.BytesIO(image_bytes), content_type=mime_type, filename=filename, + filesize=len(image_bytes), + encrypt=True, ) + if not isinstance(upload_resp, UploadResponse): + logger.error("Image upload failed: %s", upload_resp) + await self._send_text(room_id, "Sorry, I couldn't upload the generated image.") + return + + content = { + "msgtype": "m.image", + "body": filename, + "info": {"mimetype": mime_type, "size": len(image_bytes)}, + } + if maybe_keys: + content["file"] = { + "url": upload_resp.content_uri, + "key": maybe_keys["key"], + "iv": maybe_keys["iv"], + "hashes": maybe_keys["hashes"], + "v": maybe_keys["v"], + } + else: + content["url"] = upload_resp.content_uri + await self.client.room_send( room_id, message_type="m.room.message", - content={ - "msgtype": "m.image", - "body": filename, - "url": upload_resp.content_uri, - "info": {"mimetype": mime_type, "size": len(image_bytes)}, - }, + content=content, ) async def _send_text(self, room_id: str, text: str):