简体   繁体   English

你如何在 discord.js 中存储用户输入?

[英]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.我有一个机器人设置,我想添加一个 function,它使用前缀命令将美元转换为加元一个问题。 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.但作为 JS 和 Discord.js 的新手,我正在努力弄清楚如何将第一个参数存储在变量中,以便我可以使用它进行计算。

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.如果args是通过split字符串获得的,则args[1]将是一个字符串(或undefined ),而不是整数/数字。

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.您可以使用String.prototype.split定义args ,它将字符串拆分为结果数组。

// 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.最后,此变量将存储为String ,因此请确保在使用+运算符将其相乘之前将其转换为数字。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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