brain damage

This commit is contained in:
JandereDev 2022-04-05 21:45:44 +02:00
parent 7379b0106a
commit 9ce873975c
No known key found for this signature in database
GPG key ID: 5D5E18ACB990F57A
6 changed files with 103 additions and 61 deletions

4
.vscode/launch.json vendored
View file

@ -5,10 +5,10 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"command": "yarn dev", "command": "cd bridge && yarn dev",
"name": "Debug", "name": "Debug",
"request": "launch", "request": "launch",
"type": "node-terminal" "type": "node-terminal",
} }
] ]
} }

View file

@ -18,6 +18,7 @@
"discord.js": "^13.6.0", "discord.js": "^13.6.0",
"dotenv": "^16.0.0", "dotenv": "^16.0.0",
"log75": "^2.2.0", "log75": "^2.2.0",
"monk": "^7.3.4" "monk": "^7.3.4",
"ulid": "^2.3.0"
} }
} }

View file

@ -3,12 +3,21 @@ import { client } from "./client";
import { client as revoltClient } from "../revolt/client"; import { client as revoltClient } from "../revolt/client";
import { ChannelPermission } from "@janderedev/revolt.js"; import { ChannelPermission } from "@janderedev/revolt.js";
import axios from 'axios'; import axios from 'axios';
import BridgedMessage from "../types/BridgedMessage"; import { ulid } from "ulid";
client.on('messageCreate', async message => { client.on('messageCreate', async message => {
try { try {
if (!message.content) return;
logger.debug(`[M] Discord: ${message.content}`); logger.debug(`[M] Discord: ${message.content}`);
const bridgeCfg = await BRIDGE_CONFIG.findOne({ discord: message.channelId }); const [ bridgeCfg, bridgedReply ] = await Promise.all([
BRIDGE_CONFIG.findOne({ discord: message.channelId }),
(message.reference?.messageId
? BRIDGED_MESSAGES.findOne({ "discord.messageId": message.reference.messageId })
: undefined
),
]);
if (message.webhookId && bridgeCfg?.discordWebhook?.id == message.webhookId) { if (message.webhookId && bridgeCfg?.discordWebhook?.id == message.webhookId) {
return logger.debug(`Discord: Message has already been bridged; ignoring`); return logger.debug(`Discord: Message has already been bridged; ignoring`);
} }
@ -25,38 +34,64 @@ client.on('messageCreate', async message => {
return logger.debug(`Discord: Lacking Masquerade permission; refusing to send`); return logger.debug(`Discord: Lacking Masquerade permission; refusing to send`);
} }
await axios.post( // Setting a known nonce allows us to ignore bridged
`${revoltClient.apiURL}/channels/${channel._id}/messages`, // messages while still letting other AutoMod messages pass.
const nonce = ulid();
await BRIDGED_MESSAGES.update(
{ "discord.messageId": message.id },
{ {
content: message.content, // todo: parse and normalize this $setOnInsert: {
//attachments: [], origin: 'discord',
//embeds: [], discord: {
//replies: [], messageId: message.id,
masquerade: { },
name: message.author.username, },
avatar: message.author.displayAvatarURL({ size: 128 }), $set: {
'revolt.nonce': nonce,
} }
}, },
{ { upsert: true }
headers: { );
'x-bot-token': process.env['REVOLT_TOKEN']!
const sendBridgeMessage = async (reply?: string) => {
await axios.post(
`${revoltClient.apiURL}/channels/${channel._id}/messages`,
{
content: message.content,
//attachments: [],
//embeds: [],
nonce: nonce,
replies: reply ? [ { id: reply, mention: !!message.mentions.repliedUser } ] : undefined,
masquerade: {
name: message.author.username,
avatar: message.author.displayAvatarURL({ size: 128 }),
}
},
{
headers: {
'x-bot-token': process.env['REVOLT_TOKEN']!
}
}
)
.then(async res => {
await BRIDGED_MESSAGES.update(
{ "discord.messageId": message.id },
{
$set: { "revolt.messageId": res.data._id },
}
);
})
.catch(async e => {
console.error(`Failed to send message`, e.response.data);
if (reply) {
console.info('Reytring without reply');
await sendBridgeMessage(undefined);
} }
}
)
.then(async res => {
await BRIDGED_MESSAGES.insert({
origin: 'discord',
discord: {
messageId: message.id,
},
revolt: {
messageId: res.data._id,
},
}); });
}) }
.catch(e => {
console.error(`Failed to send message`, e.response.data) await sendBridgeMessage(bridgedReply?.revolt?.messageId);
});
} catch(e) { } catch(e) {
console.error(e); console.error(e);
} }

View file

@ -28,4 +28,4 @@ for (const v of [ 'REVOLT_TOKEN', 'DISCORD_TOKEN', 'DB_STRING' ]) {
]); ]);
})(); })();
export { logger, BRIDGED_MESSAGES, BRIDGE_CONFIG } export { logger, db, BRIDGED_MESSAGES, BRIDGE_CONFIG }

View file

@ -2,14 +2,17 @@ import axios from "axios";
import { BRIDGED_MESSAGES, BRIDGE_CONFIG, logger } from ".."; import { BRIDGED_MESSAGES, BRIDGE_CONFIG, logger } from "..";
import { client } from "./client"; import { client } from "./client";
import { client as discordClient } from "../discord/client"; import { client as discordClient } from "../discord/client";
import { WebhookClient } from "discord.js";
client.on('message', async message => { client.on('message', async message => {
try { try {
if (!message.content || typeof message.content != 'string') return;
logger.debug(`[M] Revolt: ${message.content}`); logger.debug(`[M] Revolt: ${message.content}`);
const [ bridgedMsg, bridgeCfg ] = await Promise.all([ const [ bridgeCfg, bridgedMsg, ...repliedMessages ] = await Promise.all([
BRIDGED_MESSAGES.findOne({ "revolt.messageId": message._id }),
BRIDGE_CONFIG.findOne({ revolt: message.channel_id }), BRIDGE_CONFIG.findOne({ revolt: message.channel_id }),
BRIDGED_MESSAGES.findOne({ "revolt.nonce": message.nonce }),
//...(message.reply_ids?.map(id => BRIDGED_MESSAGES.findOne({ "revolt.messageId": id })) ?? [])
]); ]);
if (bridgedMsg) return logger.debug(`Revolt: Message has already been bridged; ignoring`); if (bridgedMsg) return logger.debug(`Revolt: Message has already been bridged; ignoring`);
@ -19,42 +22,44 @@ client.on('message', async message => {
return logger.debug(`Revolt: No Discord webhook stored`); return logger.debug(`Revolt: No Discord webhook stored`);
} }
await BRIDGED_MESSAGES.insert({ await BRIDGED_MESSAGES.update(
origin: 'revolt', { 'revolt.messageId': message._id },
discord: {}, {
revolt: { $set: {
messageId: message._id, revolt: {
messageId: message._id,
nonce: message.nonce,
},
},
$setOnInsert: {
discord: {},
origin: 'revolt',
}
}, },
{ upsert: true }
);
const client = new WebhookClient({
id: bridgeCfg.discordWebhook.id,
token: bridgeCfg.discordWebhook.token,
}); });
axios.post( client.send({
`https://discord.com/api/v9/webhooks/${bridgeCfg.discordWebhook.id}/${bridgeCfg.discordWebhook.token}?wait=true`, content: `${message.content}`,
{ username: message.author?.username ?? 'Unknown user',
content: message.content, avatarURL: message.author?.generateAvatarURL({ max_side: 128 }),
username: message.author?.username ?? 'Unknown user', })
avatar_url: message.author?.generateAvatarURL({ max_side: 128 }),
},
{
headers: {
"Authorization": `Bot ${discordClient.token}`
}
}
)
.then(async res => { .then(async res => {
await BRIDGED_MESSAGES.update({ await BRIDGED_MESSAGES.update({
revolt: { "revolt.messageId": message._id
messageId: message._id
}
}, { }, {
$set: { $set: {
discord: { "discord.messageId": res.id
messageId: res.data._id
}
} }
}); });
}) })
.catch(e => { .catch(async e => {
console.error('Failed to execute webhook', e.response.data); console.error('Failed to execute webhook', e?.response?.data ?? e);
}); });
} catch(e) { } catch(e) {
console.error(e); console.error(e);

View file

@ -7,5 +7,6 @@ export default class {
revolt: { revolt: {
messageId?: string; messageId?: string;
nonce?: string;
} }
} }