我需要接受2个参数:第一个是时间参数,例如“ 1m”,“ 2h 42m”,“ 1d 23h 3s”,第二个是文本。我以为我可以将输入字符串转换为数组,并使用正则表达式将其分成2个数组,首先使用“ d”,“ h”,“ m”和“ s”,然后使用其他所有内容并将其转换回字符串。但是然后我意识到我将需要第三个参数,它将成为可选的目标通道(dm或当前通道,执行命令的位置),以及如果用户想要在其文本中包含1m的内容(这是提醒命令)
答案 0 :(得分:0)
最简单的方法是让用户用逗号分隔每个参数。尽管这会导致用户无法在其文本部分中使用逗号的问题。因此,如果这不是一个选择,那么另一种方法是获取消息内容并首先将其一部分剥离。首先,使用正则表达式获取时间部分。然后,您寻找频道提及内容并将其删除。剩下的只应该是文本。
下面是一些(未经测试的)代码,可以引导您朝正确的方向发展。试试看,让我知道您是否有任何问题
let msg = {
content: "1d 3h 45m 52s I feel like 4h would be to long <#222079895583457280>",
mentions: {
channels: ['<#222079895583457280>']
}
};
// Mocked Message object for testing purpose
let messageObject = {
mentions: {
CHANNELS_PATTERN: /<#([0-9]+)>/g
}
}
function handleCommand (message) {
let content = message.content;
let timeParts = content.match(/^(([0-9])+[dhms] )+/g);
let timePart = '';
if (timeParts.length) {
// Get only the first match. We don't care about others
timePart = timeParts[0];
// Removes the time part from the content
content = content.replace(timePart, '');
}
// Get all the (possible) channel mentions
let channels = message.mentions.channels;
let channel = undefined;
// Check if there have been channel mentions
if (channels.length) {
channel = channels[0];
// Remove each channel mention from the message content
let channelMentions = content.match(messageObject.mentions.CHANNELS_PATTERN);
channelMentions.forEach((mention) => {
content = content.replace(mention, '');
})
}
console.log('Timepart:', timePart);
console.log('Channel:', channel, '(Using Discord JS this will return a valid channel to do stuff with)');
console.log('Remaining text:', content);
}
handleCommand(msg);
对于messageObject.mentions.CHANNEL_PATTERN
,请查看this reference