DiscordKit Guide
GitHub Repository
  • 👋Welcome
  • 🚀Getting Started
    • Creating a Project
      • Creating a bot using a SPM project (Recommended)
      • Creating a bot using an Xcode Project
    • Installation
    • Example Project
  • 🤖Creating a Bot
    • Getting off the Ground
    • Logging In
    • Registering Commands
    • Responding to Commands
    • Adding Command Options
    • Deploying on Linux
  • đŸĒĻLegacy
    • Message Commands
  • ✨Enhancements
    • Logging
  • đŸ“ĻNitty-gritty
    • What's in the box?
    • Gateway
    • Event Dispatching
Powered by GitBook
On this page
  1. Creating a Bot

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!

You'll have to respond to an interaction within 3 seconds, if not the Discord client will display an error stating that "The interaction did not respond".

If you need more than 3s to respond to an interaction (e.g. a 🐌 database), you'll need to send a deferred response first (guide coming soon) to extend the deadline to 15 minutes. This will show the user a loading state which will be replaced by a response once you send one.

PreviousRegistering CommandsNextAdding Command Options

Last updated 2 years ago

🤖
GitHub - SwiftcordApp/DiscordKitGettingStarted at responding-to-commandsGitHub
Something not working as expected? Check out this branch!
Hello World!
Logo