diff --git a/matrix_keycloak_bot.py b/matrix_keycloak_bot.py index 4460150..04f011a 100644 --- a/matrix_keycloak_bot.py +++ b/matrix_keycloak_bot.py @@ -1,4 +1,5 @@ import asyncio +import markdown import os import sys from keycloak import KeycloakAdmin @@ -236,7 +237,7 @@ async def send_message_safe( content: dict, message_type: str = "m.room.message" ): - """Sends a message to a room, automatically trusting any unverified devices if an OlmUnverifiedDeviceError occurs.""" + """Sends a message to a room, automatically trusting unverified devices on OlmUnverifiedDeviceError.""" while True: try: return await client.room_send( @@ -248,6 +249,38 @@ async def send_message_safe( print(f"Auto-trusting unverified device '{e.device.device_id}' for user '{e.device.user_id}'...") client.verify_device(e.device) +async def send_markdown_message( + client: AsyncClient, + room_id: str, + md_text: str, + msgtype: str = "m.text", + relates_to: dict = None, +): + """Compiles Markdown to valid Matrix HTML payloads and handles message edits cleanly.""" + # Convert Markdown to HTML + html_body = markdown.markdown(md_text, extensions=["extra", "sane_lists"]) + + content = { + "msgtype": msgtype, + "body": md_text, + "format": "org.matrix.custom.html", + "formatted_body": html_body, + } + + # Properly format Matrix m.replace edits (MSC2676) + if relates_to: + content["m.relates_to"] = relates_to + content["m.new_content"] = { + "msgtype": msgtype, + "body": md_text, + "format": "org.matrix.custom.html", + "formatted_body": html_body, + } + content["body"] = f"* {md_text}" + content["formatted_body"] = f"* {html_body}" + + return await send_message_safe(client, room_id, content) + async def on_reaction(client: AsyncClient, room: MatrixRoom, event: ReactionEvent): """Listens for reaction approvals/denials in the admin room.""" print(f"[REACTION] Received '{event.key}' from {event.sender} on event '{event.reacts_to}'") diff --git a/requirements.txt b/requirements.txt index 9ea4afa..a0cbd44 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ matrix-nio[e2e]>=0.24.0 python-keycloak>=4.0.0 +markdown