Bot将string返回给我没有指定的数字

做一个不和谐的机器人。 获得“你赢”不仅是6卷,而是2和4。 我知道这不是最好的办法。 它似乎并不在乎如果随机=='插入string在这里'或随机=='插入int在这里'。

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

我看到你的代码的主要问题是:

  1. 你没有把你所有的骰子相关的代码放入if区块检查,如果这个消息是roll命令的话。

    • 即使没有调用该命令,这也会导致机器人在“roll”数为6 进行回复。
  2. 你没有检查消息是否来自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!'); } } }); 

注意:如果你不想提到你的机器人信息,请使用message.channel.send而不是message.reply

Discord.js文件