SwiftDisc is a Swift-first Discord API wrapper for building bots and integrations with async/await, typed models, and practical high-level tools.
This README covers install, first bot run, intents, and example entry points.
- Swift 6.2 concurrency model and actor-safe APIs.
- Gateway and REST support in one library.
- Built-in rate-limit handling and reconnect logic.
- High-level routers for commands, slash commands, autocomplete, components, and views.
- Guild sticker write operations are supported (
createGuildSticker,modifyGuildSticker,deleteGuildSticker). - Runnable examples in Examples.
Add SwiftDisc with Swift Package Manager:
// Package.swift
.dependencies([
.package(url: "https://github.com/M1tsumi/SwiftDisc.git", from: "2.3.0")
]),
.targets([
.target(
name: "YourBot",
dependencies: ["SwiftDisc"]
)
])- macOS 11+
- iOS 14+
- tvOS 14+
- watchOS 7+
- Windows with Swift 6.2+
import Foundation
import SwiftDisc
@main
struct MyBot {
static func main() async {
let token = ProcessInfo.processInfo.environment["DISCORD_BOT_TOKEN"] ?? ""
let client = DiscordClient(token: token)
await client.setOnReady { ready in
print("Logged in as \(ready.user.username)")
}
await client.setOnMessage { message in
guard message.content?.lowercased() == "ping" else { return }
do {
try await message.reply(client: client, content: "Pong!")
} catch {
print("Reply failed: \(error)")
}
}
do {
try await client.loginAndConnect(intents: [.guilds, .guildMessages, .messageContent])
let events = await client.events
for await _ in events { }
} catch {
print("Client failed: \(error)")
}
}
}import Foundation
import SwiftDisc
@main
struct SlashBot {
static func main() async {
let token = ProcessInfo.processInfo.environment["DISCORD_BOT_TOKEN"] ?? ""
let client = DiscordClient(token: token)
let slash = SlashCommandRouter()
await slash.register("ping") { ctx in
try await ctx.client.createInteractionResponse(
interactionId: ctx.interaction.id,
token: ctx.interaction.token,
content: "Pong!"
)
}
await client.useSlashCommands(slash)
try? await client.loginAndConnect(intents: [.guilds])
let events = await client.events
for await _ in events { }
}
}If your bot appears to connect but receives no data, one of these is usually the reason:
DISCORD_BOT_TOKENis missing or invalid.- Required intents are not passed to
loginAndConnect. - Privileged intents (especially
messageContent) are not enabled in the Discord Developer Portal. - Bot was invited without the scopes/permissions you expect.
DiscordClient: main actor and lifecycle entrypoint.- Gateway: real-time events and dispatch.
- REST client: typed HTTP request/response operations.
- High-level modules in Sources/SwiftDisc/HighLevel:
CommandRouterSlashCommandRouterAutocompleteRouterViewManager- collectors/builders/utilities
- Typed models in Sources/SwiftDisc/Models.
These examples are included and useful for real onboarding:
- Examples/PingBot.swift
- Examples/CommandsBot.swift
- Examples/SlashBot.swift
- Examples/AutocompleteBot.swift
- Examples/ComponentsExample.swift
- Examples/ViewExample.swift
- Examples/FileUploadBot.swift
Packaged executable targets can be run with:
swift run PingBotExample
swift run CommandsBotExample
swift run SlashBotExample
swift run AutocompleteBotExample
swift run ComponentsExample
swift run ViewExample
swift run FileUploadBotExampleSwiftDisc v2.3.0 is a correctness and reliability patch release that fixes critical compilation issues for Swift 6.2, resolves gateway connection and disconnect handling bugs, corrects multipart attachment handling, and improves WebSocket message size limits. This release ensures stability and proper behavior across gateway, REST, and WebSocket layers.
SwiftDisc provides several debugging and observability features for developers:
- Gateway decode diagnostics — Enable
DiscordConfiguration.enableGatewayDecodeDiagnosticsto log gateway payload decoding failures with opcode/event context and payload previews - Rate limit observability — Use
DiscordConfiguration.onRateLimitto observe REST bucket updates and waits through lightweightRateLimitEventsnapshots - Typed error handling — All REST and gateway operations throw
DiscordErrorwith descriptive messages and optionaldebugContextfor troubleshooting - Router error handlers —
CommandRouter,SlashCommandRouter, andViewManagersupport optional error handlers that receive context about failed operations - Default error logging — Routers include default error logging with channel ID, pattern type, and custom ID context when no custom error handler is set
- Build/toolchain mismatch:
- Use Swift 6.2+.
- Connected but no command responses:
- Verify intents and Developer Portal privileged intent settings.
- 429/rate-limit issues:
- Avoid tight retry loops and bursty duplicate requests.
- CI failures:
- Start by checking runner logs in Errors.
- Main API and usage reference: SwiftDiscDocs.txt
- Project changes per release: CHANGELOG.md
- Contributing workflow: CONTRIBUTING.md
- Repository standards and behavior: CODE_OF_CONDUCT.md
- Discord support server: https://discord.gg/6nS2KqxQtj
- Issues and feature requests: https://github.com/M1tsumi/SwiftDisc/issues
MIT. See LICENSE.