Javascript Bot将字符串返回到我未指定的数字

Javascript Bot将字符串返回到我未指定的数字,javascript,node.js,discord,Javascript,Node.js,Discord,制造不和机器人。不仅是6分,还有2分和4分。我知道这不是最好的办法。它似乎不在乎 random==“在此处插入字符串”或random==“在此处插入整数” //Dice Roll Game bot.on('message', (message) =>{ let diceNum = ['1','2','3','4','5','6']; let random = diceNum[Math.floor(Math.random() * diceNum.length)];

制造不和机器人。不仅是6分,还有2分和4分。我知道这不是最好的办法。它似乎不在乎 random==“在此处插入字符串”或random==“在此处插入整数”

//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!');
    }
});

我发现您的代码的主要问题是:

  • 您没有将所有与骰子相关的代码放入
    if
    -块检查消息是否为
    roll
    命令

    • 这会导致bot在数字“rolled”为6时回复,即使在未调用命令时也是如此
  • 您没有检查消息是否来自bot

    • 它将回复多次,因为您没有检查消息是否来自您的bot
  • 修复所有错误后,代码将如下所示:

    //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!');
            }
        }
    
    });
    
    旁注:如果您不想在您的bot消息前添加提及,请使用
    message.channel.send
    而不是
    message.reply


    关于平等问题,你可以看一看,事实证明,我会的!滚,它会为我和迪斯科机器人滚一个号码。有时我会掷4分,机器人掷6分,让人以为我赢了,而实际上机器人赢了。我只需要为用户输入指定仅滚动!roll.FWIW,你也可以跳过几个步骤
    Math.floor(Math.random()*6))+1
    将生成1-6之间的随机数。如果您需要将其转换为字符串,只需将其转换为字符串即可。因此,在前几行中不需要数组或数组访问。作为次要nit,您永远不会更改变量赋值,因此它们也应该是
    const
    。我认为这里的
    random
    是一个字符串,您将字符串与int进行比较,或者对int或string进行比较。