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 <noreply@anthropic.com>
This commit is contained in:
Christian Gick
2026-02-18 22:35:21 +02:00
parent da4a714913
commit 2199de47f9

33
bot.py
View File

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