2020-11-14 16:34:30 +01:00
|
|
|
import discord
|
2020-11-30 13:35:49 +01:00
|
|
|
import re
|
2020-11-11 16:46:15 +01:00
|
|
|
import json
|
2020-11-14 16:34:30 +01:00
|
|
|
import logging
|
2020-11-30 13:35:49 +01:00
|
|
|
from nio import (
|
|
|
|
AsyncClient,
|
|
|
|
RoomMessageText,
|
|
|
|
RoomMessageMedia,
|
|
|
|
RedactionEvent,
|
|
|
|
EphemeralEvent
|
|
|
|
)
|
2020-11-14 16:34:30 +01:00
|
|
|
import os
|
2020-11-11 16:46:15 +01:00
|
|
|
|
|
|
|
|
|
|
|
def config_gen(config_file):
|
|
|
|
config_dict = {
|
|
|
|
"homeserver": "https://matrix.org",
|
|
|
|
"room_id": "room:matrix.org",
|
|
|
|
"username": "@name:matrix.org",
|
|
|
|
"password": "my-secret-password",
|
|
|
|
"channel_id": "channel",
|
|
|
|
"token": "my-secret-token"
|
|
|
|
}
|
|
|
|
|
|
|
|
if not os.path.exists(config_file):
|
|
|
|
with open(config_file, "w") as f:
|
|
|
|
json.dump(config_dict, f, indent=4)
|
|
|
|
print(f"Example configuration dumped to {config_file}")
|
|
|
|
exit()
|
|
|
|
|
|
|
|
with open(config_file, "r") as f:
|
|
|
|
config = json.loads(f.read())
|
|
|
|
|
|
|
|
return config
|
|
|
|
|
|
|
|
|
|
|
|
config = config_gen("config.json")
|
|
|
|
|
2020-11-12 15:42:23 +01:00
|
|
|
logging.basicConfig(level=logging.INFO)
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_logger = logging.getLogger("matrix_logger")
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
message_store = {}
|
2020-11-14 16:14:16 +01:00
|
|
|
|
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
class MatrixClient(object):
|
|
|
|
async def create(self):
|
|
|
|
homeserver = config["homeserver"]
|
|
|
|
username = config["username"]
|
|
|
|
password = config["password"]
|
2020-11-30 16:44:34 +01:00
|
|
|
timeout = 30000
|
2020-11-14 16:14:16 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
global matrix_client
|
2020-11-16 11:38:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_client = AsyncClient(homeserver, username)
|
2020-11-29 15:35:27 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_logger.info(await matrix_client.login(password))
|
2020-11-14 17:03:06 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_logger.info("Doing initial sync.")
|
2020-11-30 16:44:34 +01:00
|
|
|
await matrix_client.sync(timeout)
|
2020-11-16 11:38:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Set up event callbacks
|
|
|
|
callbacks = Callbacks()
|
|
|
|
matrix_client.add_event_callback(
|
|
|
|
callbacks.message_callback,
|
|
|
|
(RoomMessageText, RoomMessageMedia))
|
2020-11-16 11:38:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_client.add_event_callback(
|
|
|
|
callbacks.redaction_callback, RedactionEvent)
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_client.add_ephemeral_callback(
|
|
|
|
callbacks.typing_callback, EphemeralEvent)
|
2020-11-13 15:04:31 +01:00
|
|
|
|
2020-11-30 16:44:34 +01:00
|
|
|
matrix_logger.info("Syncing forever.")
|
|
|
|
await matrix_client.sync_forever(timeout=timeout)
|
|
|
|
|
|
|
|
await matrix_client.close()
|
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def message_send(self, message, reply_id=None, edit_id=None):
|
|
|
|
content = {
|
|
|
|
"msgtype": "m.text",
|
|
|
|
"body": message,
|
|
|
|
}
|
2020-11-16 11:38:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
if reply_id:
|
2020-11-30 16:14:17 +01:00
|
|
|
reply_event = await matrix_client.room_get_event(
|
|
|
|
config["room_id"], reply_id
|
|
|
|
)
|
|
|
|
|
|
|
|
reply_event = reply_event.event.source["content"]["body"]
|
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
content["m.relates_to"] = {
|
|
|
|
"m.in_reply_to": {"event_id": reply_id},
|
|
|
|
}
|
2020-11-25 07:35:07 +01:00
|
|
|
|
2020-11-30 16:14:17 +01:00
|
|
|
content["format"] = "org.matrix.custom.html"
|
|
|
|
|
|
|
|
content["formatted_body"] = (f"""<mx-reply><blockquote>
|
|
|
|
<a href="https://matrix.to/#/{config["room_id"]}/{reply_id}">In reply to</a>
|
|
|
|
<a href="https://matrix.to/#/{config["username"]}">{config["username"]}</a><br>
|
|
|
|
{reply_event}</blockquote></mx-reply>{message}
|
|
|
|
""")
|
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
if edit_id:
|
|
|
|
content["body"] = f" * {message}"
|
2020-11-14 17:03:06 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
content["m.new_content"] = {
|
|
|
|
"body": message,
|
|
|
|
"msgtype": "m.text"
|
|
|
|
}
|
2020-11-14 17:03:06 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
content["m.relates_to"] = {
|
|
|
|
"event_id": edit_id,
|
|
|
|
"rel_type": "m.replace",
|
|
|
|
}
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
message = await matrix_client.room_send(
|
|
|
|
room_id=config["room_id"],
|
|
|
|
message_type="m.room.message",
|
|
|
|
content=content
|
|
|
|
)
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
return message.event_id
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def message_redact(self, message):
|
|
|
|
await matrix_client.room_redact(
|
|
|
|
room_id=config["room_id"],
|
|
|
|
event_id=message
|
|
|
|
)
|
2020-11-14 16:14:16 +01:00
|
|
|
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
class DiscordClient(discord.Client):
|
2020-11-30 16:27:21 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
2020-11-30 16:44:34 +01:00
|
|
|
self.bg_task = self.loop.create_task(MatrixClient().create())
|
2020-11-30 16:27:21 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def on_ready(self):
|
|
|
|
print(f"Logged in as {self.user}")
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
global channel
|
|
|
|
channel = int(config["channel_id"])
|
|
|
|
channel = self.get_channel(channel)
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def on_message(self, message):
|
|
|
|
if message.author.bot or str(message.channel.id) != \
|
|
|
|
config["channel_id"]:
|
|
|
|
return
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
content = await Process().discord(message)
|
2020-11-12 15:42:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
matrix_message = await MatrixClient().message_send(
|
|
|
|
content[0], content[1])
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
message_store[message.id] = matrix_message
|
2020-11-12 15:42:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def on_message_edit(self, before, after):
|
|
|
|
if after.author.bot or str(after.channel.id) != \
|
|
|
|
config["channel_id"]:
|
|
|
|
return
|
2020-11-12 15:42:23 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
content = await Process().discord(after)
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
await MatrixClient().message_send(
|
|
|
|
content[0], edit_id=message_store[before.id])
|
2020-11-15 15:08:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def on_message_delete(self, message):
|
|
|
|
if message.id in message_store:
|
|
|
|
await MatrixClient().message_redact(message_store[message.id])
|
2020-11-14 14:43:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def on_typing(self, channel, user, when):
|
|
|
|
if user.bot or str(channel.id) != config["channel_id"]:
|
|
|
|
return
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Send typing event
|
|
|
|
await matrix_client.room_typing(config["room_id"], timeout=0)
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def webhook_send(self, author, avatar, message, event_id):
|
|
|
|
# Create webhook if it doesn't exist
|
|
|
|
hook_name = "matrix_bridge"
|
|
|
|
hooks = await channel.webhooks()
|
|
|
|
hook = discord.utils.get(hooks, name=hook_name)
|
|
|
|
if not hook:
|
|
|
|
hook = await channel.create_webhook(name=hook_name)
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# 'wait=True' allows us to store the sent message
|
|
|
|
try:
|
|
|
|
hook = await hook.send(username=author, avatar_url=avatar,
|
|
|
|
content=message, wait=True)
|
|
|
|
message_store[event_id] = hook
|
|
|
|
except discord.errors.HTTPException as e:
|
|
|
|
matrix_logger.warning(f"Failed to send message {event_id}: {e}")
|
2020-11-29 16:33:49 +01:00
|
|
|
|
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
class Callbacks(object):
|
|
|
|
async def message_callback(self, room, event):
|
|
|
|
# Don't act on activities in other rooms
|
|
|
|
if room.room_id != config["room_id"]:
|
|
|
|
return
|
2020-11-30 07:42:05 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# https://github.com/Rapptz/discord.py/issues/6058
|
|
|
|
# content_dict = event.source.get("content")
|
|
|
|
# try:
|
|
|
|
# if content_dict["m.relates_to"]["rel_type"] == "m.replace":
|
|
|
|
# edited_event = content_dict["m.relates_to"]["event_id"]
|
|
|
|
# edited_content = content_dict["m.new_content"]["body"]
|
|
|
|
# webhook_message = message_cache[edited_event]
|
|
|
|
# await something_edit_webhook(webhook_message, edited_content)
|
|
|
|
# return
|
|
|
|
# except KeyError:
|
|
|
|
# pass
|
|
|
|
|
|
|
|
message = event.body
|
|
|
|
|
|
|
|
if not message:
|
|
|
|
return
|
2020-11-30 07:42:05 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Don't act on ourselves
|
|
|
|
if event.sender == matrix_client.user:
|
|
|
|
return
|
2020-11-30 07:42:05 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
author = event.sender[1:]
|
|
|
|
avatar = None
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
homeserver = author.split(":")[-1]
|
|
|
|
url = "https://matrix.org/_matrix/media/r0/download"
|
2020-11-15 16:32:55 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
message = await Process().matrix(message)
|
2020-11-15 16:32:55 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Get attachments
|
|
|
|
try:
|
|
|
|
attachment = event.url.split("/")[-1]
|
2020-11-15 16:32:55 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Highlight attachment name
|
|
|
|
message = f"`{message}`"
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
message += f"\n{url}/{homeserver}/{attachment}"
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2020-11-14 14:43:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Get avatar
|
|
|
|
for user in room.users.values():
|
|
|
|
if user.user_id == event.sender:
|
|
|
|
if user.avatar_url:
|
|
|
|
avatar = user.avatar_url.split("/")[-1]
|
|
|
|
avatar = f"{url}/{homeserver}/{avatar}"
|
|
|
|
break
|
2020-11-30 07:42:05 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
await DiscordClient().webhook_send(
|
|
|
|
author, avatar, message, event.event_id)
|
2020-11-13 15:04:31 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def redaction_callback(self, room, event):
|
|
|
|
# Don't act on activities in other rooms
|
|
|
|
if room.room_id != config["room_id"]:
|
|
|
|
return
|
2020-11-12 14:22:48 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Don't act on ourselves
|
|
|
|
if event.sender == matrix_client.user:
|
|
|
|
return
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Redact webhook message
|
|
|
|
try:
|
|
|
|
message = message_store[event.redacts]
|
|
|
|
await message.delete()
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2020-11-13 11:08:28 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def typing_callback(self, room, event):
|
|
|
|
# Don't act on activities in other rooms
|
|
|
|
if room.room_id != config["room_id"]:
|
|
|
|
return
|
2020-11-13 17:31:04 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
if room.typing_users:
|
|
|
|
# Don't act on ourselves
|
|
|
|
if len(room.typing_users) == 1 \
|
|
|
|
and room.typing_users[0] == matrix_client.user:
|
|
|
|
return
|
2020-11-14 06:03:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Send typing event
|
|
|
|
async with channel.typing():
|
|
|
|
pass
|
2020-11-14 16:34:30 +01:00
|
|
|
|
2020-11-14 16:25:37 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
class Process(object):
|
|
|
|
async def discord(self, message):
|
|
|
|
content = message.clean_content
|
2020-11-13 17:31:04 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
replied_event = None
|
|
|
|
if message.reference:
|
|
|
|
replied_message = await message.channel.fetch_message(
|
|
|
|
message.reference.message_id)
|
|
|
|
try:
|
|
|
|
replied_event = message_store[replied_message.id]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
2020-11-13 11:08:28 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Replace emote IDs with names
|
|
|
|
content = re.sub(r"<a?(:\w+:)\d*>", r"\g<1>", content)
|
2020-11-15 15:08:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
# Append attachments to message
|
|
|
|
for attachment in message.attachments:
|
|
|
|
content += f"\n{attachment.url}"
|
2020-11-15 15:08:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
content = f"<{message.author.name}> {content}"
|
2020-11-15 15:08:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
return content, replied_event
|
2020-11-15 15:08:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
async def matrix(self, message):
|
|
|
|
message = message.replace("@everyone", "@\u200Beveryone")
|
|
|
|
message = message.replace("@here", "@\u200Bhere")
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
mentions = re.findall(r"(^|\s)(@(\w*))", message)
|
|
|
|
emotes = re.findall(r":(.*?):", message)
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
guild = channel.guild
|
2020-11-14 16:14:16 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
for emote in emotes:
|
|
|
|
emote_ = discord.utils.get(guild.emojis, name=emote)
|
|
|
|
if emote_:
|
|
|
|
message = message.replace(f":{emote}:", str(emote_))
|
2020-11-14 14:43:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
for mention in mentions:
|
|
|
|
member = await guild.query_members(query=mention[2])
|
|
|
|
if member:
|
|
|
|
message = message.replace(mention[1], member[0].mention)
|
2020-11-14 14:43:25 +01:00
|
|
|
|
2020-11-30 13:35:49 +01:00
|
|
|
return message
|
2020-11-14 14:43:25 +01:00
|
|
|
|
|
|
|
|
2020-11-30 16:44:34 +01:00
|
|
|
def main():
|
2020-11-30 13:35:49 +01:00
|
|
|
intents = discord.Intents.default()
|
|
|
|
intents.members = True
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-30 16:44:34 +01:00
|
|
|
DiscordClient(intents=intents).run(config["token"])
|
|
|
|
|
2020-11-11 16:46:15 +01:00
|
|
|
|
2020-11-12 15:42:23 +01:00
|
|
|
if __name__ == "__main__":
|
2020-11-30 16:44:34 +01:00
|
|
|
main()
|