聊天机器人用户从字符串中获取参数的最佳方法

Best way to get arguments from string by user for chat bot

我需要接受 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