Responding to Commands
Hello World! Coming through loud and clear!
Now that you've registered a command, lets respond to it! For the /hello command, we want our bot to respond with a random fun message:
Hello, World!
Helloooo! I can hear you!
Who's there?
Beep, boop, I'm a bot.
I'm alive!
Let's start by putting all those messages in an array in our Bot
struct:
@main
public struct Bot {
private static let HELLO_MESSAGES = [
"Hello, World!",
"Helloooo! I can hear you!",
"Who's there?",
"Beep, boop, I'm a bot.",
"I'm alive!"
]
...
We can use the built-in .randomElement()
method on our array to get a random hello message. As we're sure our array isn't empty, we can safely force-unwrap the result with !
. Putting all that together in our interaction's handler function gives us:
NewAppCommand("hello", description: "Get a nice hello message") { interaction in
print("Received hello interaction!")
// Reply with a random hello message
try? await interaction.reply(HELLO_MESSAGES.randomElement()!)
}
Run your bot and invoke the /hello command. Your bot should respond with a random message each time, as shown below! Congrats on your first functional slash command!

Last updated