Registering Commands

Your bot's just sitting there doing no good. Let's change that!

With DiscordKit, it's extremely convenient to register slash commands and handle interactions with them. Simply use the handy utility methods and provided resultBuilders!

Guild Commands vs Global Commands

Apart from the fact that guild commands are only accessible in the guild that was specified during their creation, guild commands update instantly which is very useful during development. Global commands, although available in any server, may take up to a few hours to propagate and update in servers.

In this example, we'll be registering guild commands for the sake of time.

Configuring Environment Variables

Add a new static constant in your Bot struct called commandGuildID and set it to the ID of the server you want to test your slash commands in. It should look something like this:

static let commandGuildID = "964741354112577557"

Within the Bot struct in bot.swift, create a new private function as shown below:

private static func registerSlashCommands() async throws {
    try await bot.registerApplicationCommands(guild: commandGuildID) {
        NewAppCommand("hello", description: "Get a nice hello message") { interaction in
            print("Received hello interaction!")
        }
    }
}

Append the following lines to the ready event listener you added in Logging In to register application commands (slash commands in this case) by calling the function you've added above:

// Register slash commands after logging in
do {
    print("Registering interactions...")
    try await registerSlashCommands()
    print("Registered interactions!")
} catch {
    print("Failed to register interactions: \(error.localizedDescription)")
}

This needs to be added in the ready event handler and not outside as this requires the application ID of your bot to be known. This is only possible after receiving the READY gateway event.

At this point, run your app and take a look in the console. With any luck, you'll see a Registered interactions! pop up. Check the slash commands you registered the slash commands to, and you'll see that your bot now has one slash command!

However, there's one tiny issue (which may or may not be a a deal breaker xD): the bot doesn't respond to the interaction, as seen below:

If you check your console once again, you should see a message logging the received interaction as well, indicating that your application received this interaction but didn't respond to it.

We'll be fixing this in the next page, so hang along!

Last updated