Adding Command Options
commands --help
You now have a bot that uses slash commands, what's next? Command options, of course! They make your commands dynamic and are a crucial part of most commands. And of course, they're easy-as-pie to work with, thanks to the resultBuilder
syntax used by DiscordKit.
What are resultBuilder
s?
If you've used SwiftUI or even DiscordKit, you've already used them! They allow the special syntax you can use to create commands! It's special syntax that allows building multiple "blocks" into a "stack" (i.e. array), such as creating SwiftUI views or registering your bot's commands! In this page, we'll be further using this syntax to register, you guessed it, command options.
Let's try adding options to the /hello command we previously added. A name
option would be really handy, so we could give the user personalised hello messages for increased human-ness.
To do so, we can add option children blocks to the /hello command we defined earlier, similar to how you'd add children to a SwiftUI view:
Then, we'd need to handle the value of the name option, if one is given. As we did not specify that our option is required, it's optional by default. The interaction
struct passed to your handler contains the optionValue(of:)
method that allows easy retrieval of option values. Let's modify the handler to send back a personalised hello message if a name was specified, otherwise just return a random hello message as usual.
Here, we're using an optional binding to conditionally unwrap and run a block of code if the name option isn't nil
(which means it was specified by the user). The else
clause will be run if the value of the option is nil
.
Give the command a go - with just a few lines, you've added and handled your bot's first command option! How cool is that?
Last updated