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:
31
bot.py
31
bot.py
@@ -974,20 +974,39 @@ class Bot:
|
|||||||
|
|
||||||
async def _send_image(self, room_id: str, image_bytes: bytes, mime_type: str, filename: str):
|
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 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),
|
data_provider=io.BytesIO(image_bytes),
|
||||||
content_type=mime_type,
|
content_type=mime_type,
|
||||||
filename=filename,
|
filename=filename,
|
||||||
|
filesize=len(image_bytes),
|
||||||
|
encrypt=True,
|
||||||
)
|
)
|
||||||
await self.client.room_send(
|
if not isinstance(upload_resp, UploadResponse):
|
||||||
room_id,
|
logger.error("Image upload failed: %s", upload_resp)
|
||||||
message_type="m.room.message",
|
await self._send_text(room_id, "Sorry, I couldn't upload the generated image.")
|
||||||
|
return
|
||||||
|
|
||||||
content = {
|
content = {
|
||||||
"msgtype": "m.image",
|
"msgtype": "m.image",
|
||||||
"body": filename,
|
"body": filename,
|
||||||
"url": upload_resp.content_uri,
|
|
||||||
"info": {"mimetype": mime_type, "size": len(image_bytes)},
|
"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=content,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _send_text(self, room_id: str, text: str):
|
async def _send_text(self, room_id: str, text: str):
|
||||||
|
|||||||
Reference in New Issue
Block a user