我想这样做,以便它会在某些单词之后抓取某些信息,并例如在某些单词处停止
ss!submit | WIYISD: _____ | SHIWW: _____ | WDYWTA: _____ | SPN: _____
在WIYISD:,SHIWW:,WDYWTA:和SPN:之后收集争论,并在收集每个争论后停在|的位置。
我只是不知道从哪里开始。
我看了看别人的所作所为,然后试图把它自己拿出来,但不知道怎么做。
编辑:我想根据用户输入的内容将其发布到频道中,类似于不和谐测试人员中的错误机器人。
答案 0 :(得分:1)
首先在竖线处分割以获取字符串的每个部分(String.split()
)。然后,遍历子字符串("Loops and iteration")并检查每个字符串(String.startsWith()
)的开头,并根据需要处理结果参数。
const str = 'ss!submit | WIYISD: hopefully | SHIWW: this code | WDYWTA: will | SPN: help you!';
const split = str.split(' | ').slice(1); // Also removing the command portion.
const args = {};
for (let i = 0; i < split.length; i++) {
const arg = split[i];
if (arg.startsWith('WIYISD: ')) args.WIYISD = arg.replace('WIYISD: ', '');
else if (arg.startsWith('SHIWW: ')) args.SHIWW = arg.replace('SHIWW: ', '');
else if (arg.startsWith('WDYWTA: ')) args.WDYWTA = arg.replace('WDYWTA: ', '');
else if (arg.startsWith('SPN: ')) args.SPN = arg.replace('SPN: ', '');
else {
console.error('Check your syntax.'); // Send an error message instead...
break; // ...and return (illegal in this context).
}
}
console.log(args); // The result in this example is an object, not an array.
将此整合到您的消息事件中...
// const bot = new Discord.Client();
const prefix = 'ss!';
bot.on('message', message => {
// Stop if the author is a bot or the message doesn't start with the prefix.
if (message.author.bot || !message.content.startsWith(prefix)) return;
// This is a very crude setup. Consider a command handler to keep the code organized.
if (message.content.startsWith(`${prefix}submit `)) {
const split = message.content.split(' | ').slice(1);
const args = {};
for (let i = 0; i < split.length; i++) {
const arg = split[i];
if (arg.startsWith('WIYISD: ')) args.WIYISD = arg.replace('WIYISD: ', '');
else if (arg.startsWith('SHIWW: ')) args.SHIWW = arg.replace('SHIWW: ', '');
else if (arg.startsWith('WDYWTA: ')) args.WDYWTA = arg.replace('WDYWTA: ', '');
else if (arg.startsWith('SPN: ')) args.SPN = arg.replace('SPN: ', '');
else {
return message.channel.send(':x: Invalid syntax.')
.catch(console.error); // Make sure the catch rejected promises.
}
}
// Use 'args' as you wish.
}
});