Skip to content
This repository has been archived by the owner on Aug 22, 2024. It is now read-only.

@Rules @ComputedRules

Adam Pine edited this page May 18, 2021 · 1 revision

@Rules / @ComputedRules - Advanced message validation

If you need to use advanced expressions and aliases for your commands, this decorator is for you. It accepts regex (if you specify a string it will be considered as a regex expression, you have to escape the "." => "\." characters) and an instance of RuleBuilder.

import {
  ClassCommand,
  Command,
  CommandMessage,
  Rules
} from "@typeit/discord";

@Discord("!")
export abstract class Bye {
  @Command()
  @Rules(/salut\s{1,}toi(\s{1,}|$)/i)
  async hello(command: CommandMessage) {
    command.reply("Ciao!");
  }
}

The rules can also be applied to @Discord, it will be merged to the rules of commands inside the class:

In this example we rewrite explicitly the prefix rule

import {
  ClassCommand,
  Command,
  CommandMessage,
  Rules,
  Rule
} from "@typeit/discord";

@Discord()
@Rules(Rule().startWith("!")) // Explicit prefix
export abstract class Bye {
  @Rules(Rule("salut").space("toi").spaceOrEnd())
  async hello(command: CommandMessage) {
    command.reply("Ciao!");
  }
}

RuleBuilder

But it's not clear to put a RegExp... Yes for this reason you can use the RuleBuilder API:
Now to write /salut\s{1,}toi(\s{1,}|$)/i it's simple:

import {
  ClassCommand,
  Command,
  CommandMessage,
  Rules,
  Rule
} from "@typeit/discord";

@Discord("!")
export abstract class Bye {
  @Rules(Rule("salut").space("toi").spaceOrEnd())
  async hello(command: CommandMessage) {
    command.reply("Ciao!");
  }
}

Computed rules

Okay but I have rules that depends on computed my server datas like for my @CommandName... No problem just use @ComputedRules:

import {
  ClassCommand,
  Command,
  CommandMessage,
  Rules,
  Rule
} from "@typeit/discord";

async function getRules() {
  return [Rule("salut").space("toi").spaceOrEnd()]
}

@Discord("!")
export abstract class Bye {
  @ComputedRules(getRules)
  async hello(command: CommandMessage) {
    command.reply("Ciao!");
  }
}