forked from MT-CTF/ctf-discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
272 lines (222 loc) · 7.97 KB
/
index.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
const Discord = require("discord.js");
const fs = require("fs/promises");
const client = new Discord.Client();
const statsPath = process.env.STATS;
const oldStatsPath = process.env.OLD_STATS;
const rankingsChannel = process.env.RANKINGS_CHANNEL;
const prefix = "!";
let STAFF_MESSAGES = []
async function readStats(path) {
const content = (await fs.readFile(path)).toString();
let list = {};
const raw = JSON.parse(JSON.parse(content).players);
for (let key in raw) {
list[key.toLowerCase()] = raw[key];
}
const orderedList = Object.values(list).sort((a, b) => b.score - a.score);
orderedList.forEach((stats, i) => {
stats.place = i + 1;
});
return [list, orderedList];
}
let oldStatsList = null;
let statsList = null;
async function updateStats() {
const ret = await readStats(statsPath);
statsList = ret[0];
updateRankingsChannel(ret[1]);
}
async function updateOldStats() {
oldStatsList = (await readStats(oldStatsPath))[0];
}
updateStats();
updateOldStats();
setInterval(updateStats, 30000);
function formatLeaderboard(list) {
const rankingsEmbed = new Discord.MessageEmbed()
.setColor("#0099ff")
.setTitle("CTF Rankings")
const max = 60;
for (var i = 0; i < max; i += 20) {
const from = i;
const to = i + 20
const newContent = list.slice(from, to)
.map(stats => {
let kd = stats.kills;
if (stats.deaths > 1) {
kd /= stats.deaths;
}
stats.name = stats.name.replace("_", "\\_")
return `**${stats.place}. ${stats.name}**\nK/D: ${kd.toFixed(1)} - Score: *${Math.round(stats.score)}*`;
})
.join("\n");
rankingsEmbed.addField(`__Top ${from+1} - ${to}__`, newContent, true)
}
return rankingsEmbed;
}
async function updateRankingsChannel(list) {
if (!rankingsChannel) {
return;
}
const channel = client.channels.cache.get(rankingsChannel);
if (!channel) {
return;
}
const rankingsEmbed = formatLeaderboard(list);
const messages = await channel.messages.fetch({ limit: 1 });
if (messages.size == 0) {
channel.send(rankingsEmbed);
} else {
const message = messages.first();
message.edit(rankingsEmbed);
}
}
function ordinalSuffixOf(i) {
var j = i % 10, k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
function formatRanking(stats) {
let kd = stats.kills;
if (stats.deaths > 1) {
kd /= stats.deaths;
}
const fields = [
{ name: "Kills", value: stats.kills, inline: true },
{ name: "Deaths", value: stats.deaths, inline: true },
{ name: "K/D", value: kd.toFixed(1), inline: true },
{ name: "Bounty kills", value: stats.bounty_kills, inline: true },
{ name: "Captures", value: stats.captures, inline: true },
{ name: "Attempts", value: stats.attempts, inline: true },
]
return new Discord.MessageEmbed()
.setColor("#0099ff")
.setTitle(`${stats.name}, ${ordinalSuffixOf(stats.place)}`)
.setDescription(`${stats.name} is in ${ordinalSuffixOf(stats.place)} place, with ${Math.round(stats.score)} score.`)
.addFields(fields)
.setTimestamp();
}
function handleRankRequest(rankList, message, command, args) {
if (!rankList) {
message.channel.send("Please wait, stats are still loading...");
return;
}
const username = message.author.username;
const nickname = message.member.nickname || username;
let stats;
if (args.length == 0) {
stats = rankList[nickname.toLowerCase()] || rankList[username.toLowerCase()];
if (!stats) {
message.channel.send(`Unable to find ${nickname} or ${username}, please provide username explicitly like so: \`!rank username\``);
return;
}
} else {
stats = rankList[args[0].trim().toLowerCase()];
if (!stats) {
message.channel.send(`Unable to find user ${args[0]}`);
return;
}
}
message.channel.send(formatRanking(stats));
if (args.length > 0 && stats.name.toLowerCase() == nickname.toLowerCase()) {
message.channel.send(`_pst: you can just use \`!${command}\`_`);
}
}
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", message => {
if (message.content[0] != prefix) {
return;
}
const args = message.content.slice(prefix.length).trim().split(" ");
const command = args.shift().toLowerCase();
if (command == "rank" || command == "r" || command == "rankings") {
handleRankRequest(statsList, message, command, args);
} else if (command == "oldrank") {
handleRankRequest(oldStatsList, message, command, args);
} else if (command == "oldleaders") {
const orderedList = Object.values(oldStatsList).sort((a, b) => b.score - a.score);
message.channel.send(formatLeaderboard(orderedList));
} else if (command == "leaders") {
if (rankingsChannel) {
message.channel.send(`<#${rankingsChannel}>`);
} else {
const orderedList = Object.values(statsList).sort((a, b) => b.score - a.score);
message.channel.send(formatLeaderboard(orderedList));
}
} else if (command == "help") {
const helpEmbed = new Discord.MessageEmbed()
.setTitle("Commands")
.setColor("#0000E5")
.addField(prefix + "rank", "Shows ingame rankings", false)
.addField(prefix + "oldrank", "Shows old rankings", false)
.addField(prefix + "leaders", "Shows the top 60 leaderboard or links to the dedicated channel for it", false)
.addField(prefix + "oldleaders", "Shows old top 60 leaderboard", false)
.addField(prefix + "help", "Shows the available commands", false)
.addField(prefix + "mute <@username>", "Mutes a user", false)
.addField(prefix + "unmute <@username>", "Unmutes a user", false)
return message.channel.send(helpEmbed);
} else if (command == "mute") {
if (!message.member.hasPermission("KICK_MEMBERS"))
return message.reply("You dont have the permission to run this command");
let muteuser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!muteuser)
return message.reply("Couldn't find user");
if (muteuser.hasPermission("KICK_MEMBERS"))
return message.reply("Can't mute them, the user you are trying to mute is a staff member!");
let muterole = message.guild.roles.cache.find(role => role.name === "Muterated");
muteuser.roles.add(muterole.id);
message.reply(`<@${muteuser.id}> has been muted`);
} else if (command == "unmute") {
if (!message.member.hasPermission("KICK_MEMBERS"))
return message.reply("You dont have the permission to run this command");
let unmuteuser = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!unmuteuser)
return message.reply("Couldn't find user");
let muterole = message.guild.roles.cache.find(role => role.name === "Muterated");
(unmuteuser.roles.remove(muterole.id));
message.reply(`<@${unmuteuser.id}> has been unmuted`);
} else if (command == "st" || command == "x") {
if (!message.member.hasPermission("KICK_MEMBERS"))
return message.reply("You dont have the permission to run this command");
STAFF_MESSAGES.push(`<${message.member.user.username}@Discord> ${message.content.slice(prefix.length).trim()}`);
//message.reply("Staff channel message sent");
message.react('☑️');
} else if (command == "players") {
PLAYERS.push(`<${message.member.user.username}@Discord> ${message.content.slice(prefix.length).trim()}`);
}
});
client.login(process.env.TOKEN);
var http = require('http');
http.createServer(function (req, res) {
if (req.method == "GET" && STAFF_MESSAGES.length > 0) {
res.writeHead(200, {'Content-Type': 'text/plain'});
console.log("Relaying staff messages: " + STAFF_MESSAGES.join("-|-"));
res.write(JSON.stringify(STAFF_MESSAGES));
STAFF_MESSAGES = [];
} /* else if (req.method == "PUT") {
req.on("data", (chunk) => {
console.log(chunk.toString());
});
} */
res.writeHead(200);
res.end();
}).listen(31337);
http.createServer(function (req, res) {
if (req.method == "GET" && PLAYERS.length > 0) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(JSON.stringify(PLAYERS));
PLAYERS = [];
}
res.writeHead(200);
res.end();
}).listen(31338);