TexLiLy/main.py
2023-06-12 10:20:48 -04:00

76 lines
2.3 KiB
Python

from nio import *
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)
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)
content = {
"body": filename,
"info": {
"size": size,
"w": w, "h": h,
"mimetype": "image/png"
},
"msgtype": "m.image",
"url": resp.content_uri,
}
await client.room_send(room.room_id, message_type="m.room.message", content=content)
except FileNotFoundError:
content = {
"msgtype": "m.text",
"body": "Couldn't parse LaTeX correctly."
}
await client.room_send(room.room_id, message_type="m.room.message", content=content)
# Our file callback.
async def file_cb(room: MatrixRoom, event: RoomMessageFile) -> None:
url = event.url
filename = event.body
async def main() -> None:
# Load our config file.
global client
config = {}
try:
with open('texlily.yaml', 'r') as conf:
config = yaml.safe_load(conf)
except FileNotFoundError:
print("No config file found.\nPlease create a file named `texlily.yaml` and read the README file.")
quit()
# Retrieve our configuration.
homeserver = str(config["homeserver"])
user = str(config["user"])
token = str(config["token"])
path = str(config["path"])
client = AsyncClient(homeserver)
client.access_token = token
client.user_id = user
# Bad kludge!
await client.sync(timeout=300000)
# Register all of the callbacks
client.add_event_callback(msg_cb, RoomMessageText)
client.add_event_callback(file_cb, RoomMessageFile)
await client.sync_forever(timeout=10000, full_state=True)
asyncio.run(main())