简体   繁体   中英

Discord.js v13 Return in Message Collector

I try to create a "Setup" command with message.channel.createMessageCollector in Discord.js v13. I want the user to type quit to cancel/abort the command. I am trying with this code but using return inside the collector doesn't stop it:

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
});

How can I make it work?

A simple return statement won't stop the collector. It just makes the rest of the code inside that function not to run. But, if there is a new incoming message, the callback function gets executed again.

However, you can use the Collector#stop() method that stops the collector and emits the end event. You can also add a reason the collector is ending.

Check out the code below:

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}`);
});

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM