我正在使用 Node.js 在 Discord.js 库中构建代码,用于邀请 LeaderBoard 命令!
我使用的代码是:
{ "shortcuts": [
//First you can optionally make room for your new hotkey if it is taken.
// {
// "command": "imageviewer:flip-horizontal",
// "keys": [
// "H"
// ],
// "selector": ".jp-ImageViewer",
// "disabled": true
// },
// Then assign a new hotkey
{
"command": "notebook:hide-cell-outputs",
"keys": [
"H"
],
"selector": ".jp-Notebook:focus",
"disabled": false
}
]
}
代码没有错误,但是当我执行 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)
}
})
}
}
时,bot 会发送 10 条具有相同内容的不同消息。此外,我想为每个用户添加更多信息,例如用户收到了多少邀请以及这些邀请还剩下多少!我的机器人连续发送此 10 次,我想要的是:
答案 0 :(得分:1)
您循环遍历 sortedInvites
数组 10 次并每次都发送一条消息,因此这种行为应该不会让您感到惊讶。如果您只想发送一条消息,请从循环中删除 send
。
此外,您只需 sort
inviteCounter
对象的键,因此您丢失了其他数据。为了保存数据,改成这样:
const sortedInvites = Object.keys(inviteCounter).sort().reduce(
(obj, key) => {
obj[key] = inviteCounter[key];
return obj;
},
{}
);
然后,如果你想在数据旁边显示用户名,你可以用这样的数据创建一个数组,并用一个新行将它连接在一起,以在消息中将它们彼此分开:
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);