Gru*_*ton 2 node.js discord.js
我正在尝试制作一个与服务器进行一些交互的 Discord 机器人。
我已经编写了一些有效的代码,但是它存在一个大问题。这是我的代码:
if (command === "file") {
var accusor = message.author.id;
var username = args[0];
var reason = args[1];
var punishment = args[2];
var duration = args[3];
if(!duration) duration = "N/A";
console.log("Returning last " + amount + " for " + username);
request.post({url:'http://grumpycrouton.com/kismet/api/post_complaint.php', form: {accusor:accusor,search:username,reason:reason,punishment:punishment,duration:duration}}, function(err,httpResponse,body) {
message.reply(body);
});
}
Run Code Online (Sandbox Code Playgroud)
命令是!file {playername} {reason} {punishment} {duration},但问题是,有时一些变量可能有多个单词。例如,{reason}可能是“玩家过得不好”之类的内容,但由于参数的拆分方式,我的代码无法正确解析它。
假设输入了这个命令:
!file GrumpyCrouton "Player had a bad time" Kick "1 Day"
但是参数实际上会以不同的方式展开,因为第三个参数中有空格,但正则表达式将所有参数按空格分开,而不考虑引号。基本上,Discord 忽略引号并将每个单词用作它自己的参数,从而使{punishment}和{duration}的参数索引为 6 和 7 而不是 2 和 3,因为每个单词都被视为一个参数。
这是我的论点被阅读的方式:
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
Run Code Online (Sandbox Code Playgroud)
我怎样才能让用引号括起来的字符串作为单个参数而不是多个参数读取?
一个简单的正则表达式就可以解决问题:)
const input = 'ban user "Look at what you have done!" 7d "This is another string" value';
const regex = new RegExp('"[^"]+"|[\\S]+', 'g');
const arguments = [];
input.match(regex).forEach(element => {
if (!element) return;
return arguments.push(element.replace(/"/g, ''));
});
console.log(arguments);
/*
* Use a function with a spreader like:
* doSomething(...arguments);
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2356 次 |
| 最近记录: |