Command options
Options can be declared within a command, with four types available:
- StringOption: Returns a string.
- NumberOption: Returns a number.
- BooleanOption: Returns a boolean.
- MentionOption: Returns the BaseUser who was mentioned.
Command options work with this template:
1!command -option1 value1 -option2 value2
Attach options into commands
To attach options to commands, the only thing we must do is set the options
field within our command class.
1import {2 ChatCommand,3 SetCommand,4 NumberOption5} from '@twitchfy/chatbot';6
7const options = {8 min: new NumberOption({ defaultValue: 1 }),9 max: new NumberOption({ defaultValue: 6 })10};11
12@SetCommand({13 name: 'dice',14 options15})16
17export default class DiceCommand extends ChatCommand {};
1const {2 ChatCommand,3 NumberOption4} = require('@twitchfy/chatbot');5
6const options = {7 min: new NumberOption({ defaultValue: 1 }),8 max: new NumberOption({ defaultValue: 6 })9};10
11module.exports = class DiceCommand extends ChatCommand {12 name = 'dice';13 options = options;14};
As seen in the example above, we are defining the options as an object whose keys are the option names. We are setting a defaultValue to the option, which will be returned if the option is not specified. If there isn’t a default value and the option isn’t specified, it will return null
.
Running commands with options
Running commands with options is similar to running a normal command, but the CommandContext includes an options object containing all of the options defined for the command.
1import {2 ChatCommand,3 SetCommand,4 NumberOption,5 type TwitchContext6} from '@twitchfy/chatbot';7
8const options = {9 min: new NumberOption({ defaultValue: 1 }),10 max: new NumberOption({ defaultValue: 6 })11};12
13@SetCommand({14 name: 'dice',15 options16})17
18export default class DiceCommand extends ChatCommand {19 async run(ctx: TwitchContext<typeof options>){20
21 const { min, max } = ctx.options;22
23 return await ctx.reply(`The dice has rolled. And the number is... ${this.generateValue(min, max)}`)24
25 }26
27 generateValue(min: number, max: number){28 return Math.floor(Math.random() * (max - min + 1)) + min;29 }30};
1const {2 ChatCommand,3 NumberOption4} = require('@twitchfy/chatbot');5
6const options = {7 min: new NumberOption({ defaultValue: 1 }),8 max: new NumberOption({ defaultValue: 6 })9};10
11module.exports = class DiceCommand extends ChatCommand {12 name = 'dice';13 options = options;14 async run(ctx){15
16 const { min, max } = ctx.options;17
18 return await ctx.reply(`The dice has rolled. And the number is... ${this.generateValue(min, max)}`)19
20 }21
22 generateValue(min, max){23 return Math.floor(Math.random() * (max - min + 1)) + min;24 }25
26};