🤖Basic Bot

Here are the basics to get your bot up and running.

import Discord

let bot = Bot(token: "<your token>", intents: Intents.default)
bot.run()

It's that simple. Even though it's online, it doesn't do much at the moment so lets change that. Lets have your bot respond to a simple message.

Responding to a message

The library comes with the EventListener class. This is used to listen to a handful of events that can be dispatched by Discord. This is how you add an event listener.

import Discord

let bot = Bot(token: "<your token>", intents: Intents.default)

class MyListener : EventListener {
    override func onMessageCreate(message: Message) async {
        // Don't respond to our own message
        guard !message.author.isBot else {
            return
        }

        if message.content == "hi swifty" {
            try! await message.channel.send("Hello!")
        }
    }
}

try! bot.addListeners(MyListener(name: "example"))
bot.run()

When you send a message in a channel, you should get a response.

Slash Commands

Discord.swift doesn't support the old format of text commands (!command). It utilizes Discords feature rich, UI based slash commands (/command). Lets create one!

import Discord

let bot = Bot(token: "<your token>", intents: Intents.default)

bot.addSlashCommand(
    name: "example",
    description: "Example command",
    guildId: 123456789012345678,
    onInteraction: { interaction in
        try! await interaction.respondWithMessage("This is an example")
    }
)

try! await bot.syncApplicationCommands() // Only needs to be done once
bot.run()

Once you've executed the above code, it should show up in your server like so.

When you've used the command, it will produce the following.

Last updated