我正在尝试创建一个函数,如果用户发送的图像获得了一定数量的赞成票,机器人就会将该图像发送到另一个频道。我现在拥有的代码可以正常工作,除了它发送的图像收到所需的赞成票数 AND 之前的图像也获得了所需的赞成票数。
假设用户 A 发送了一张图片。该图像获得 2 个赞成票,并被发送到 #upvoted-images 频道。用户 B 出现并发布了一张图片。他们的图片也获得了 2 个赞,并发送到 #upvoted-images,但用户 A 的图片与用户 B 的图片一起再次发送。
bot.on("message", async message => {
if(message.channel.id !== '869294795019923486')return;
if(message.author.bot) return;
message.react("⭐")
bot.on('messageReactionAdd', (reaction, user) => {
let limit = 2; // number of thumbsdown reactions you need
if (reaction.emoji.name == '⭐' && reaction.count >= limit){
const channel = message.guild.channels.cache.find(ch => ch.name === 'test3');
message.react("?")
channel.send("My Bot's message", {files:[message.attachments.first().url]});
console.log(message.attachments.url)
}
})
})
我现在有点受阻,感谢任何帮助,谢谢!
答案 0 :(得分:1)
问题在于每次发送消息时您都在创建一个新的事件侦听器。在您的案例中,messageReactionAdd
的每个侦听器回调都有对原始 message
对象的引用。这意味着当事件触发时,它将为事件侦听器注册的每条消息触发。
解决方案是将 messageReactionAdd
的事件侦听器置于 message
的事件侦听器之外。
client.on("message", async (message) => {
if (message.channel.id !== "869294795019923486") return;
if (message.author.bot) return;
message.react("⭐");
});
client.on("messageReactionAdd", (reaction, user) => {
const message = reaction.message;
// You could use your ? reaction for a neat safety check,
// so images that were already sent to the channel don't get sent again.
// We treat ? reaction as an indication that the bot has already sent the image to the specified channel.
// This way when someone unreacts and adds the reaction back,
// or when someone adds the reaction after it met the two upvote treshold,
// it won't get sent again.
if (message.reactions.cache.some(re => re.emoji.name === "?" && re.users.cache.has(client.user.id))) {
return;
}
let upvoteLimit = 2;
// Number of reactions needed to be cast by the users (including the bot itself)
// in order for the image to be sent to another channel.
if (reaction.emoji.name == "⭐" && reaction.count >= upvoteLimit) {
const channel = message.guild.channels.cache.find(ch => ch.name === "test3");
channel.send("My Bot's message", {files:[message.attachments.first().url]});
message.react("?");
}
});
请注意,这仅适用于机器人在线时发送的图像。如果您希望它适用于较旧的图像,您可能需要查看 partials。
如果您只想暂时收集反应,可以查看ReactionCollector
。