【问题标题】:Best way to get arguments from string by user for chat bot聊天机器人用户从字符串中获取参数的最佳方式
【发布时间】:2019-07-28 04:56:21
【问题描述】:

我需要接受 2 个参数:第一个是时间参数,例如“1m”、“2h 42m”、“1d 23h 3s”,第二个是文本。我想我可以将输入字符串转换为数组并使用正则表达式将其拆分为 2 个数组,首先使用“d”、“h”、“m”和“s”,然后再转换回字符串。但后来我意识到我需要第三个参数,它是可选的目标频道(dm 或当前频道,执行命令的地方),以及如果用户想在他的文本中包含 1m(它是提醒命令)怎么办

【问题讨论】:

    标签: arrays string discord chatbot discord.js


    【解决方案1】:

    最简单的方法是让用户用逗号分隔每个参数。尽管这会产生用户无法在其文本部分中使用逗号的问题。因此,如果这不是一个选项,另一种方法是获取消息内容并从剥离部分内容开始。您首先使用正则表达式获取时间部分。然后你寻找频道提及并将其删除。你剩下的应该只是文本。

    以下是一些(未经测试的)代码,可以引导您朝着正确的方向前进。试一试,如果有任何问题,请告诉我

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-20
      • 2023-01-15
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多