How to stop MessageCollector with custom message

Viewed 74

I have slash command that collects messages from users. Users should input their nicknames from the game, and then bot should return in embeded 2 teams. I managed to filter and collect nicknames, and call calculation functions. This works if I enter maximum number of nicknames, but now I want to add feature, where I would manually stop collecting by sending message "stop". Now I don't know where to add condition if(m.content==="stop") {collector.stop();}

const { SlashCommandBuilder } = require("@discordjs/builders");
const { getSummonerProfile } = require("./../functions/summonerData");
const { MessageEmbed } = require("discord.js");

let arrayOfSummoners = [];
let arrayOfNicknames = [];

async function checkIfSummonerExist(m) {
  const test = await getSummonerProfile(m.content);
    
  if (test && m.author.bot == false && !arrayOfNicknames.includes(m.content)) {
    m.react("");
    return true;
  } else if (test == false && m.author.bot == false) {
    m.react("");
    return false;
  }
  if (arrayOfNicknames.includes(m.content)) {
    m.react("");
  }
}
module.exports = {
  data: new SlashCommandBuilder()
    .setName("custom")
    .setDescription("Enter the name of the user."),
    
  async execute(interaction) {

    await interaction.deferReply();

     interaction.editReply("Insert users");

      const exampleEmbed = new MessageEmbed()
        .setColor("#0099ff")
        .setTimestamp();

    // `m` is a message object that will be passed through the filter function
    const filter = (m) => checkIfSummonerExist(m);
    const collector = interaction.channel.createMessageCollector({
      filter,
      max: 4,
    });
    if(m.content==="stop")
    {
      collector.stop();
    }
    collector.on("collect", (m) => {
      arrayOfNicknames.push(m.content);
      exampleEmbed.addFields({
        name: "Regular field title",
        value: m.content, inline:true
      });
    });
    collector.on("end", (collected) => { 
        interaction.followUp({ embeds: [exampleEmbed] });
    });      
  },
};

If I add this condition in filter fuction (checkIfSummonerExist(m), I get error collector is not defined and I if call it in execute, like in example above, I get error m is not defined

1 Answers

I would put the if statement inside the collector.on callback. Something like this:

collector.on("collect", m => {
  if(m.content === "stop") return collector.stop()
  // Other code
})
Related