From 7fdfaadafe70f002709c23527ed234cbacedaf36 Mon Sep 17 00:00:00 2001 From: git-bruh Date: Fri, 13 Nov 2020 22:01:04 +0530 Subject: [PATCH] Add support for attachments --- README.md | 1 + main.py | 28 ++++++++++++++++++++-------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5375b7a..9e94e77 100644 --- a/README.md +++ b/README.md @@ -16,3 +16,4 @@ A simple Matrix-Discord bridge written in Python. - [x] Sending messages - [x] Discord webhooks (with avatars) +- [x] Attachments (URL) diff --git a/main.py b/main.py index be6c58b..6a0a496 100644 --- a/main.py +++ b/main.py @@ -48,14 +48,18 @@ async def on_message(message): if message.author.bot: return - # Replace IDs in mentions with the tagged user's name + # Replace mention/emote IDs with names content = await process(message.content, "emote_") content = await process(content, "mention") - message_ = f"<{message.author.name}> {content}" + content = f"<{message.author.name}> {content}" + + # Append attachments to message + for attachment in message.attachments: + content += f"\n{attachment.url}" if str(message.channel.id) == config["channel_id"]: - await message_send(message_) + await message_send(content) async def process(message, category): @@ -129,7 +133,8 @@ async def create_matrix_client(): # Sync once before adding callback to avoid acting on old messages await matrix_client.sync(timeout) - matrix_client.add_event_callback(message_callback, nio.RoomMessageText) + matrix_client.add_event_callback(message_callback, (nio.RoomMessageText, + nio.RoomMessageMedia)) # Sync forever await matrix_client.sync_forever(timeout=timeout) @@ -162,15 +167,22 @@ async def message_callback(room, event): author = event.sender[1:] avatar = None + homeserver = author.split(":")[-1] + url = "https://matrix.org/_matrix/media/r0/download" + + # Get attachments + try: + attachment = event.url.split("/")[-1] + message += f"\n{url}/{homeserver}/{attachment}" + except AttributeError: + pass + # Get avatar for user in room.users.values(): if user.user_id == event.sender: if user.avatar_url: - homeserver = author.split(":")[-1] - avatar = user.avatar_url.split("/")[-1] - avatar = "https://matrix.org/_matrix/media/r0/download/" \ - f"{homeserver}/{avatar}" + avatar = f"{url}/{homeserver}/{avatar}" break await webhook_send(author, avatar, message)