Skip to content
Advertisement

Slowmode command

When I type ;sm, my bot responds with: “You need to specify a time in seconds” <– Thats okay.

But when I type ;sm [time], it still responds with: “You need to specify a time in seconds.”, but it should set the rate limit and tell me that “Slowmode is now [time]s”.

Here’s my code:

const Discord = require("discord.js");

module.exports.run = async (bot, message) => {
    if(message.author.bot) return;
    if(!message.member.hasPermission('MANAGE_MESSAGES')) 
        return message.channel.send("You need `MANAGE_MESSAGES` permission to execute this command.");
    const messageArray = message.content.split(' ');
    const args = messageArray.slice(1);

    if (!args[1] == null) {
        message.channel.setRateLimitPerUser(args[0])
        message.channel.send(`Slowmode is now ${args[0]}s`)
    }
    if (args[1] == null) {
        return message.channel.send("You need to specify time in seconds!")
    };
};

module.exports.config = {
    name: "sm",
    aliases: []
}

Advertisement

Answer

First, make sure you understand what your variables are. If you type a command like !sm 10, your messageArray will be an array like ['!sm', '10'] and your args will be an array like ['10'].

When you slice the array (messageArray.slice(1)), you remove the first element. So if you want to check the first argument after the command you should check args[0], not args[1].

Second, when you check !args[1] == null you’re converting args[1] to a boolean. If you check if a boolean is null, it will always return false, so you’ll never execute setRateLimitPerUser.

console.log(true == null)  // => false
console.log(false == null) // => false

You can instead check if the argument is null. If it is, you can return early. This way you don’t need another if or else if statement. Even better, you could check if the argument is a not a number using isNaN.

module.exports.run = async (bot, message) => {
  if (message.author.bot) return;
  if (!message.member.hasPermission('MANAGE_MESSAGES'))
    return message.channel.send(
      'You need `MANAGE_MESSAGES` permission to execute this command.',
    );
  const messageArray = message.content.split(' ');
  const args = messageArray.slice(1);
  const seconds = args[0];
  const MAX_SECONDS = 21600;

  if (isNaN(seconds)) {
    return message.channel.send('You need to specify time in seconds!');
  }

  if (seconds > MAX_SECONDS) {
    return message.channel.send(
      `The maximum number of seconds is ${MAX_SECONDS}.`,
    );
  }

  try {
    await message.channel.setRateLimitPerUser(seconds);
    message.channel.send(`Slowmode is now ${seconds}s`);
  } catch (error) {
    message.channel.send('Oops, there is a problem with that command');
    console.log(error);
  }
}

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement