簡體   English   中英

Discord.js 多反應收集器

[英]Discord.js multiple reaction collector

如何使此代碼適用於多個反應? 我希望嵌入有多個反應,並根據選定的反應,它會給出不同的反應這是代碼:

module.exports = {
    name: 'test',
    description: "ping command",
    async execute(message, args, Discord){
        
        var newEmbed = new Discord.MessageEmbed()
        .setColor('#A5775C')
        .setTitle('Reactions')
        .setDescription('*React to this!')
        
const MAX_REACTIONS = 1;
        
      const sentMessage = await message.channel.send({embeds: [newEmbed]});

      await sentMessage.react('🐸');

      const filter = (reaction, user) => reaction.emoji.name === '🐸' && !user.bot;

      const collector = sentMessage.createReactionCollector({
        filter,
        max: MAX_REACTIONS,
      });

      collector.on('end', (collected, reason) => {

        if (reason === 'limit')
          return message.channel.send(`You reacted with 🐸!`);
      });
    }
  }```

首先,您需要將所有需要的反應添加到消息中:

await sentMessage.react('emoji');
await sentMessage.react('emoji_2');
await sentMessage.react('emoji_3');
// ... //

現在,您需要編輯filter(reaction, user)函數。 reaction.emoji.name === '🐸'表示收集器只會響應一個表情符號 - 🐸。 如果您希望收集器響應不同的表情符號,您可以刪除此表情。 在這種情況下,收集器將響應任何表情符號。 但是,您也可以讓收集器響應特定的表情符號列表:

const filter = (reaction, user) => ["emoji1", "emoji2", "emoji3" /* ... */].includes(reaction.emoji.name) && !user.bot
// the collector will now respond to all the emoji in the array

最后,要顯示用戶選擇的表情符號而不是🐸,請替換message.channel.send()中的字符串:

message.channel.send(`You reacted with ${collected.first().emoji.name}!`);

此外,我可以為您提供另外 2 個可選的東西來改進代碼:

  1. 由於代碼是專門為收集一個反應而編寫的,因此MAX_REACTIONS常量可能不會改變。 所以你可以去掉它,在創建收集器時使用1
  2. 因為您在創建收集器時沒有傳遞time屬性,所以如果命令的作者沒有選擇反應,則收集器將無限期地持續下去。 因此,您可以在創建收集器時傳遞idle屬性並以毫秒為單位指定時間。 在指定的不活動毫秒數后,收集器將停止。 例如:
const collector = sentMessage.createReactionCollector({
    filter,
    max: 1,
    idle: 10000 // the collector will stop after 10 seconds of inactivity
});

如果收集器由於不活動而停止, reason將是"idle" ,在collector.on("end", ...)內部:

collector.on('end', (collected, reason) => {
    if (reason === "limit") {
        return message.channel.send(`You reacted with ${collected.first().emoji.name}!`);
    } else if (reason === "idle") {
        // ... //
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM