Optional Arguments

In Discapp, arguments are required by default. This means that when you declare a argument, Discapp will make sure that the user has written that argument, otherwise it'll not be exeecuted.

But, sometimes it's useful to receive an argument, but it's not mandatory. For these cases Discapp provides the feature of marking an argument as optional or not required.

For demonstrating optional arguments we will write the HelloCommand that receives one argument:

  • language (optional)

The HelloCommand will output the 'hello' word in the specified language. If language is not provided, then we'll assume it's english.

Writing the HelloCommand#

path/to/your/app/src/Commands/HelloCommand.ts
import { Command, BaseCommand, Argument } from "discapp";
@Command()
export class HelloCommand extends BaseCommand {
@Argument({
isRequired: false,
})
public language = "en";
public execute() {
switch (this.language) {
case "en":
return "hello";
case "pt":
return "olá";
default:
return "â–¯";
}
}
}
info

Here we're defining an optional argument and assigning it a default value. This means that if the user doesn't send the language argument, it'll be "english" by default.

Defining a default value is not required. If no default value is defined, the default value will be undefined.

Testing HelloCommand#

  • Sending !hello should make the bot respond with hello
  • Sending !hello en should make the bot respond with hello
  • Sending !hello pt should make the bot respond with olá
  • Sending !hello es should make the bot respond with â–¯

Considerations#

Notice that optional arguments must be the last argument or be followed only by optional arguments.

This is because, when parsing the arguments, allowing the existence of optional before optional arguments would allow nondeterministic behavior with arguments having multiple possible values at the same time.