diff --git a/commands/100-games/leaderboard.js b/commands/100-games/leaderboard.js new file mode 100644 index 0000000..ab0f7cb --- /dev/null +++ b/commands/100-games/leaderboard.js @@ -0,0 +1,33 @@ +const { SlashCommandBuilder, EmbedBuilder } = require('discord.js'); +const { getLeaderboardEntries } = require('../../databaseHelperFunctions.js'); + + +module.exports = { + data: new SlashCommandBuilder() + .setName('leaderboard') + .setDescription('Show the leaderboard!'), + async execute(interaction) { + const leaderboard = await getLeaderboardEntries(); + + if (!leaderboard) return interaction.reply('There was a problem!'); + + await leaderboard.sort((a, b) => parseInt(b.count) - parseInt(a.count)); + let desc = ''; + + for (let i = 0; i < leaderboard.length; i++) { + let newLine = ''; + newLine = newLine.concat((i + 1), '. \t', leaderboard[i].username, ' - ', leaderboard[i].count, ' games\n'); + desc = desc.concat(newLine); + } + + const embed = new EmbedBuilder() + .setColor(0x6441a5) + .setTitle('The 100 Games Challenge Leaderboard!') + .setDescription(desc) + .setFooter({ text: 'The Ochulus • 100 Games Challenge', iconURL: interaction.client.user.avatarURL() }) + .setTimestamp(); + + + return interaction.reply({ embeds: [embed] }); + }, +}; \ No newline at end of file diff --git a/databaseHelperFunctions.js b/databaseHelperFunctions.js index 8ee8a76..68259ea 100644 --- a/databaseHelperFunctions.js +++ b/databaseHelperFunctions.js @@ -140,6 +140,30 @@ async function deleteBeatenGameNum(num, user) { return entry; } +async function getLeaderboardEntries() { + const users = await Users.findAll() + .catch((err) => { + console.log(err); + }); + + const results = []; + + for (let i = 0; i < users.length; i++) { + const count = await BeatenGames.count({ where: { userId: users[i].id } }); + + const res = await Users.findOne({ where: { id: users[i].id } }) + .catch((err) => { + console.log(err); + }); + const username = res.username; + + const fun = { username, count }; + results.push(fun); + } + + return results; +} + module.exports = { checkUserRegistration, getUserRegistration, @@ -149,4 +173,5 @@ module.exports = { deleteBeatenGameId, deleteBeatenGameNum, checkGameStorageId, + getLeaderboardEntries, }; \ No newline at end of file