aioappsrv/main.py

305 lines
7.5 KiB
Python
Raw Normal View History

import discord
2020-11-11 16:46:15 +01:00
import json
import logging
2020-11-12 14:22:48 +01:00
import nio
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")
intents = discord.Intents.default()
intents.members = True
discord_client = discord.Client(intents=intents)
2020-11-12 15:42:23 +01:00
logging.basicConfig(level=logging.INFO)
2020-11-11 16:46:15 +01:00
message_cache = {}
2020-11-11 16:46:15 +01:00
@discord_client.event
async def on_ready():
print(f"Logged in as {discord_client.user}")
2020-11-12 14:22:48 +01:00
# Start Matrix bot
await create_matrix_client()
2020-11-11 16:46:15 +01:00
@discord_client.event
async def on_message(message):
2020-11-16 09:58:56 +01:00
# Don't act on bots
2020-11-11 16:46:15 +01:00
if message.author.bot:
return
2020-11-16 09:58:56 +01:00
if str(message.channel.id) != config["channel_id"]:
return
2020-11-15 19:29:02 +01:00
# Replace Discord IDs with mentions and emotes
content = await process_discord(message.content)
2020-11-13 17:31:04 +01:00
content = f"<{message.author.name}> {content}"
# Append attachments to message
for attachment in message.attachments:
content += f"\n{attachment.url}"
2020-11-11 16:46:15 +01:00
2020-11-16 09:58:56 +01:00
matrix_message = await message_send(content)
message_cache[message.id] = matrix_message
2020-11-12 14:22:48 +01:00
@discord_client.event
async def on_message_delete(message):
if message.id in message_cache:
await message_redact(message_cache[message.id])
2020-11-14 14:43:25 +01:00
@discord_client.event
async def on_typing(channel, user, when):
# Don't act on bots
if user.bot:
return
2020-11-16 09:58:56 +01:00
if str(channel.id) != config["channel_id"]:
return
# Send typing event
await matrix_client.room_typing(config["room_id"], timeout=0)
2020-11-14 14:43:25 +01:00
2020-11-14 16:14:16 +01:00
async def get_channel():
channel = int(config["channel_id"])
channel = discord_client.get_channel(channel)
return channel
2020-11-15 19:29:02 +01:00
async def process_discord(message):
emote_list = await process_split(message, "<:", ">")
mention_list = await process_split(message, "<@", ">")
2020-11-15 19:29:02 +01:00
for emote in emote_list:
emote_name = emote.split(":")[1]
message = message.replace(emote, f":{emote_name}:")
2020-11-15 19:29:02 +01:00
for mention in mention_list:
# Discord mentions can start with either "<@" or "<@!"
try:
mention_ = int(mention[2:-1])
except ValueError:
mention_ = int(mention[3:-1])
2020-11-15 19:29:02 +01:00
user = discord_client.get_user(mention_)
2020-11-16 09:58:56 +01:00
message = message.replace(mention, f"@{user.name}")
2020-11-15 19:29:02 +01:00
return message
2020-11-11 16:46:15 +01:00
2020-11-15 19:29:02 +01:00
async def process_matrix(message):
emote_list = await process_split(message, ":", ":")
mention_list = await process_split(message, "@", "")
2020-11-15 19:29:02 +01:00
for emote in emote_list:
emote_ = discord.utils.get(discord_client.emojis, name=emote[1:-1])
2020-11-15 19:29:02 +01:00
if emote_:
message = message.replace(emote, str(emote_))
2020-11-15 19:29:02 +01:00
channel = await get_channel()
guild = channel.guild
2020-11-15 15:44:45 +01:00
2020-11-15 19:29:02 +01:00
for mention in mention_list:
for member in await guild.query_members(query=mention[1:]):
message = message.replace(mention, member.mention)
2020-11-12 14:22:48 +01:00
return message
2020-11-15 19:29:02 +01:00
async def process_split(message, start, end):
return_list = []
for item in message.split():
if item.startswith(start) and item.endswith(end):
return_list.append(item)
return return_list
async def webhook_send(author, avatar, message, event_id):
2020-11-14 16:14:16 +01:00
channel = await get_channel()
2020-11-12 14:22:48 +01:00
# Create webhook if it doesn't exist
hook_name = "matrix_bridge"
2020-11-14 16:14:16 +01:00
hooks = await channel.webhooks()
2020-11-11 16:46:15 +01:00
hook = discord.utils.get(hooks, name=hook_name)
if hook is None:
2020-11-14 16:14:16 +01:00
hook = await channel.create_webhook(name=hook_name)
2020-11-11 16:46:15 +01:00
# 'wait=True' allows us to store the sent message
hook = await hook.send(username=author, avatar_url=avatar, content=message,
wait=True)
message_cache[event_id] = hook
2020-11-11 16:46:15 +01:00
async def create_matrix_client():
homeserver = config["homeserver"]
username = config["username"]
password = config["password"]
2020-11-12 15:42:23 +01:00
timeout = 30000
2020-11-12 14:22:48 +01:00
global matrix_client
matrix_client = nio.AsyncClient(homeserver, username)
2020-11-12 15:42:23 +01:00
print(await matrix_client.login(password))
# Sync once before adding callback to avoid acting on old messages
await matrix_client.sync(timeout)
2020-11-13 17:31:04 +01:00
matrix_client.add_event_callback(message_callback, (nio.RoomMessageText,
nio.RoomMessageMedia))
2020-11-12 14:22:48 +01:00
matrix_client.add_event_callback(redaction_callback, nio.RedactionEvent)
2020-11-14 14:43:25 +01:00
matrix_client.add_ephemeral_callback(typing_callback, nio.EphemeralEvent)
2020-11-12 15:42:23 +01:00
# Sync forever
await matrix_client.sync_forever(timeout=timeout)
2020-11-12 14:22:48 +01:00
await matrix_client.logout()
2020-11-12 14:22:48 +01:00
await matrix_client.close()
2020-11-11 16:46:15 +01:00
2020-11-12 14:22:48 +01:00
async def message_send(message):
message = await matrix_client.room_send(
2020-11-12 14:22:48 +01:00
room_id=config["room_id"],
message_type="m.room.message",
content={
"msgtype": "m.text",
"body": message
}
)
return message.event_id
async def message_redact(message):
await matrix_client.room_redact(
room_id=config["room_id"],
event_id=message,
reason="Message deleted"
)
2020-11-12 14:22:48 +01:00
async def message_callback(room, event):
2020-11-14 14:43:25 +01:00
# Don't act on activities in other rooms
if room.room_id != config["room_id"]:
return
message = event.body
2020-11-12 14:22:48 +01:00
if not message:
return
# Don't act on ourselves
2020-11-12 15:42:23 +01:00
if event.sender == matrix_client.user:
return
2020-11-11 16:46:15 +01:00
2020-11-13 11:08:28 +01:00
author = event.sender[1:]
avatar = None
2020-11-13 17:31:04 +01:00
homeserver = author.split(":")[-1]
url = "https://matrix.org/_matrix/media/r0/download"
2020-11-14 13:39:44 +01:00
# Don't mention @everyone or @here
message = message.replace("@everyone", "@\u200Beveryone")
message = message.replace("@here", "@\u200Bhere")
2020-11-15 19:29:02 +01:00
# Replace Discord mentions and emotes with IDs
message = await process_matrix(message)
2020-11-13 17:31:04 +01:00
# Get attachments
try:
attachment = event.url.split("/")[-1]
2020-11-14 16:25:37 +01:00
# Highlight attachment name
message = f"`{message}`"
2020-11-13 17:31:04 +01:00
message += f"\n{url}/{homeserver}/{attachment}"
except AttributeError:
pass
2020-11-13 11:08:28 +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]
2020-11-13 17:31:04 +01:00
avatar = f"{url}/{homeserver}/{avatar}"
2020-11-13 11:08:28 +01:00
break
await webhook_send(author, avatar, message, event.event_id)
async def redaction_callback(room, event):
# Don't act on activities in other rooms
if room.room_id != config["room_id"]:
return
# Don't act on ourselves
if event.sender == matrix_client.user:
return
2020-11-16 09:38:27 +01:00
# Redact webhook message
try:
message = message_cache[event.redacts]
await message.delete()
except KeyError:
pass
2020-11-11 16:46:15 +01:00
2020-11-14 14:43:25 +01:00
async def typing_callback(room, event):
2020-11-14 16:14:16 +01:00
channel = await get_channel()
2020-11-14 14:43:25 +01:00
# Don't act on activities in other rooms
if room.room_id != config["room_id"]:
return
if room.typing_users:
# Don't act on ourselves
if len(room.typing_users) == 1 \
and room.typing_users[0] == matrix_client.user:
return
# Send typing event
2020-11-14 16:14:16 +01:00
async with channel.typing():
2020-11-14 14:43:25 +01:00
pass
2020-11-11 16:46:15 +01:00
def main():
2020-11-12 14:22:48 +01:00
# Start Discord bot
2020-11-11 16:46:15 +01:00
discord_client.run(config["token"])
2020-11-12 15:42:23 +01:00
if __name__ == "__main__":
main()