【问题标题】:Discord.js v13 return in message collector doesn't stop collecting消息收集器中的 Discord.js v13 返回不会停止收集
【发布时间】:2022-01-12 05:56:29
【问题描述】:

我尝试在Discord.js v13 中使用message.channel.createMessageCollector() 创建一个“设置”命令。我希望用户输入quit 来取消/中止命令。我正在尝试在收集器内使用return 使用此代码并不会阻止它:

const filter = (m) => {
  return m.author.id === message.author.id;
};

const collector = message.channel.createMessageCollector({
  filter,
  max: 5,
  time: 1000 * 20,
});

collector.on("collect", (collect) => {
  if (collect.content.toLowerCase() === "quit") return message.reply("Bye!"); // The return is doesn't work
});

我怎样才能让它工作?

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    一个简单的return 语句不会停止收集器。它只是使该函数内的其余代码不运行。但是,如果有新的传入消息,回调函数会再次执行。

    但是,您可以使用Collector#stop() 方法来停止收集器并发出end 事件。您还可以添加收集器结束的原因。

    查看以下代码:

    const filter = (m) => m.author.id === message.author.id;
    
    const collector = message.channel.createMessageCollector({
      filter,
      max: 5,
      time: 1000 * 20,
    });
    
    collector.on('collect', (collected) => {
      if (collected.content.toLowerCase() === 'quit') {
        // collector stops and emits the end event
        collector.stop('user cancelled');
        // although the collector stopped this line is still executed
        return message.reply('Bye!');
      }
    
      // this line only runs if the above if statement is false
      message.reply(`You said _"${collected.content}"_`);
    });
    
    // listening for the end event
    collector.on('end', (collected, reason) => {
      // reason is the one you passed above with the stop() method
      message.reply(`I'm no longer collecting messages. Reason: ${reason}`);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 2022-01-21
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 2020-10-25
      • 2019-11-25
      • 2021-12-18
      相关资源
      最近更新 更多