modify matrix message content to format mentions and newlines

This commit is contained in:
Laureηt 2023-10-19 17:27:27 +00:00
parent 10c7513add
commit d7a14fd4ee
Signed by: Laurent
SSH key fingerprint: SHA256:kZEpW8cMJ54PDeCvOhzreNr4FSh6R13CMGH/POoO8DI

View file

@ -1,5 +1,6 @@
import asyncio import asyncio
import logging import logging
import re
import time import time
from collections import deque from collections import deque
@ -190,6 +191,18 @@ class LLMClient(AsyncClient):
output = response["choices"][0]["message"]["content"] # type: ignore output = response["choices"][0]["message"]["content"] # type: ignore
output = output.strip().removeprefix(f"{self.uid}:").strip() output = output.strip().removeprefix(f"{self.uid}:").strip()
# replace newlines with <br>
formatted_output = output.replace("\n", "<br>")
# detect mentions and replace them with html mentions
formatted_output = re.sub(
r"@[^:]+:[^ :]+",
lambda match: f'<a href="https://matrix.to/#/{match.group(0)}"></a>',
formatted_output,
)
logger.debug(f"Formatted response: {formatted_output}")
# send the response # send the response
await self.room_send( await self.room_send(
room_id=self.room, room_id=self.room,
@ -197,6 +210,8 @@ class LLMClient(AsyncClient):
content={ content={
"msgtype": "m.text", "msgtype": "m.text",
"body": output, "body": output,
"format": "org.matrix.custom.html",
"formatted_body": formatted_output,
}, },
) )
logger.debug(f"Sent response: {output}") logger.debug(f"Sent response: {output}")