JavaScript custom command for Discord bot dice roller

Hey everyone! I’m working on a Discord bot using the Discord.js-commando library. I’ve got a dice rolling command that works for basic rolls, but I’m having trouble with custom ranges. Here’s what I want it to do:

!roll (1 to 6)
!roll 25 (1 to 25)
!roll 100 200 (100 to 200)

The !roll and !roll 100 200 work fine, but !roll 25 keeps failing. My validation says it’s not a valid number. Any ideas why this is happening?

Here’s a simplified version of my code:

function rollDice(args) {
  const params = args.split(' ');
  const isNum = /^\d+$/;

  if (params.length > 2) {
    return 'Too many parameters!';
  }

  if (params[0] && !isNum.test(params[0])) {
    return 'Invalid number!';
  }

  if (params.length === 0) {
    return Math.floor(Math.random() * 6) + 1;
  } else if (params.length === 1) {
    return Math.floor(Math.random() * parseInt(params[0])) + 1;
  } else {
    return Math.floor(Math.random() * (parseInt(params[1]) - parseInt(params[0]) + 1)) + parseInt(params[0]);
  }
}

Can anyone spot what I’m doing wrong? Thanks!

I’ve worked with Discord bots before, and your issue seems to stem from how you’re handling the input validation. The problem is likely in your regex pattern. ‘/^\d+$/’ only matches strings that are entirely digits, but ‘25’ is being passed as an argument, not a string.

Try modifying your isNum check to:

const isNum = (n) => !isNaN(parseInt(n)) && isFinite(n);

This should correctly identify ‘25’ as a valid number. Also, consider using Number() instead of parseInt() for consistency. Remember to handle edge cases like negative numbers or decimals if those are possibilities in your use case.

Lastly, error messages can be more helpful. Instead of just ‘Invalid number!’, you could specify which parameter is invalid. This makes debugging easier for both you and your users.

I’ve encountered a similar issue when working on my own Discord bot. The problem likely stems from how you’re parsing the arguments. Instead of splitting the args string, try using the built-in argument handling in Discord.js-commando.

Here’s a approach that worked for me:

.addArgument(args.integer('min').default(1))
.addArgument(args.integer('max').optional())

This setup automatically validates and converts arguments to integers. For single number inputs like ‘!roll 25’, set ‘max’ as optional and use ‘min’ as the upper bound if ‘max’ isn’t provided.

In your run method:

run(message, { min, max }) {
  if (!max) {
    max = min;
    min = 1;
  }
  const result = Math.floor(Math.random() * (max - min + 1)) + min;
  return message.say(`You rolled a ${result}`);
}

This approach should handle all your desired roll formats without manual parsing. Hope this helps!

hey mate, might be an issue with how you split input. try trimming the args first: const params = args.trim().split(/\s+/); this ensures extra spaces don’t mess with the regex, which might be why ‘!roll 25’ fails. hope that fixes it!