提问者:小点点

使用Discord.js的Node.js中的反应的多个输出


我想让机器人对有两个选择的投票消息作出反应,并让用户对提供的表情作出反应,但除此之外,我还想获取用户id,知道谁投了什么票。我现在遇到的问题是:第一个轮询的输出是:

2x the bots id (for both choices)
1x the users id (if they only voted for one choice)
this is how it should be.

但是当我在之后创建另一个轮询时,输出是:

4x the bots id 
2x the users id 

然后再做第三次投票,结果显示:

6x the bots id 
3x the users id 
and so on..

因此,在3次轮询之后,我的控制台输出总共是12x的bots id和6x的用户id,而它应该只有6x和3x。我需要在每次轮询后重新启动bot,以便它打印出正确的输出。这里到底是怎么回事,我该如何修复呢?

index.js:

const Discord = require("discord.js");
const tokenfile = require("./token.json");
const bot = new Discord.Client({disableEveryone: true});
bot.commands = new Discord.Collection();
const fs = require("fs");

fs.readdir("./Commands/",(err,files)=>{
    if(err) console.log(err);
    let jsfile = files.filter(f=>f.split(".").pop()==="js")
    if(jsfile.length <= 0){
        console.log("Couldnt find commands.");
        return;
    }
    jsfile.forEach((f, i)=>{
        let props = require(`./Commands/${f}`);
        console.log(`${f} loaded!`);
        bot.commands.set(props.help.name, props);
    });
});

bot.on("ready", async () =>{
    console.log(`${bot.user.username} is online!`);
});

bot.on("message", async message =>{
    if(message.author.bot) return;
    if(message.channel.type === "dm") return;

    let prefix = tokenfile.prefix;
    let messageArray = message.content.split(" ");
    let cmd = messageArray[0];
    let args = messageArray.slice(1);
    let commandfile = bot.commands.get(cmd.slice(prefix.length));
    if(commandfile) await commandfile.run(bot, message, args);
});

bot.login(tokenfile.token); 

poll.js:


module.exports.run = async(bot, message, args)=> {
    let poll = message.content.match(/"(.+?)"/g);
    let bicon = bot.user.displayAvatarURL;
    let botembed = new Discord.RichEmbed()
        .setThumbnail(bicon)
        .setColor("#15f153")
        .addField("Created by:", message.author.username)
        .addField("Poll:", poll);
    message.channel.send(botembed)
        .then(async (pollMessage) => {
            await pollMessage.react('✅');
            await pollMessage.react('❌')
        });
    bot.on('messageReactionAdd', (reaction, user) => {
        if (reaction.emoji.name === "❌") {
                console.log(`${user.id}`);
        }

        if (reaction.emoji.name === "✅") {
            console.log(`${user.id}`);
        }
    });
};

module.exports.help = {
    name: "poll"
}; 

共1个答案

匿名用户

您所经历的行为是因为您将嵌套侦听器附加到MessageReactionAdd事件。每次机器人看到在该点之后的任何消息上添加了一个反应,它就会调用您的侦听器函数。这意味着在一次投票之后,机器人仍然在倾听反应,并将继续连接更多的听众。事实上,在附加一定量的侦听器之后,您可能会在控制台中看到关于可能的内存泄漏的警告。

考虑使用Message.AwaitReactions()或直接使用ReactionCollector。有关详细信息和示例用法,请参阅超链接文档。