To give myself a purpose for learning Swift, I decided to try and port my Discord bot, based on Node, to Swift. This of course means I lose the benefit of the fantastic Discord.js library.
Because I have no clue what I’m doing, I rely on these libraries to make the magic happen, so I was going to need something for Swift. Enter DiscordKit, another handy Discord library. I HIGHLY recommend following the getting started guide at: https://swiftcord.gitbook.io/discordkit-guide/, but here’s how I made the basics work:
import Foundation
import DiscordKitBot
@main
struct ribble {
static func main() {
let bot = Client(intents: [.unprivileged])
let commandGuildID = ProcessInfo.processInfo.environment["COMMAND_GUILD_ID"]
bot.ready.listen {
print("Logged in as \(bot.user!.username)#\(bot.user!.discriminator)!")
func registerSlashCommands() async throws {
try await bot.registerApplicationCommands(guild: commandGuildID) {
NewAppCommand("swifty", description: "Test The Swift Bot") { interaction in
print("Received swifty interaction!")
try? await interaction.reply("Whaddup Doe from Swift")
}
}
}
do {
print("Registering interactions...")
try await registerSlashCommands()
print("Registered interactions!")
} catch {
print("Failed to register interactions: \(error.localizedDescription)")
}
}
do {
try bot.login()
} catch let error {
print(error)
}
RunLoop.main.run()
}
}
I also had to learn the Swift Package Manager. Click on your project -> Package Dependencies to get started. From here click the + and add https://github.com/SwiftcordApp/DiscordKit, and then make sure that DiscordKitBot specifically is added to your target.
Seriously, follow the official guide though. 😂