From 315ff32422c24a2ac239b302f7a01cdeb008d8b9 Mon Sep 17 00:00:00 2001 From: agatha Date: Sat, 8 Jun 2024 15:20:37 -0400 Subject: [PATCH] implement markdown support for matrix bot, closes #2 --- main.py | 9 ++++++++- matrix.py | 23 +++++++++++++++++++++++ requirements.txt | 3 ++- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 0f0b58b..48ade5d 100644 --- a/main.py +++ b/main.py @@ -29,10 +29,17 @@ async def main(): monitor_thread = threading.Thread(target=monitor.log_loop, args=(15,)) monitor_thread.start() + # Send "online message" + try: + await bot.send_markdown("**MBOT ONLINE**") + await bot.logout() + except nio.exceptions.LocalProtocolError: + pass + while True: event = queue.get() try: - await bot.send_message(event) + await bot.send_markdown(event) await bot.logout() queue.task_done() except nio.exceptions.LocalProtocolError: diff --git a/matrix.py b/matrix.py index 765b956..70a8b46 100644 --- a/matrix.py +++ b/matrix.py @@ -1,3 +1,4 @@ +import markdown from loguru import logger from nio import AsyncClient, LoginResponse @@ -28,6 +29,28 @@ class MatrixBot: ) logger.info("Message sent") + async def send_markdown(self, message: str): + if not self.client.access_token: + logged_in = await self.login() + if not logged_in: + return + + # Convert message to markdown + html = markdown.markdown(message) + + # Send markdown formatted message + await self.client.room_send( + room_id=self.config['room_id'], + message_type="m.room.message", + content={ + "msgtype": "m.text", + "body": message, + "format": "org.matrix.custom.html", + "formatted_body": html + } + ) + logger.info("Markdown message sent") + async def login(self): response = await self.client.login( password=self.config['password'] diff --git a/requirements.txt b/requirements.txt index 2bad5e3..5d48d7a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,4 +2,5 @@ matrix-nio loguru web3 requests -SQLAlchemy \ No newline at end of file +SQLAlchemy +markdown \ No newline at end of file