Getting off the Ground

So you've created a project and added DiscordKit to it. What's next?

Main Entry-point

If you've followed Creating a Project and Installation, your project should contain a main.swift file with some content. It should look something this:

As you can see, it has some example code. We don't want any of that - delete everything and replace it with the code below:

At this point, you might be faced with a bunch of cryptic build errors - a known Swift compiler bug. I was too, and the workaround was to rename the main.swift file to some other name - in my case I chose Bot.swift, but you can choose anything that suits you. From this point on in the guide, Bot.swift will refer to this file and main.swift will no longer be used.

Now let's try and run the thing. If you're using Xcode, press the "Play" button in the top left. if you're using VSCode, press the F5 key. Otherwise, run the command swift run in your terminal. Once it finishes compiling,

Note that the first time that you compile you bot, compilation will take significantly longer than subsequent builds, especially on Linux. This is because swift is building your dependency cache. Please be patient as it does so.

We've created a simple main entry-point for your app, which is more scalable and encapsulated than the original code. Next, let's securely add our bot's token to the environment.

Bot Token

There are 2 ways to provide your Bot token.

Providing a bot token with a file

You can store your token in a separate file, and then load the contents of that file as a string. Here is a code example of this method, which loads the token from a file in the current working directory called token.txt:

static let bot = Client(intents: .unprivileged)
// Loads the contents of the file "token.txt" as a string
// (will crash if the file is not found!)
static let token = try! String(contentsOfFile: "token.txt")
public static func main() {
    bot.login(token: token) // Log in with the loaded token
}

Make sure to add the file containing your token to your .gitignore file, so that you don't accidentally upload your token to the internet!

Providing a bot token with an environment variable

You can provide your bot token in the environment variable DISCORD_TOKEN. Then simply call bot.login() to connect your bot to Discord.

Last updated