[ABSTRACT] Abstract the PNG sending code.

This commit is contained in:
LoaD Accumulator 2023-06-12 17:07:04 +02:00
parent 6dad6d6801
commit 91cd675721
No known key found for this signature in database
GPG key ID: 6898757653ABE3E6

36
main.py
View file

@ -4,33 +4,45 @@ import asyncio
import yaml
import os
# Our message callback. It should be passed through a router.
async def msg_cb(room: MatrixRoom, event: RoomMessageText) -> None:
if event.body.startswith("$"):
import imagesize
import latex
try:
filename = latex.render("", event.body)
async def send_png(room: MatrixRoom, filename: str) -> None:
import imagesize
basename = os.path.basename(filename)
w, h = imagesize.get(filename)
file = open(filename, "r+b")
size = os.path.getsize(filename)
filename = os.path.basename(filename)
resp, keys = await client.upload(file, content_type="image/png", filename=filename)
resp, keys = await client.upload(file, content_type="image/png", filename=basename)
if not isinstance(resp, UploadResponse):
raise OSError("Couldn't upload file.")
content = {
"body": filename,
"body": basename,
"info": {
"size": size,
"w": w, "h": h,
"mimetype": "image/png"
"mimetype": "image/png",
"w": w, "h": h
},
"msgtype": "m.image",
"url": resp.content_uri,
}
file.close()
await client.room_send(room.room_id, message_type="m.room.message", content=content)
except FileNotFoundError:
# Our message callback. It should be passed through a router.
async def msg_cb(room: MatrixRoom, event: RoomMessageText) -> None:
if event.body.startswith("$"):
import latex
try:
filename = latex.render("", event.body)
await send_png(room, filename)
except (FileNotFoundError, OSError):
content = {
"msgtype": "m.text",
"body": "Couldn't parse LaTeX correctly."