Home > Back-end >  Collector doesn't end with reason time
Collector doesn't end with reason time

Time:01-29

I got this jumbled words code where it ends if nobody got the right answer after the time has ran out. But the collector doesn't end somehow. The code works just fine but I wanted the collector to end in a given limited time.

This was the code:

const listword = ['array', 'of', 'words'];

var word = listword[Math.floor(Math.random() * listword.length)].toLowerCase();
var jumbled = word
  .split('')
  .sort(function () {
    return 0.5 - Math.random();
  })
  .join('');

interaction.followUp({ content: `The word is ${word}`, ephemeral: true });
await interaction.channel.send(`Guess the word \`${jumbled}\`!`);
const filter = (response) => listword.includes(response.content.trim());

const collector = interaction.channel.createMessageCollector(filter, {
  time: 15000, //this doesn't work somehow
});
collector.on('collect', (response) => {
  if (response.author.bot) return;
  var guessword = response.content.trim();
  if (guessword.toLowerCase() === word) {
    response.react('✅');
    response.reply({
      content: `${response.author} guessed it right! The word was \`${word}\`.`,
      allowedMentions: { users: [], roles: [], repliedUser: false },
    });
    collector.stop();
  } else {
    if (response.author.bot) return;
    response.react('❌');
  }
});

collector.on('end', (collected) => {
  if (!collected.size) {
    interaction.channel.send(
      'Time is up! Nobody was able to guess the word'   `\`${word}\`.`
    );
  }
});

I don't know why the collector doesn't end unless the word is guessed correctly. What do I need do to fix it?

CodePudding user response:

In discord.js v13, all Collector related classes and methods (both .create*() and .await*()) takes a single object parameter. That means, createMessageCollector accepts a single parameter, an options object. (previously, the first parameter was a filter and the second one is the options).

As you provide the filter as the first argument, the object with the time key is simply ignored. Just pass a single object with the filter and the time and it will work fine:

const collector = interaction.channel.createMessageCollector({
  filter,
  time: 15000,
});

Similar answer: https://stackoverflow.com/a/70455975/6126373

  • Related