1

Making a discord bot. Getting "you win" on not only a 6 roll, but 2 and 4 as well. I know this is not the best way to make it. It doesn't seem to care if random == 'insert string here' or random == 'insert int here'.

//Dice Roll Game
bot.on('message', (message) =>{  

    let diceNum = ['1','2','3','4','5','6'];
    let random = diceNum[Math.floor(Math.random() * diceNum.length)];

    if(message.content == '!roll') {
        message.reply('You rolled a' + ' ' + random + '!');
    }

    if(random == 6){
        message.reply('You win!');
    }
});
MLavoie
  • 9,671
  • 41
  • 36
  • 56
  • For the equality issue, you can take a look at [this answer](https://stackoverflow.com/a/359509/6320039) – Ulysse BN Oct 10 '17 at 23:51
  • It turns out, that when I would ! roll, it would roll a number for myself and the discord bot. Sometimes I would roll a 4 and the bot a 6 giving the illusion that I won when in reality the bot did. I just have to specify to only roll for the user entering !roll. – Garrett Rose Oct 10 '17 at 23:56
  • FWIW, you can skip a couple steps there, too. `Math.floor(Math.random() * 6)) + 1` will yield a random number from 1-6. If you need it to be a string, just cast it to a string. So you don't need the array or the array access in the first couple lines. As a minor nit, you're never changing your variable assignments so they should be `const` as well. – Paul Oct 11 '17 at 00:37
  • I think here `random` is a string and you are comparing string with int, either do a comparison for both int or string. – Ayush Mittal Oct 11 '17 at 01:18

1 Answers1

2

I see the main problems with your code is that:

  1. You did not put your all of your dice-related code into the if-block checking if the message is the roll command.

    • This causes the bot to reply when the number "rolled" is 6 even when the command is not invoked.
  2. You did not check whether the message came from a bot.

    • It would reply multiple times since you did not check whether the message came from your bot.

Your code would look like this once you fixed all your errors:

//Dice Roll Game
bot.on('message', message => { // If theres only one parameter, you can omit brackets
    // Bot Check
    if(message.author.bot)return;

    // Even with useless parameters to the command, it will still run
    if(message.content.startsWith('!roll')) { 

        // Arrays are not needed

        // Gives a random int from 1 - 6, (~~) floors an integer 
        let random = ~~(Math.random() * 6) + 1; 

       message.reply(`You rolled a ${ random }!`); // ES6 Template Strings 

        // Please use strict equality signs to prevent bugs from appearing in your code
        if(random === 6){
            message.reply('You win!');
        }
    }

});

Side Note: If you do not want a mention prepended to your bot message, please use message.channel.send instead of message.reply.

Discord.js Docs

Joseph Goh
  • 376
  • 2
  • 13