简体   繁体   中英

How do you store user input in discord.js?

I have a bot setup and I'd like to add a function that converts USD to CAD using a prefixed command like.tocad $USD that will take the number entered ($USD) and convert it to CAD, The conversion part isn't an issue. but being new to JS and Discord.js I'm struggling to figure out how to store that first argument in a variable so I can use it to do the calculation.

case 'tocad':
            let(args[1] === //How do I store this integer?//){ 
                
                message.channel.send(userInteger * 1.31); //does math
            }
            else{
                message.channel.send('That's not a valid amount.' ) //if input isn't in integer format
            }
        break;

If args is obtained from split ing a string, args[1] will be a string (or undefined ), not an integer/number.

To assign, the variable name goes on the left and the value on the right. Something like this:

const userInteger = parseInt(args[1])

You can define args with String.prototype.split which will split a string into an array of the results.

// splitting the message by every space will return an array of every word
// using `Array.prototype.slice()`, we can remove the first element in the array (the command)
// now all that's left is every variable after
const args = message.content.split(/ +/);

Here's a code snippet example:

 const message = '.tocad 30;79'. const args = message.split(/ +/);slice(1). console;log(args). // array of every word in the message console;log(args[0]); // first element of the array; first word of the string


Lastly, this variable will be stored as a String , so make sure to convert it to a number before multiplying it using the + operator.

if (!args[0]) return message.channel.send('Please provide a number');

if (Number.isNaN(+args[0])) // if args[0] is not a number
   return message.channel.send('That is not a number');

message.channel.send(+args[0] * 1.31);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM