Array Arguments

Sometimes the value of a argument should be a list of values. For these cases, Discapp provides support for array arguments.

In this chapter we will write the SumCommand that will receive the parcels argument, that will be a array. The SumCommand will return the sum of all the elements in parcels argument.

Writing the SumCommand#

path/to/your/app/src/Commands/SumCommand.ts
import { Command, BaseCommand, Argument } from "discapp";
@Command()
export class SumCommand extends BaseCommand {
@Argument()
public parcels: string[];
public execute() {
return this.parcels.reduce((total, parcel) => {
return total + Number(parcel);
});
}
}
info

All array arguments must be of type string[] or any[]. This is because we can't currently reflect the specific type of an array property.

Testing the SumCommand#

  • Sending !sum should warn that parcels is required
  • Sending !sum 1 2 should make the bot respond with 3
  • Sending !sum 1 2 3 should make the bot respond with 6

Considerations#

Arrays arguments must be the last argument of your command, otherwise the command will not be valid.

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