Discord.js命令输入字符串

时间:2018-06-16 07:18:51

标签: javascript discord discord.js

我正在写一个Discord Bot游戏,我的问题是玩家必须创造一个角色。但是,每个标准人员都有名字和姓氏,但我在一个命令中接受其他输入。我的问题是,我不确定在确实放置引号的情况下,我的代码是否会忽略名称周围的引号。

说一个人为他们的角色Joe Shmoe命名。当他们输入命令p://ccreate "Joe Shmoe" Male 38时,我担心我的论证翻译可能需要'" Joe'作为args [0],' Shmoe"'如args [1],男性为args [2],38为args [3]。我的问题是我想要" Joe Shmoe"被解释为一个论点。这是我的代码:

client.on("message", async message => {
if(message.author.bot) return;
if(message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase(); 

如果我是对的,请您详细说明如何编辑它,以便如果我的代码收到这样的问题,它会将字符串保存为一个?但是,我也知道有些替代方法可能会在任何非整数,布尔值等方面都需要引号,所以最好你能找到一种方法,包含在引号中的任何内容都包含在一个字符串中,如果一个字符串只包含一个单词,仍然可以在不抛出代码的情况下将其识别为字符串。我知道这已经完成了,而不是怎么做。

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点,这里有一种可能的方法,用于解释每一步中发生的事情。

/* The user enters  p://ccreate "Joe Shmoe" Male 38 */
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
// args = ['p://ccreate', '"Joe', 'Shmoe"', 'Male, '38'];
const command = args.shift().toLowerCase();
// args = ['"Joe', 'Shmoe"', 'Male', '38'];

/* Now you want to get the full name, i.e: the first 2 elements from args */
const name = args.slice(0,2).join(' ').replace(/"/g,'');
/* args.slice(0,2) gets the first 2 elements
   .join(' ') joins these elements separating them with a space
   .replace(/"/g,'') removes all instances of the character " */
// So now, name = 'Joe Shmoe'

const gender = args.slice(-2)[0];
/* args.slice(-2) gets the last 2 elements in the array
   [0] gets the first element in the returned array of 2 elements */
// Therefore, gender = 'Male'

const age = args.slice(-1);
/* args.slice(-1) gets the last element in the array */
// As a result, age = '38'. Keep in mind that this is a string, you could use parseInt(age) if you require it as an integer.