matrix_chatgpt_bot/src/send_image.py

65 lines
1.9 KiB
Python
Raw Normal View History

2023-03-22 14:28:22 +00:00
"""
code derived from:
https://matrix-nio.readthedocs.io/en/latest/examples.html#sending-an-image
"""
import os
2023-09-13 06:36:35 +00:00
2023-03-22 14:28:22 +00:00
import aiofiles.os
import magic
from log import getlogger
2023-09-13 06:36:35 +00:00
from nio import AsyncClient
from nio import UploadResponse
from PIL import Image
2023-03-22 14:28:22 +00:00
logger = getlogger()
2023-05-30 02:26:39 +00:00
async def send_room_image(client: AsyncClient, room_id: str, image: str):
2023-03-22 14:28:22 +00:00
"""
image: image path
"""
mime_type = magic.from_file(image, mime=True) # e.g. "image/jpeg"
im = Image.open(image)
(width, height) = im.size # im.size returns (width,height) tuple
# first do an upload of image, then send URI of upload to room
file_stat = await aiofiles.os.stat(image)
async with aiofiles.open(image, "r+b") as f:
resp, maybe_keys = await client.upload(
f,
content_type=mime_type, # image/jpeg
filename=os.path.basename(image),
filesize=file_stat.st_size,
)
if not isinstance(resp, UploadResponse):
2023-09-13 06:36:35 +00:00
logger.warning(f"Failed to upload image. Failure response: {resp}")
2023-03-22 14:28:22 +00:00
await client.room_send(
room_id,
message_type="m.room.message",
2023-05-30 02:26:39 +00:00
content={
"msgtype": "m.text",
2023-09-13 06:36:35 +00:00
"body": f"Failed to upload image. Failure response: {resp}",
2023-05-30 02:26:39 +00:00
},
2023-03-22 14:28:22 +00:00
ignore_unverified_devices=True,
)
return
content = {
"body": os.path.basename(image), # descriptive title
"info": {
"size": file_stat.st_size,
"mimetype": mime_type,
"w": width, # width in pixel
"h": height, # height in pixel
},
"msgtype": "m.image",
"url": resp.content_uri,
}
try:
await client.room_send(room_id, message_type="m.room.message", content=content)
except Exception as e:
2023-05-30 02:26:39 +00:00
logger.error(f"Image send of file {image} failed.\n Error: {e}", exc_info=True)
2023-04-13 05:41:47 +00:00
raise Exception(e)