k44Eqha/mppbridger.js

213 lines
6.8 KiB
JavaScript
Raw Normal View History

2022-01-04 04:21:13 +01:00
var Client = require('./lib/Client.js');
2022-01-04 04:04:16 +01:00
global.createMPPbridge = async function createMPPbridge({room, channel, uri}) {
channel = dClient.channels.resolve(channel);
var webhooks = await channel.fetchWebhooks();
2022-01-04 05:40:43 +01:00
var webhook = webhooks.filter(w => w.token).first() || await channel.createWebhook("sdfadffg");
2022-01-04 06:02:27 +01:00
//todo figure out new way to buffer
2022-01-04 06:06:31 +01:00
function dSend(msg, options = {}) {
if (msg) options.content = msg;
2022-01-04 06:02:27 +01:00
if (options.content?.length > 2000) {
options.attachments ||= [];
options.attachments.push(new Discord.MessageAttachment(Buffer.from(options.content), "message.txt"));
delete options.content;
}
2022-01-04 05:40:43 +01:00
2022-01-04 06:02:27 +01:00
let username = gClient.channel && gClient.channel._id || room;
if (username.length > 80) username = username.substr(0,79) + '…';
2022-01-04 05:40:43 +01:00
2022-01-04 06:02:27 +01:00
webhook.send(options).catch(error => {
handleError(error, `webhook fail in ${channel.id}`);
channel.send(options).catch(error => handleError(error, `send fail in ${channel.id} after webhook send fail`));
});
2022-01-04 05:40:43 +01:00
}
2022-01-04 04:04:16 +01:00
const gClient = new Client(uri);
if (uri == "wss://mppclone.com:8443") gClient.token = config.mpc_token; //todo hmm
gClient.setChannel(room, {visible:false});
gClient.start();
2018-09-04 08:36:06 +02:00
// maintain the client's presence in the channel
2018-09-03 23:01:13 +02:00
gClient.channelCorrectorInterval = setInterval(()=>{
// if client is connected and not in a channel (meaning setChannel failed due to ratelimit because another client joined a channel with the same user within the last second) OR client is in a channel but it is not the right channel…
if ((gClient.isConnected() && !gClient.channel) || (gClient.channel && gClient.channel._id != room))
// …set the channel!
gClient.setChannel(room, {visible:false});
2018-09-03 23:01:13 +02:00
}, 1000);
2018-11-29 21:37:29 +01:00
let lastError;
2018-11-29 00:13:10 +01:00
gClient.on("error", error => {
2022-01-04 05:40:43 +01:00
handleError(error, `[${uri}][${room}]`);
2018-11-29 21:37:29 +01:00
error = error.toString();
if (lastError != error) {
dSend(`**${error.toString()}**`);
lastError = error;
}
2018-11-29 00:13:10 +01:00
});
2018-09-04 08:36:06 +02:00
var isConnected = false; // TODO use gClient.isConnected() ?
gClient.on('connect', () => {
2022-01-04 04:04:16 +01:00
console.log(`[${uri}][${room}] Connected to server`);
2018-11-29 22:16:39 +01:00
dSend(`**Connected to server; joining channel…**`);
isConnected = true;
2018-11-29 22:16:39 +01:00
lastError = undefined;
});
2018-07-14 07:04:28 +02:00
gClient.on('hi', ()=>{
2022-01-04 04:04:16 +01:00
console.log(`[${uri}][${room}] Received greeting`);
2018-11-30 23:50:08 +01:00
if (!testmode) {
2022-01-04 04:04:16 +01:00
gClient.sendArray([{m: "userset", set: {name: config.mppname }}]);
2018-11-30 23:50:08 +01:00
}
2018-12-01 08:40:20 +01:00
gClient.sendArray([{m:'m',x:Math.floor(Math.random()*100),y:Math.floor(Math.random()*100)}])
2018-07-14 07:04:28 +02:00
});
gClient.on('disconnect', () => {
if (isConnected) {
2022-01-04 04:04:16 +01:00
console.log(`[${uri}][${room}] Disconnected from server`);
2018-09-04 08:36:06 +02:00
dSend(`**Disconnected from server**`);
isConnected = false;
}
});
/*gClient.on('status', status => {
2022-01-04 04:04:16 +01:00
console.log(`[${uri}] [${room}] ${status}`);
});*/
2018-09-04 08:36:06 +02:00
// on channel change
{
let lastCh;
gClient.on('ch', async msg => {
// announce channel join
if (!lastCh) {
dSend(`**Joined channel \`${msg.ch._id}\`**`);
2022-01-04 04:04:16 +01:00
console.log(`[${uri}][${room}] Joined channel ${msg.ch._id}`);
}
2018-09-04 08:36:06 +02:00
// announce channel change
else if (msg.ch._id !== lastCh) {
dSend(`**Channel changed from \`${lastCh}\` to \`${msg.ch._id}\`**`);
2022-01-04 04:04:16 +01:00
console.log(`[${uri}][${room}] Channel changed from ${lastCh} to ${msg.ch._id}`);
}
2018-09-04 08:36:06 +02:00
lastCh = msg.ch._id;
});
gClient.on("disconnect", () => lastCh = undefined);
2018-09-04 08:36:06 +02:00
}
// MPP to Discord
2018-09-04 08:36:06 +02:00
gClient.on('a', async msg => {
if (msg.p._id == gClient.getOwnParticipant()._id) return;
var id = msg.p._id.substr(0,6);
var name = sanitizeName(msg.p.name);
var content = escapeDiscordMentions(msg.a);
var str = `\`${id}\` **${name}:** ${content}`;
dSend(str);
});
// Discord to MPP
{
let msgQueue = [];
2018-09-04 08:36:06 +02:00
dClient.on('message', async message => {
2022-01-04 04:04:16 +01:00
if (message.channel.id !== channel.id || message.author.id == dClient.user.id || !message.member /*|| message.content.startsWith('!')*/) return;
var str = message.cleanContent;
2018-10-03 21:06:20 +02:00
var aname = `${message.member.displayName}#${message.member.user.discriminator}`;
if (str.startsWith('/') || str.startsWith('\\'))
2018-10-03 21:06:20 +02:00
msgQueue.push(`${aname}`);
else
2018-10-03 21:06:20 +02:00
str = `${aname}: ${str}`;
if (str.startsWith('\\')) str = str.slice(1);
if (message.attachments.first()) str += ' '+message.attachments.first().url;
if (str.length > 512) str = str.substr(0,511) + '…';
msgQueue.push(str);
});
setInterval(()=>{
let message = msgQueue.shift();
if (message) gClient.sendArray([{m:'a', message}]);
}, 1600); // just about fastest without exceeding quota; I figured quota is 4 messages per 6 seconds in lobbies
}
// announce join/leave/rename
gClient.prependListener("p", async participant => {
if (gClient.ppl[participant.id]) { // is update
let oldName = gClient.ppl[participant.id].name, newName = participant.name;
if (newName != oldName)
dSend(`\`${participant._id.substr(0,6)}\` ___**${sanitizeName(oldName)}** changed their name to **${sanitizeName(newName)}**___`);
} else { // is join
dSend(`\`${participant._id.substr(0,6)}\` ___**${sanitizeName(participant.name)}** entered the room.___`);
}
});
gClient.prependListener("bye", async msg => {
2018-12-14 07:09:57 +01:00
var participant = gClient.ppl[msg.p];
dSend(`\`${participant._id.substr(0,6)}\` ___**${sanitizeName(participant.name)}** left the room.___`);
});
2018-09-04 08:36:06 +02:00
// on notifications
gClient.on('notification', async msg => {
// show notification
2022-01-04 06:06:31 +01:00
dSend(undefined, {embeds:[{
title: msg.title,
description: msg.text || msg.html
2022-01-04 05:40:43 +01:00
}]});
// handle bans
if (msg.text && (msg.text.startsWith('Banned from "'+room+'"') || msg.text.startsWith('Currently banned from "'+room+'"'))) {
// Banned from "{room}" for {n} minutes.
// Currently banned from "{room}" for {n} minutes.
let arr = msg.text.split(' ');
arr.pop();
let minutes = arr.pop();
gClient.stop();
setTimeout(()=>{
gClient.setChannel(room);
gClient.start();
}, minutes*60*1000+3000);
dSend(`**Attempting to rejoin in ${minutes} minutes.**`);
}
});
// make room invisible when nobody else is in it
2018-09-04 08:36:06 +02:00
gClient.on("ch", async function(msg){
if (gClient.isOwner()) {
if (gClient.countParticipants() <= 1) {
gClient.sendArray([{m:'chset', set: { visible: false }}])
} else {
gClient.sendArray([{m:'chset', set: { visible: true }}])
}
}
});
// addons
{
// record raw data
2022-01-04 04:21:13 +01:00
let createWSMessageCollector = require("./datacollector")
gClient.on("message", createWSMessageCollector(async function(data, startDate, endDate){
2022-01-04 04:04:16 +01:00
var attachmentName = `${uri} ${room} raw data recording from ${startDate.toISOString()} to ${endDate.toISOString()} .txt.gz`;
await channel.send(new Discord.MessageAttachment(data, attachmentName));
}));
}
2022-01-04 04:04:16 +01:00
return gClient;
2018-07-14 05:31:56 +02:00
};
// start
(async function () {
2022-01-04 04:04:16 +01:00
global.bridges = require("./bridges");
for (let bridge of bridges) {
try {
bridge.client = await createMPPbridge(bridge);
} catch(e) {
2022-01-04 05:40:43 +01:00
handleError(error, JSON.stringify(bridge));
2022-01-04 04:04:16 +01:00
}
}
2022-01-04 04:04:16 +01:00
})();