Skip to content

Commit

Permalink
Merge pull request #73 from clienterrverse/main
Browse files Browse the repository at this point in the history
Updating the code in my branch
  • Loading branch information
GrishMahat authored Aug 8, 2024
2 parents ec2599a + 31a690e commit 80c70d7
Show file tree
Hide file tree
Showing 19 changed files with 1,164 additions and 1,084 deletions.
646 changes: 50 additions & 596 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,21 @@
"homepage": "https://github.com/clienterrverse/clienterrverse_economy#readme",
"description": "",
"dependencies": {
"@napi-rs/canvas": "^0.1.53",
"axios": "^1.7.2",
"bottleneck": "^2.19.5",
"canvas": "^2.11.2",
"colors": "^1.4.0",
"date-fns": "^3.6.0",
"discord-arts": "^0.6.1",
"discord-html-transcripts": "^3.2.0",
"discord.js": "^14.15.3",
"mathjs": "^12.4.2",
"mathjs": "^13.0.3",
"mongoose": "^8.5.2",
"nanoid": "^5.0.7",
"os": "^0.1.2"
},
"devDependencies": {
"dotenv": "^16.4.5",
"nodemon": "^3.1.1",
"prettier": "3.3.2"
"prettier": "3.3.3"
}
}
1 change: 1 addition & 0 deletions src/commands/developer/dm.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export default {
testMode: false,
devOnly: true,
category: 'Devloper',
prefix: true,

run: async (client, interaction) => {
const subcommand = interaction.options.getSubcommand();
Expand Down
1 change: 0 additions & 1 deletion src/commands/developer/emojiapp.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import axios from 'axios';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { createCanvas, loadImage } from 'canvas';

const data = new SlashCommandBuilder()
.setName('emoji-app')
Expand Down
159 changes: 90 additions & 69 deletions src/commands/economy/leaderboard.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
import { Balance } from '../../schemas/economy.js';
import pagination from '../../utils/buttonPagination.js';
import mongoose from 'mongoose';

const ITEMS_PER_PAGE = 12;
const LEADERBOARD_LIMIT = 50;

export default {
data: new SlashCommandBuilder()
Expand All @@ -18,81 +20,100 @@ export default {
category: 'economy',

run: async (client, interaction) => {
// Defer the interaction
await interaction.deferReply();

// Use aggregation to fetch user balances sorted by the sum of balance and bank in descending order
const balances = await Balance.aggregate([
{
$project: {
userId: 1,
balance: 1,
bank: 1,
totalBalance: { $add: ['$balance', '$bank'] },
},
},
{
$sort: { totalBalance: -1 },
},
{
$limit: 50,
},
]).exec();
try {
const balances = await fetchBalances();
if (balances.length === 0) {
return interaction.editReply('No users found in the leaderboard.');
}

const leaderboardEntries = await createLeaderboardEntries(
client,
balances
);
const pages = createLeaderboardPages(leaderboardEntries);

if (balances.length === 0) {
return interaction.editReply('No users found in the leaderboard.');
await pagination(interaction, pages);
} catch (error) {
console.error('Error in leaderboard command:', error);
await interaction.editReply(
'An error occurred while fetching the leaderboard.'
);
}
},
};

// Function to fetch user details
const fetchUserDetails = async (userId) => {
try {
const user = await client.users.fetch(userId);
return user.tag;
} catch {
return 'Unknown User';
}
};
async function fetchBalances() {
return Balance.aggregate([
{
$project: {
userId: 1,
balance: 1,
bank: 1,
totalBalance: { $add: ['$balance', '$bank'] },
},
},
{ $sort: { totalBalance: -1 } },
{ $limit: LEADERBOARD_LIMIT },
]).exec();
}

// Create an array to hold the leaderboard entries
const leaderboardEntries = await Promise.all(
balances.map(async (balance, index) => {
const userTag = await fetchUserDetails(balance.userId);
const totalBalance = balance.totalBalance;
return {
index: index + 1,
userTag,
totalBalance,
wallet: balance.balance,
bank: balance.bank,
};
})
);
console.log('leaderboardEntries');
async function createLeaderboardEntries(client, balances) {
return Promise.all(
balances.map(async (balance, index) => {
const userTag = await fetchUserTag(client, balance.userId);
return {
index: index + 1,
userTag,
totalBalance: balance.totalBalance,
wallet: balance.balance,
bank: balance.bank,
};
})
);
}

// Split leaderboard entries into pages of 10 entries each
const itemsPerPage = 12;
const pages = [];
for (let i = 0; i < leaderboardEntries.length; i += itemsPerPage) {
const pageEntries = leaderboardEntries.slice(i, i + itemsPerPage);
const fields = pageEntries.map((entry) => ({
name: `${entry.index === 1 ? 'πŸ₯‡' : entry.index === 2 ? 'πŸ₯ˆ' : entry.index === 3 ? 'πŸ₯‰' : 'πŸ…'} **${entry.index}. ${entry.userTag}**`,
value: `Total: ${entry.totalBalance.toLocaleString()} coins\nWallet: ${entry.wallet.toLocaleString()} | Bank: ${entry.bank.toLocaleString()}`,
inline: true,
}));
async function fetchUserTag(client, userId) {
try {
const user = await client.users.fetch(userId);
return user.tag;
} catch {
return 'Unknown User';
}
}

const embed = new EmbedBuilder()
.setTitle('πŸ† Leaderboard')
.addFields(fields)
.setColor(0xffd700) // Gold color
.setFooter({
text: `Page ${Math.floor(i / itemsPerPage) + 1} of ${Math.ceil(leaderboardEntries.length / itemsPerPage)}`,
});
function createLeaderboardPages(entries) {
const pages = [];
for (let i = 0; i < entries.length; i += ITEMS_PER_PAGE) {
const pageEntries = entries.slice(i, i + ITEMS_PER_PAGE);
const embed = createPageEmbed(pageEntries, i, entries.length);
pages.push(embed);
}
return pages;
}

pages.push(embed);
console.log(i);
}
function createPageEmbed(entries, startIndex, totalEntries) {
const fields = entries.map((entry) => ({
name: `${getRankEmoji(entry.index)} **${entry.index}. ${entry.userTag}**`,
value: formatEntryValue(entry),
inline: true,
}));

// Use pagination to display the leaderboard
await pagination(interaction, pages);
},
};
return new EmbedBuilder()
.setTitle('πŸ† Leaderboard')
.addFields(fields)
.setColor(0xffd700)
.setFooter({
text: `Page ${Math.floor(startIndex / ITEMS_PER_PAGE) + 1} of ${Math.ceil(totalEntries / ITEMS_PER_PAGE)}`,
});
}

function getRankEmoji(rank) {
const emojis = ['πŸ₯‡', 'πŸ₯ˆ', 'πŸ₯‰'];
return emojis[rank - 1] || 'πŸ…';
}

function formatEntryValue(entry) {
return `Total: ${entry.totalBalance.toLocaleString()} coins\nWallet: ${entry.wallet.toLocaleString()} | Bank: ${entry.bank.toLocaleString()}`;
}
Loading

0 comments on commit 80c70d7

Please sign in to comment.