如何在discord.js中解析带引号的命令参数?

时间:2019-12-04 15:31:52

标签: discord.js

标题说明了大部分内容。 我想做一个轮询命令:

  const args = message.content.slice(1).trim().split(/ +/g); // trims the args
    const command = args.shift().toLowerCase(); // finds the actual command
    const guild = message.guild;
client.on("message", async message => {

   if (command === "poll") {
        const poll = new Discord.RichEmbed().setColor('#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6));
        if (args) {
            if (message.member.roles.find(r => r.name === "poller")) {
                var upvote = message.guild.emojis.find(emoji => emoji.name == 'Upvote');
                var downvote = message.guild.emojis.find(emoji => emoji.name == 'Downvote');
                let sendTo = "";
                sendTo+=(args[0]);
                sendTo += (upvote + args[1]);
                sendTo += ("\n\n" + downvote + args[2]);
                message.channel.send(sendTo)
                    .then(function(message) {
                        message.react(guild.emojis.find(emoji => emoji.name === "Upvote"));
                        message.react(guild.emojis.find(emoji => emoji.name === "Downvote"));
                    }).catch(function() {
                        poll.setDescription("Error has occured. Stopping process.");
                        poll.setFooter('Unknown error has occured. Terminating action 000921.');
                        message.channel.send(poll);
                    });
                message.delete().catch(O_o => {});
            }
        } else {
            console.log("Failed");
        }
    }
}

这里的主要问题是,我需要多个单词来进行民意调查,但是即使使用引号,它仍然会像正常一样返回它。 例如;投票“ test 1”“ test 2”“ test 3”返回“ test:upvote:1”:downvote:“ test。 我该怎么做才能解决此问题?

1 个答案:

答案 0 :(得分:0)

您可以使用:

const pollOptions = message.content.match(/".+?"/g).map(str => str.replace(/"/g, ''))

// ;poll "Option 1" "Option 2" "Option 3"
// pollOptions would equal ['Option 1', 'Option 2', 'Option 3']

代码段示例:

const input = '"Option 1" and also "Option 2", and maybe "Option 3" as well'
const updated = input.match(/".+?"/g).map(str => str.replace(/"/g, ''))

console.log(updated) // isolating whatever's within the quotes