These examples are simple, single-file bots demonstrating new features. They assume you have a Discord bot token available as an environment variable DISCORD_BOT_TOKEN and a Swift toolchain installed.
- Set your token in the shell session
- Windows PowerShell
$env:DISCORD_BOT_TOKEN = "YOUR_BOT_TOKEN"
- macOS/Linux bash/zsh
export DISCORD_BOT_TOKEN="YOUR_BOT_TOKEN"
- Windows PowerShell
- File:
Examples/AutocompleteBot.swift - What it does: Registers a
/searchcommand with an autocomplete provider for thequeryoption and echoes the selection. - Run (from repo root):
- SwiftPM as a script (Swift 5.9+ supports
swift run --swift-fileon some setups). If not supported, copy into your app target. - Suggested: integrate into your app by copying the file contents or loading via Xcode/SwiftPM executable target.
- SwiftPM as a script (Swift 5.9+ supports
- File:
Examples/FileUploadBot.swift - What it does: Sends a local file as an attachment with an embed. Update the
channelIdand file path before running. - Notes:
DiscordConfiguration(maxUploadBytes:)can override the default 100MB guardrail.
- File:
Examples/ThreadsAndScheduledEventsBot.swift - What it does: Prints thread lifecycle and guild scheduled event activity to stdout.
- File:
Examples/VoiceStdin.swift - What it does: Joins a voice channel and streams length‑prefixed Opus frames from stdin using
PipeOpusSource. - Requirements:
DiscordConfiguration(enableVoiceExperimental: true); provide Opus packets (48kHz, ~20ms). No Swift dependencies required. - Usage:
- Build/run the example and pipe framed Opus into stdin.
- Framing format per packet:
[u32 little‑endian length][<length> bytes]repeated.
let slash = SlashCommandRouter()
client.useSlashCommands(slash)
let ac = AutocompleteRouter()
client.useAutocomplete(ac)
ac.register(path: "search", option: "query") { ctx in
let q = (ctx.focusedValue ?? "").lowercased()
let results = ["Swift","Discord","NIO","Opus","Uploads","Autocomplete"]
return results.filter { q.isEmpty || $0.lowercased().contains(q) }
.prefix(5)
.map { .init(name: $0, value: $0) }
}let data = try Data(contentsOf: URL(fileURLWithPath: "./README.md"))
let attachment = FileAttachment(filename: "README.md", data: data, description: "Docs", contentType: "text/markdown")
_ = try await client.sendMessageWithFiles(channelId: "CHANNEL_ID", content: "Here is the file", embeds: [Embed(title: "Uploaded README")], files: [attachment])for await ev in client.events {
switch ev {
case .threadCreate(let ch): print("thread create", ch.id)
case .guildScheduledEventCreate(let e): print("gse create", e.name)
default: break
}
}- Examples are intentionally minimal; integrate them into your own executable target for
swift runconvenience. - Ensure the bot has the needed intents and permissions in the Developer Portal.