【问题标题】:Check if discord bot command's arguments match with the format specified by the commands config检查 discord bot 命令的参数是否与命令配置指定的格式匹配
【发布时间】:2020-12-25 09:57:00
【问题描述】:

我想做一些东西来检查为命令提供的参数是否与命令期望的参数匹配。

例如;
config 命令要求第一个参数为 showsetreset
如果使用setreset,则需要多2 个参数:

module.exports = class Config {
 constructor() {
  this.cmdconf = {
   // arguments key
   args: '< show [setting] | set <option> <value> | reset <option> <value> >',
  };
 }
 run() {
  // command
 }
};

键:&lt;required&gt;[optional]
&lt;option&gt; 是要更改的设置,&lt;value&gt; 是要更改的值
当我运行命令时,我想检查是否提供了所有参数

有没有一种方法可以让我轻松地做到这一点,并让它适用于每个命令,而无需为每个命令单独编写检查器?

编辑:我举了一个更高级的例子

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    假设您的命令结构如下:

    module.exports = {
      name: 'config',
      execute (message, args) => {
    

    您可以将args 属性添加为array

    module.exports = {
      name: 'config',
      args: 'show [setting] | set <option> <value> | reset <option> <value>'
      execute (message, args) => {
    

    在您的命令处理程序中,添加以下行:

    const isReq = (string) => {
     const matched = string.match(/^<(.+)>$/);
     return matched ? matched[1] : false;
    };
    
    if (command.args) {
     var everythingAccountedFor = false;
     const options = command.args.split(' | ');
     for (const option of options) {
      const [definer, ...values] = option.split(' ');
      if (definer !== args[0]) continue;
    
      if (
       values.some((word, index) => isReq(word) && args[index + 1] !== isReq(word))
      )
       break;
    
      everythingAccountedFor = true;
      break;
     }
     if (!everythingAccountedFor)
      return message.channel.send(
       `You're message did not provide a required argument.\nHere is the command structure: \`${command.args}\``
      );
    }
    

    这是我在测试 Discord 服务器中设置的示例:

    【讨论】:

    • 这很有用,但是当涉及到命令的多个参数时,我仍然不知道该怎么做。我编辑了我的问题,对我正在寻找的内容进行了更高级和更详细的解释。
    • 好的,感谢您提出更深入的问题。我现在会尝试编辑我的答案。
    • 忽略我不正确的“you're”形式,我很困:p
    • 谢谢,我一定会看一看,看看效果如何。
    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 2019-11-12
    • 2017-05-03
    • 2017-08-31
    相关资源
    最近更新 更多