Skip to content

SpinnySpiwal/Spincord-Kit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SpincordKit 🎡

Swift 5.9 Platforms License

The first Discord API Library to include Voice Support in Native Swift!

SpincordKit is a comprehensive Swift library for interacting with the Discord API, featuring full voice support, real-time gateway connections, and all the tools you need to build a fully fledged Discord Client Alternative. ETF Encoding is not yet supported, but is in the works. It is also the first Swift library to support all Discord voice encryption algorithms.

✨ Features

  • πŸš€ Gateway Connection - Real-time WebSocket connection to Discord
  • 🎡 Full Voice Support - Complete voice chat implementation with audio encoding
  • πŸ” Advanced Voice Encryption - All Discord voice encryption algorithms supported
  • πŸ“‘ Voice Gateway - Dedicated voice WebSocket connections
  • 🌐 REST API Client - Complete HTTP API wrapper with retry logic
  • πŸ’¬ DM Channel Caching - Intelligent caching for direct messages
  • πŸŽ›οΈ Adjustable Bitrate - Bypass Discord's bitrate limits for premium audio quality
  • πŸ“± Cross-Platform - Supports macOS 13+ and iOS 16+

πŸ› οΈ Installation

Swift Package Manager

Add SpincordKit to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/spinnyspiwal/SpincordKit.git", branch: "main")
]

Or add it through Xcode:

  1. File β†’ Add Package Dependencies
  2. Enter the repository URL
  3. Click Add Package

Requirements

  • macOS 13.0+ or iOS 16.0+
  • Swift 5.9+
  • Opus library (for voice encoding)

πŸš€ Quick Start

Basic Bot Setup

import SpincordKit

let gateway = DiscordGateway(token: "YOUR_BOT_TOKEN")

// Register event handlers
gateway.registerCallback(event: "READY") { payload in
    print("Bot is ready! πŸŽ‰")
    print("Logged in as: \(gateway.userData.globalName ?? "Unknown")")
}

gateway.registerCallback(event: "MESSAGE_CREATE") { payload in
    guard let d = payload["d"] as? [String: Any],
          let content = d["content"] as? String,
          let channelId = d["channel_id"] as? String else { return }

    if content == "!ping" {
        gateway.sendMessage(channelId: channelId, content: "Pong! πŸ“") { result in
            switch result {
            case .success: print("Message sent!")
            case .failure(let error): print("Error: \(error)")
            }
        }
    }
}

// Connect to Discord
Task {
    await gateway.connect()
}

Voice Chat Example

import SpincordKit

// Connect to a voice channel
await gateway.connectToVoice(guildId: "GUILD_ID", channelId: "VOICE_CHANNEL_ID")

// Register voice connection callback
gateway.registerCallback(event: "CONNECTED") { payload in
    print("Connected to voice channel! 🎀")

    // Start speaking
    Task {
        await gateway.voiceSession?.sendSpeakingEvent(isSpeaking: true)
    }
}

// Send audio data (PCM format)
if let voiceSession = gateway.voiceSession {
    let pcmData = loadAudioData() // Your PCM audio data
    let encryptor = VoiceEncryption(
        secretKey: secretKey,
        mode: .xsalsa20Poly1305Lite
    )

    Task {
        await voiceSession.privateData.udpVoiceConn?.sendAudioPacket(
            pcmData,
            frameSize: 960,
            encryptor: encryptor
        )
    }
}

REST API Usage

// Send a message
gateway.sendMessage(channelId: "CHANNEL_ID", content: "Hello World!") { result in
    switch result {
    case .success(let response):
        print("Message sent: \(response)")
    case .failure(let error):
        print("Failed to send message: \(error)")
    }
}

// Get channel messages
gateway.getChannelMessages(
    channelId: "CHANNEL_ID",
    limit: 50
) { result in
    switch result {
    case .success(let messages):
        print("Retrieved \(messages) messages")
    case .failure(let error):
        print("Error fetching messages: \(error)")
    }
}

// Get DM channels (when you fetch a channel, it will be intelligently cached.)
gateway.getDMChannels { result in
    switch result {
    case .success(let channels):
        print("DM Channels: \(channels)")
    case .failure(let error):
        print("Error: \(error)")
    }
}

🎡 Voice Features

Supported Encryption Modes

SpincordKit supports all Discord voice encryption algorithms:

  • aead_aes256_gcm - AES-256-GCM AEAD encryption
  • aead_aes256_gcm_rtpsize - AES-256-GCM with RTP size suffix
  • aead_xchacha20_poly1305_rtpsize - XChaCha20-Poly1305 with RTP size
  • xsalsa20_poly1305 - XSalsa20-Poly1305 (standard)
  • xsalsa20_poly1305_suffix - XSalsa20-Poly1305 with suffix
  • xsalsa20_poly1305_lite - Lightweight XSalsa20-Poly1305
  • xsalsa20_poly1305_lite_rtpsize - Lite version with RTP size

Audio Encoding

// Configure Opus encoder
let encoder = try DiscordOpusEncoder(
    sampleRate: 48000,
    channels: 2,
    frameSize: 960,
    bitrate: 128000  // High quality bitrate
)

// Encode PCM audio
let pcmData = loadPCMAudio()
let encodedAudio = try encoder.encode(pcm: pcmData)

Audio Format Conversion

// Convert Float32 to Int16
let int16Data = PCMFormatter.convertFloat32ToInt16(float32Data)

// Ensure stereo format
let stereoData = PCMFormatter.ensureStereo(monoData, inputChannels: 1)

// Send with automatic format conversion
await udpConnection.sendAudioPacketWithFormat(
    audioData,
    frameSize: 960,
    format: .float32,
    inputChannels: 1,
    encryptor: encryptor
)

πŸ“š Advanced Usage

Custom Presence

let activity = Activity(
    name: "🎡 SpincordKit",
    type: 0, // Playing
    state: "Building awesome bots!"
)

await gateway.updatePresence(
    status: "online",
    afk: false,
    since: 0,
    activities: [activity]
)

Event Handling

// Handle various Discord events
gateway.registerCallback(event: "GUILD_CREATE") { payload in
    // Handle guild events
}

gateway.registerCallback(event: "VOICE_STATE_UPDATE") { payload in
    // Handle voice state changes
}

gateway.registerCallback(event: "MESSAGE_DELETE") { payload in
    // Handle message deletions
}

Error Handling

// Register error callbacks
gateway.registerCallback(event: "ERROR") { payload in
    print("Gateway error: \(payload)")
}

// Handle connection issues
gateway.registerCallback(event: "RECONNECT") { payload in
    print("Reconnecting to Discord...")
}

πŸ”§ Configuration

Voice Configuration

// Custom voice configuration
let config = VoiceChatConfig(
    sampleRate: 48000,
    channels: 2,
    frameSize: 960,
    bitrate: 256000  // High quality
)

Logging

// Enable verbose logging
Log.verbose = true

// Or use the vprint function
vprint("Debug message", someVariable)

πŸ“– API Reference

DiscordGateway

The main gateway class for Discord connections.

  • init(token: String) - Initialize with bot token
  • connect() - Connect to Discord gateway
  • disconnect() - Disconnect from gateway
  • registerCallback(event:_:) - Register event handlers
  • sendMessage(channelId:content:completion:) - Send messages
  • connectToVoice(guildId:channelId:) - Connect to voice channels

VoiceGateway

Voice-specific gateway for audio streaming.

  • sendSpeakingEvent(isSpeaking:) - Update speaking status
  • updateEncodingBitrate(bitrate:) - Change audio quality
  • registerCallback(event:_:) - Register voice event handlers

UDPVoiceConnection

UDP connection for voice data transmission.

  • sendAudioPacket(_:frameSize:encryptor:) - Send audio data
  • sendSilenceFrames(encryptor:) - Send silence frames
  • discoverIP(_:) - Discover external IP for voice

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Discord for their comprehensive API documentation
  • The Swift community for excellent networking libraries
  • Contributors to the Opus and Sodium libraries

πŸ’¬ Support

  • Create an issue for bug reports or feature requests
  • Join our Discord Server

Made with ❀️ by SpinnySpiwal

About

SPINCORDKIT OPEN SOURCE BEFORE GTA 6!

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages