I'm trying to make a game for my discord bot: bot chooses a random number and then, user tries to find number by guidance of the bot. I tried this thing but when I send a message (I send a number) it turns NaN. Why this happens and how can I fix it?
let randomNumber = (Math.floor( Math.random() * (100)))
let usersAnswer = parseInt(message.content)
if (!message.author.bot && message.content === "!pick number"){
message.reply("I kept! :check: ").then(j => {
message.channel.awaitMessages(( message, user) => (user.id === message.author.id && randomNumber < usersAnswer || randomNumber > usersAnswer),
{max: 1, time: 10000}).then(j => {
if (usersAnswer < randomNumber) {
message.reply("Increase! :arrow_up:" + usersAnswer) //I add usersAnswer to the bot's message because I want to see what it reads my message like in Discord
}
else {
message.reply("Decrease! :arrow_down:" + usersAnswer)
}
})
})
}
If you use parseInt()
you need to set a radix before using this method. I took 10 as an example.
let usersAnswer = parseInt(message.content, 10)
if (!message.author.bot && message.content === "!pick number"){
message.reply("I kept! :check: ").then(j => {
message.channel.awaitMessages(( message, user) => (user.id === message.author.id && randomNumber < usersAnswer || randomNumber > usersAnswer),
{max: 1, time: 10000}).then(j => {
if (usersAnswer < randomNumber) {
message.reply("Increase! :arrow_up:" + usersAnswer) //I add usersAnswer to the bot's message because I want to see what it reads my message like in Discord
}
else {
message.reply("Decrease! :arrow_down:" + usersAnswer)
}
})
})
}
Or you could also simply use Number()
:
let usersAnswer = Number(message.content)
if (!message.author.bot && message.content === "!pick number"){
message.reply("I kept! :check: ").then(j => {
message.channel.awaitMessages(( message, user) => (user.id === message.author.id && randomNumber < usersAnswer || randomNumber > usersAnswer),
{max: 1, time: 10000}).then(j => {
if (usersAnswer < randomNumber) {
message.reply("Increase! :arrow_up:" + usersAnswer) //I add usersAnswer to the bot's message because I want to see what it reads my message like in Discord
}
else {
message.reply("Decrease! :arrow_down:" + usersAnswer)
}
})
})
}
If I were you I would add a check if the usersAnswer is even a Number otherwise the output could also be NaN.) You could do this by simply adding the following line:
if (isNaN(usersAnswer)) return message.reply('This is not a number');