DiscordJS-有没有办法抑制反应收集器?

时间:2020-09-29 19:12:45

标签: javascript node.js discord discord.js

超级快速的问题。我想知道是否有一种方法可以“重新启动”反应收集器。我目前在我的事件策划器bot中使用反应收集器,根据用户的反应将用户添加到列表中。例如,如果我竖起大拇指表示反对,它将把我添加到参加会议的人员列表中。我希望它之后将自己重置为1个大拇指(只是机器人的反应),以便它可以等待收集其他用户的反应。这样做的原因是因为我希望它继续运行直到事件发生。有办法吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

由于我不熟悉ReactorCollector类型,所以我不得不做一些文档阅读,而且看来有很多破解方法,但是我想我想ve使用事件监听器找到了一种优雅的解决方案。 (我不知道您将如何初始化收集器,但是出于测试目的,我在发送任何随机消息时都进行了挖矿。显然不要这样做。)

我不知道您是要在1位用户做出反应后还是在任意点之后进行重置。 这是在每次反应后重设并跟踪谁反应的方法。

let attendees = []; //array of users who are attending
client.on("message", message => {
    if (message.author.bot) return;
    message.react("?"); //add the bot's reaction so other users can easily click it
    rc = new Discord.ReactionCollector(message, reaction => { //create a new collector, with a filter to only collect emojis that are thumbs up.
        return (reaction._emoji.name == '?');
    });
    
    rc.on("collect", (reaction, user) => { //create an event listener for when a reaction is added to this collector
        if (user != client.user) { //if not the bot's reaction
            console.log(`${user} reacted`);
            attendees.push(user); //add user to attendees array
            reaction.users.remove(user); //remove their reaction
            console.log(`Removed ${user} from reaction after they reacted`);
            console.log(`Attendees are now: ${attendees}`);
        }
    });
});

一个用户做出反应后的输出:

<@ID1> reacted
Removed <@ID1> from reaction after they reacted
Attendees are now: <@ID1>
//ID removes for privacy purposes
//the Attendees list will continue to grow with every reaction

只要您想停止收集反应,就可以致电rc.stop(OPTIONAL_STRING_REASON)
如果需要,可以在调用rc.stop()之后直接做一些事情,也可以使用其他事件侦听器!

rc.on("end", (collections, reason) => {
   console.log(`Stopping collection because ${reason}`);
});
rc.stop("The poll is now over!");

如果您希望让所有人在某个任意场合之前做出反应,那么请吸引所有用户并删除他们的反应: (这与最后一种方法非常相似,因此我没有留下评论)
let rc = undefined;
client.on("message", async message => {
    if (message.author.bot) return;
    if (message.content.startsWith("new")) {
        message.react("?");
        rc = new Discord.ReactionCollector(message, reaction => {
            return (reaction._emoji.name == '?');
        });
        rc.on("end", async (collection, reason) => {
            console.log(`Stopping collection because ${reason}`);
            let thumbsup = collection.get("?")
            let users = await thumbsup["users"].fetch(); //we have to "wait" to get all of them!
            users.each((user, id) => {
                if (user != client.user) { //dont count the bot
                    console.log(`${user} is attending!`);
                    //here is where you could add your users to some array
                    thumbsup["users"].remove(user); //remove their reaction
                }
            });
        });
    } else if (message.content.startsWith("end")) {
        rc.stop("Times up!"); //stop the collector
    }
});