-
Notifications
You must be signed in to change notification settings - Fork 2
/
discordBridge.js
210 lines (175 loc) · 6.67 KB
/
discordBridge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
module.exports = function(IS_DEV) {
const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = process.env.DISCORD_BOT_TOKEN;
const SUBSCRIBE_REACT = '🔔'; //'👀';
const UNSUBSCRIBE_REACT = '🔕'; //'😴';
// invite link
// https://discord.com/oauth2/authorize?client_id=760107519971950643&permissions=268443648&redirect_uri=&scope=bot
let connected = false;
let lastGames = [];
function isSuitableChannel(channel) {
if (channel.type != "text" || channel.deleted)
return false;
if (!channel.guild.me.permissionsIn(channel).has(Discord.Permissions.FLAGS.VIEW_CHANNEL | Discord.Permissions.FLAGS.SEND_MESSAGES | Discord.Permissions.FLAGS.ADD_REACTIONS | Discord.Permissions.FLAGS.MANAGE_CHANNELS))
return false;
return true;
}
function getInviteRole(guild) {
const role = guild.me.roles.cache.find(role => role.editable && role.name.toLowerCase().includes("invite"));
if (!role)
console.error(`could not find invite role in guild '${guild.name}'!`);
return role;
}
async function initializeGuild(guild) {
const guid = guild.id;
if (IS_DEV && guid != "763763925140635659")
return;
try {
if (!guild.me.hasPermission(Discord.Permissions.FLAGS.MANAGE_ROLES))
return console.error(`No MANAGE_ROLES permission in guild '${guild.name}'!`);
if (!getInviteRole(guild))
return;
for (const [cuid, channel] of guild.channels.cache) {
if (!isSuitableChannel(channel))
continue;
const messages = await channel.messages.fetch({ limit: 50 }).catch(console.error);
const lastSelfMessage = messages.find(m => m.author && m.author.id == client.user.id);
if (lastSelfMessage)
existingMessages[guid] = new Promise(resolve => resolve(lastSelfMessage));
console.log(`found channel '${channel.name}' in guild '${guild.name}'.`);
broadcastToGuild(guild, true);
return;
}
console.log(`could not find channel in guild '${guild.name}' with required permissions!`);
existingMessages[guid] = undefined;
} catch (ex) {
console.error(ex);
}
}
client.on("roleUpdate", (_, role) => {
if (role.members.get(role.guild.me.id))
initializeGuild(role.guild);
});
client.on("channelUpdate", (_, channel) => {
initializeGuild(channel.guild);
});
client.on("guildMemberUpdate", (_, member) => {
console.log(member.id);
if (member.id == member.guild.me.id)
initializeGuild(member.guild);
});
client.on("ready", async _ => {
connected = true;
await Promise.all(client.guilds.cache.map(initializeGuild));
});
client.login(TOKEN);
function handleReact(reaction, user, added) {
if (reaction.message.member && reaction.message.member.id == client.user.id && !reaction.me) {
const role = getInviteRole(reaction.message.guild);
if (role) {
const member = reaction.message.guild.members.cache.find(member => member.id === user.id);
if (member) {
if (reaction.emoji.name == SUBSCRIBE_REACT) {
member.roles.add(role).catch(console.warn);
reaction.message.reactions.cache.get(UNSUBSCRIBE_REACT).users.remove(user.id).catch(console.warn);
} else if (reaction.emoji.name == UNSUBSCRIBE_REACT) {
member.roles.remove(role).catch(console.warn);
reaction.message.reactions.cache.get(SUBSCRIBE_REACT).users.remove(user.id).catch(console.warn);
}
}
}
}
}
client.on("messageReactionAdd", (reaction, user) => handleReact(reaction, user, true));
// client.on("messageReactionRemove", (reaction, user) => handleReact(reaction, user, false));
let existingMessages = {};
function createMessage(ping, roleId) {
const embed = new Discord.MessageEmbed();
// embed.setColor('#000000');
embed.setTitle('Public Games');
// embed.setAuthor('Some name', 'https://i.imgur.com/wSTFkRM.png', 'https://discord.js.org')
//.setDescription('Some description here')
// embed.setThumbnail('https://i.imgur.com/wSTFkRM.png')
const descriptions = [];
for (const game of lastGames) {
let timeStr = "";
if (game.time.start[0] == -1)
timeStr = "unlimited time";
else {
const formatF = x => x < 1000 ? "." + x/100 : x / 1000 % 60 == 0 ? x/60000 + "m" : x/1000;
const andSign = "+";
const scaleSign = "N";
if (game.time.incr)
timeStr += andSign + formatF(game.time.incr);
if (game.time.incrScale)
timeStr += andSign + formatF(game.time.incrScale) + scaleSign;
if (game.time.grace || game.time.graceScale) {
if (game.time.grace && game.time.graceScale)
timeStr += andSign + "(" + formatF(game.time.grace) + andSign + formatF(game.time.graceScale) + scaleSign + ")";
else
timeStr += andSign + "(" + formatF(game.time.grace || game.time.graceScale) + (game.time.graceScale ? scaleSign : "") + ")";
}
if (!timeStr.length)
timeStr = andSign + "0";
timeStr = (game.time.start[0] / 60000 % 60 == 0 ? game.time.start[0]/60/60/1000 + "h" : game.time.start[0] / 1000 % 60 == 0 ? game.time.start[0]/60/1000 : game.time.start[0]/1000 + "s") + timeStr;
}
if (!game.started)
descriptions.push(`**[join](https://multiversechess.com/${game.shortCode})** - **${game.mode}** - **${timeStr}** - vs ${game.opponent.name}`);
else
descriptions.push(`**[spectate](https://multiversechess.com/${game.shortCode})** - **${game.mode}** - **${timeStr}** - ${game.players[1].name} vs ${game.players[0].name}`);
}
if (lastGames.length == 0)
embed.setDescription("No games :(");
else
embed.setDescription(descriptions.join('\n'));
// embed.setTimestamp();
embed.setFooter('multiversechess.com');
return {
content: (IS_DEV ? "THIS IS A TEST " : "") + (ping ? `<@${IS_DEV ? '180017294657716225' : '&' + roleId}>` : ''),
embed: embed,
};
}
function broadcastToGuild(guild, silent, ping) {
const guid = guild.id;
if (existingMessages[guid]) {
if (silent) {
const role = getInviteRole(guild);
existingMessages[guid].then(message => {
message.edit(createMessage(false, role.id).embed).catch(console.error);
});
return;
} else {
existingMessages[guid].then(message => {
message.delete().catch(console.error);
});
}
}
for (const [cuid, channel] of guild.channels.cache) {
if (!isSuitableChannel(channel))
continue;
const role = getInviteRole(guild);
if (role) {
const msg = channel.send(createMessage(ping && lastGames.length, role.id)).catch(console.error);
existingMessages[guid] = msg;
msg.then(msg => {
if (lastGames.length && !ping)
msg.edit(createMessage(true, role.id)).catch(console.error);
msg.react(SUBSCRIBE_REACT).then(_ => msg.react(UNSUBSCRIBE_REACT).catch(console.error)).catch(console.error)
});
break;
}
}
}
function broadcast(silent, ping) {
for (const [guid, guild] of client.guilds.cache)
broadcastToGuild(guild, silent, ping);
}
return {
update: function(games, silent, ping) {
lastGames = games;
if (connected)
broadcast(silent, ping);
},
};
};