From c2d1d70cd1a3d1e37bddabeb80d66f3bca624fa5 Mon Sep 17 00:00:00 2001 From: vin Date: Sun, 14 Jan 2024 23:16:42 -0500 Subject: [PATCH] use mautrix for sending matrix messages --- main.py | 47 ++++++++++++++++++++++++++++++++++++++--------- requirements.txt | 2 +- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index 6c1b2b4..5589f25 100644 --- a/main.py +++ b/main.py @@ -1,20 +1,49 @@ -import os, discord +import asyncio, json, os, discord +import mautrix.client intents = discord.Intents.default() intents.message_content = True -token = os.getenv("DISCORD_TOKEN") -client = discord.Client(intents=intents) +dclient = discord.Client(intents=intents) +mclient = mautrix.client.ClientAPI( + os.getenv("MATRIX_USERID"), + base_url=os.getenv("MATRIX_HOMESERVER"), + token=os.getenv("MATRIX_TOKEN") +) -channelids = [1196201613132574733] +rooms = {1196201613132574733: "!eChKdzVweNTyHctaKQ:wired.rehab"} -@client.event +async def matrix_init(): + joined = await mclient.get_joined_rooms() + print(joined) + for room in rooms.values(): + try: + await mclient.join_room_by_id(room) + except Exception as e: + print("Failed to join room", room) + print(type(e).__name__, e) + exit(1) + joined = await mclient.get_joined_rooms() + print(joined) + for room in joined: + await mclient.send_message(room, '{"body":"joined","msgtype":"m.text"}') +task = asyncio.get_event_loop().create_task(matrix_init()) +asyncio.get_event_loop().run_until_complete(task) + +@dclient.event async def on_ready(): - print(f"Logged in as {client.user}") + print(f"Logged in as {dclient.user}") -@client.event +@dclient.event async def on_message(message): - if message.channel.id in channelids: + if message.channel.id in rooms.keys(): print(f"<{message.author.global_name}> {message.content}") -client.run(token) + content = {} + content['body'] = f" {message.content}" + content['msgtype'] = "m.text" + + print(json.dumps(content)) + await mclient.send_message(rooms[message.channel.id], json.dumps(content)) + +dclient.run(os.getenv("DISCORD_TOKEN")) diff --git a/requirements.txt b/requirements.txt index c0e500d..bdb716d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ discord.py - +mautrix