DEV Community

quefep
quefep

Posted on

Building Discord Bots with Swift: A Complete Guide to SwiftDisc in 2025

Discord bots power millions of servers, handling everything from moderation to custom games. But if you're a Swift developer, you've likely noticed a gap: most Discord libraries are built for JavaScript, Python, or Java. What if you want to leverage Swift's type safety, modern concurrency, and elegant syntax?

That's where SwiftDisc comes in.

In this guide, I'll show you how to build a fully functional Discord bot using Swift, from setup to deployment. Whether you're an iOS developer exploring server-side Swift or a bot developer looking for a better experience, this tutorial has you covered.

What is SwiftDisc?

SwiftDisc is a modern, Swift-native wrapper for the Discord API that brings:

  • Type-safe API interactions using Swift's strong type system
  • Native async/await support for clean, readable code
  • Comprehensive Discord API coverage including slash commands, buttons, modals
  • Swift-first design that feels natural to Swift developers
  • Active maintenance with regular updates for new Discord features

Prerequisites

Before we start, make sure you have:

  • Swift 5.9 or later installed
  • A Discord account and server for testing
  • Basic familiarity with Swift and async/await
  • 15-20 minutes to follow along

Step 1: Setting Up Your Discord Application

First, we need to create a Discord bot and get credentials:

  1. Visit the Discord Developer Portal
  2. Click "New Application" and give it a name
  3. Navigate to the "Bot" section and click "Add Bot"
  4. Under "Privileged Gateway Intents," enable necessary intents
  5. Copy your bot token (keep this secret!)
  6. Use the OAuth2 URL Generator to invite your bot to a test server

Security Note: Never commit your bot token to version control. Use environment variables instead.

Step 2: Creating Your Swift Project

mkdir MyDiscordBot
cd MyDiscordBot
swift package init --type executable
Enter fullscreen mode Exit fullscreen mode

Add SwiftDisc to your Package.swift:

// Package.swift
// swift-tools-version: 5.9
import PackageDescription

let package = Package(
    name: "MyDiscordBot",
    platforms: [.macOS(.v13)],
    dependencies: [
        .package(url: "https://github.com/M1tsumi/SwiftDisc.git", from: "1.0.0")
    ],
    targets: [
        .executableTarget(
            name: "MyDiscordBot",
            dependencies: ["SwiftDisc"]
        )
    ]
)
Enter fullscreen mode Exit fullscreen mode

Step 3: Building Your First Bot

Create your main bot file:

import SwiftDisc
import Foundation

@main
struct DiscordBot {
    static func main() async throws {
        let token = ProcessInfo.processInfo.environment["DISCORD_TOKEN"]!
        let bot = DiscordClient(token: token)

        // Handle ready event
        bot.onReady { user in
            print("โœ… Logged in as \(user.username)")
        }

        // Handle message events
        bot.onMessage { message in
            guard !message.author.isBot else { return }

            if message.content == "!ping" {
                try await message.reply("Pong! ๐Ÿ“")
            }
        }

        try await bot.connect()
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Adding Slash Commands

Modern Discord bots use slash commands for better UX:

// Register commands on startup
bot.onReady { user in
    try await bot.registerSlashCommand(
        name: "hello",
        description: "Greet the bot"
    )
}

// Handle slash command interactions
bot.onSlashCommand { interaction in
    if interaction.commandName == "hello" {
        try await interaction.respond(
            content: "Hello, \(interaction.user.username)! ๐Ÿ‘‹"
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Working with Embeds and Rich Content

SwiftDisc makes creating beautiful embeds simple:

let embed = Embed(
    title: "Server Stats",
    description: "Current server information",
    color: 0x5865F2,
    fields: [
        .init(name: "Members", value: "\(guild.memberCount)", inline: true),
        .init(name: "Online", value: "\(onlineCount)", inline: true)
    ],
    footer: .init(text: "Powered by SwiftDisc")
)

try await channel.send(embed: embed)
Enter fullscreen mode Exit fullscreen mode

Step 6: Running Your Bot

Set your token as an environment variable:

export DISCORD_TOKEN="your-bot-token-here"
swift run
Enter fullscreen mode Exit fullscreen mode

You should see your bot come online!

Why Choose Swift for Discord Bots?

Type Safety: Catch errors at compile time, not runtime. Swift's strong typing prevents common Discord API mistakes.

Modern Concurrency: Swift's async/await makes handling Discord's event-driven architecture clean and intuitive.

Performance: Swift's compiled nature means lower memory usage and faster response times compared to interpreted languages.

Familiar Syntax: If you're already building iOS/macOS apps, you can use the same language for your bots.

Comparison with Other Libraries

Feature SwiftDisc Discord.py Discord.js
Language Swift Python JavaScript
Type Safety โœ… Strong โš ๏ธ Optional โš ๏ธ Optional
Async/Await โœ… Native โœ… Native โœ… Native
Learning Curve Low (for Swift devs) Low Low
Performance High Medium Medium

Deploying Your Bot

Option 1: Docker

Create a Dockerfile:

FROM swift:5.9
WORKDIR /app
COPY . .
RUN swift build -c release
CMD [".build/release/MyDiscordBot"]
Enter fullscreen mode Exit fullscreen mode

Option 2: Cloud Platforms

  • Railway
  • Heroku
  • DigitalOcean
  • AWS EC2

Next Steps and Advanced Features

Now that you have a working bot, explore:

  • Buttons and Select Menus for interactive components
  • Modal forms for user input
  • Voice channel integration for music bots
  • Database integration with MongoDB or PostgreSQL
  • Sharding for large bots (1000+ servers)

Common Pitfalls to Avoid

  1. Forgetting Gateway Intents: Enable necessary intents in the Developer Portal
  2. Blocking the main thread: Always use async/await for API calls
  3. Hardcoding tokens: Use environment variables
  4. Not handling rate limits: SwiftDisc handles this automatically, but be aware of limits

Contributing and Community

SwiftDisc is open source and welcomes contributions:

For Sneak Peaks and Early Updates - https://x.com/thats_alot

Conclusion

Swift isn't just for iOS apps anymore. With SwiftDisc, you can build powerful, type-safe Discord bots using a language you already know and love. The combination of Swift's modern features and Discord's rich API opens up endless possibilities.

Ready to get started? Clone the SwiftDisc repository, follow this tutorial, and join our community. I can't wait to see what you build!

โญ If you found this helpful, star SwiftDisc on GitHub and share with other Swift developers!

Top comments (0)