gpt4 book ai didi

javascript - Bot 将字符串返回到我没有指定的数字

转载 作者:行者123 更新时间:2023-11-30 15:00:04 25 4
gpt4 key购买 nike

制作一个不和谐的机器人。不仅在 6 卷上获得“你赢了”,而且在 2 和 4 上也如此。我知道这不是最好的方法。它似乎并不关心是否random == 'insert string here' 或 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!');
}
});

最佳答案

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

  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.

修复所有错误后,您的代码将如下所示:

//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

Discord.js Docs

关于javascript - Bot 将字符串返回到我没有指定的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46677623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com