How do I end a emmiter.on within a conditional statement

1.3k views Asked by At

Right now I am trying to create a Discord bot command that ignores specific commands in specific channels. In order to de-ignore the channel the user must type in a command, then they receive a prompt telling them to type "Yes/No" and then respond Yes, No, or if they didn't type Yes/No then tell them to do so and then repeat. Here's my code:

if (msg.content === prefix + 'ignore') {
    const guildMember = msg.member;
    const author = msg.author.id;
    if (guildMember.roles.has('309165526427369473')) {
      if (ignoredChannels.has(msg.channel.id)) {
        msg.reply('Would you like to stop ignoring this channel? (Yes/No)');
        client.on('message', msg => {
       /* if (author === msg.author.id) {
            if (msg.content === 'Yes') {
              ignoredChannels.delete(msg.channel.id);
              msg.reply('Channel is now not ignored.');
            }
            else if (msg.content === 'No') {
              msg.reply('Channel is still ignored.');
            }
            else {
              msg.reply('You did not type in the correct arguments. Please type "Yes" or "No".');
            }
          } */
          else {}
        });
      }
      else {
      ignoredChannels.set(msg.channel.id, msg.channel.name);
      msg.reply('Channel is now ignored.');
      }
    }
    else {
      msg.reply('You do not have the permissions to do this.');
    }
  }

In the commented code, that is where each conditional statement is. I would basically like to put }); in each statement to end the client.on but of course, that would be improper syntax. Now I have already tried removing the all of the listeners using client.removeAllListeners at the end of each condition but that will disable the other "message" listener I have placed elsewhere in the code that receives all of the other commands. I have also tried placing the removeLisener but that requires the specific listener function and the "msg" listener is built-in to discord.js. I also can't use client.once because it has multiple listener functions within each condition. Why I need to end the client.on is to stop the bot from responding to the required inputs from the user multiple times (needs just once), never ending the emitter.

1

There are 1 answers

0
André On BEST ANSWER

You shouldn't add a new event client.on('message') just for receive one confirmation message.
You should use .awaitMessages() instead. Example:

// Await !vote messages
const filter = m => m.content.startsWith('!vote');
// Errors: ['time'] treats ending because of the time limit as an error
channel.awaitMessages(filter, { max: 4, time: 60000, errors: ['time'] })
  .then(collected => console.log(collected.size))
  .catch(collected => console.log(`After a minute, only ${collected.size} out of 4 voted.`));

copied from documentation

You can filter who is "allowed" to confirm the response by adding it to the filter.