Reputation: 29
I am building a code ,in Discord.js library with Node.js, of an Invite LeaderBoard command !
The code i am using is :
module.exports = {
name: 'leaderboard',
description: 'Invites Leader Board',
async execute(message, args, Discord, client){
const { guild } = message
guild.fetchInvites().then((invites) => {
const inviteCounter = {}
invites.forEach((invite) => {
const { uses, inviter } = invite
const { username, discriminator } = inviter
const name = `${username}#${discriminator}`
inviteCounter[name] = (inviteCounter[name] || 0) + uses
})
let replyText = 'Invites:'
const sortedInvites = Object.keys(inviteCounter).sort(
(a, b) => inviteCounter[b] - inviteCounter[a]
)
console.log(sortedInvites)
sortedInvites.length = 10
for (const invite of sortedInvites) {
const count = inviteCounter[invite]
const embed = new Discord.MessageEmbed()
.setColor('BLUE')
.setTitle('`INVITES LEADERBOARD`')
.setDescription(sortedInvites)
message.channel.send(embed)
}
})
}
}
The code comes with no errors but when I execute !leaderboard
, bot sends 10 different messages with the same content. In additional I want to add more info to each user , like how many invites does the user got and how many are left from these invites ! My bot sends this 10 times in row, what I want is :
Upvotes: 0
Views: 661
Reputation: 9002
You loop through the sortedInvites
array 10 times and send a message every time, so this behavior should not surprise you. If you only want to send one message, remove the send
from the loop.
Also, you only sort
the keys of the inviteCounter
object, so you loose the other data. In order to preserve the data, change it to this:
const sortedInvites = Object.keys(inviteCounter).sort().reduce(
(obj, key) => {
obj[key] = inviteCounter[key];
return obj;
},
{}
);
Then, if you want to display username next to data, you can create an array with the data like this and join it together with a new line to separate it from each other in the message:
const invitesData = Object.keys(sortedInvites).map(invite => {
return `${invite}: ${sortedInvites[invite]}`;
});
const embed = new Discord.MessageEmbed()
.setColor("BLUE")
.setTitle("`INVITES LEADERBOARD`")
.setDescription(invitesData.join("\n"));
message.channel.send(embed);
Upvotes: 1