-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpurge.js
61 lines (53 loc) · 2.22 KB
/
purge.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
// Importing necessary modules and initializing database models
const { SlashCommandBuilder } = require('discord.js');
const { Player } = require('../dbinit.js');
const Sequelize = require('sequelize');
// Define the command for purging inactive or duplicate players based on update time
module.exports = {
data: new SlashCommandBuilder()
.setName('purge')
.setDescription('Deletes all players who are inactive/lower elo duplicates'),
async execute(interaction) {
try {
// Define the date 6 months ago from the current date
const sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
// Fetching all players from the database
const players = await Player.findAll();
// Grouping players by handle
const groupedByHandle = players.reduce((acc, player) => {
acc[player.handle] = acc[player.handle] || [];
acc[player.handle].push(player);
return acc;
}, {});
// Identifying duplicates and inactive players
let toDelete = [];
for (const handle in groupedByHandle) {
if (groupedByHandle[handle].length > 1) {
// Sort duplicates by ELO, highest first
groupedByHandle[handle].sort((a, b) => b.elo - a.elo);
// All except the highest ELO are considered lower ELO duplicates
toDelete.push(...groupedByHandle[handle].slice(1));
}
// Add inactive players to the deletion list
groupedByHandle[handle].forEach(player => {
if (new Date(player.updatedAt) < sixMonthsAgo) {
toDelete.push(player);
}
});
}
// Removing duplicates from the deletion list
toDelete = toDelete.filter((value, index, self) =>
index === self.findIndex((t) => (t.id === value.id)));
// Deleting identified players from the database
for (const player of toDelete) {
await player.destroy();
}
// Sending confirmation message
return interaction.reply(`Purged ${toDelete.length} players from the database.`);
} catch (error) {
// Handling errors during database operations
return interaction.reply('Something went wrong during the purge process' + `\n\`` + error + `\``);
}
}
}