我需要接受2个参数:首先是时间参数,例如“1m”,“2h 42m”,“1d 23h 3s”,第二个是文本。我以为我可以将输入字符串转换为数组并使用正则表达式将其拆分为2个数组,首先使用“d”,“h”,“m”和“s”,然后将其他所有内容转换回字符串。但后来我意识到我需要第三个参数,它将成为可选目标通道(dm或当前通道,其中命令已被执行),以及如果用户想在其文本中包含1m(它的提醒命令)该怎么办
最简单的方法是让用户用逗号分隔每个参数。虽然这会产生用户无法在其文本部分中使用逗号的问题。因此,如果这不是一个选项,另一种方法是获取消息内容并从剥离部分内容开始。首先用正则表达式抓住时间部分。然后你寻找频道提及并剥离它们。你剩下的应该只是文字。
下面是一些(未经测试的)代码,可以引导您朝着正确的方向前进。尝试一下,如果您有任何问题,请告诉我
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