Code Monkey home page Code Monkey logo

discordkit's Introduction

DiscordKit

Package for interacting with Discord's API to build Swift bots

DiscordKit for Bots is now released! Use DiscordKit to create that bot you've been looking to make, in the Swift that you know and love!

About

DiscordKit is a Swift package for creating Discord bots in Swift.

If DiscordKit has helped you, please give it a ⭐ star and consider sponsoring! It keeps me motivated to continue developing this and other projects.

Installation

Swift Package Manager (SPM):

Package.swift

Add the following to your Package.swift:

.package(url: "https://github.com/SwiftcordApp/DiscordKit", branch: "main")
Xcode Project

Add a package dependancy in your Xcode project with the following parameters:

Package URL:

https://github.com/SwiftcordApp/DiscordKit

Branch:

main

Product:

  • DiscordKitBot

For more detailed instructions, refer to this page in the DiscordKit guide.

Example Usage

Create a simple bot with a /ping command:

import DiscordKitBot

let bot = Client(intents: .unprivileged)

// Guild to register commands in. If the COMMAND_GUILD_ID environment variable is set, commands are scoped
// to that server and update instantly, useful for debugging. Otherwise, they are registered globally.
let commandGuildID = ProcessInfo.processInfo.environment["COMMAND_GUILD_ID"]

bot.ready.listen {
    print("Logged in as \(bot.user!.username)#\(bot.user!.discriminator)!")

    try? await bot.registerApplicationCommands(guild: commandGuildID) {
        NewAppCommand("ping", description: "Ping me!") { interaction in
            try? await interaction.reply("Pong!")
        }
    }
}

bot.login() // Reads the bot token from the DISCORD_TOKEN environment variable and logs in with the token

// Run the main RunLoop to prevent the program from exiting
RunLoop.main.run()

(Yes, that's really the whole code, no messing with registering commands with the REST API or anything!)

Not sure what to do next? Check out the guide below, which walks you through all the steps to create your own Discord bot!

Resources

Here are some (WIP) resources that might be useful while developing with DiscordKit.

Platform Support

Currently, DiscordKit only offically supports macOS versions 11 and up. Theoretically, you should be able to compile and use DiscordKit on any Apple platform with equivalent APIs, however this has not been tested and is considered an unsupported setup.

DiscordKitBot and DiscordKitCore is supported on Linux, but not DiscordKit itself. However, you are able to develop and host bots made with DiscordKit on Linux.

Windows is not supported natively at the moment. The recommended method is to use Windows Subsystem for Linux to do any development/hosting of DiscordKit bots on Windows. Native support may come in the future.

discordkit's People

Contributors

aloisius avatar candygoblen123 avatar charxene avatar cryptoalgorithm avatar floofyplasma avatar helloyunho avatar im-fran avatar sjmarf avatar tonyarnold avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

discordkit's Issues

Is this project active?

I was considering whether to continue learning Swift or learn Go, C or other languages and since I mainly deal with Discord and Minecraft I wanted to know if this project was active to understand if one day there will be a Swift API for Discord

DiscordKit for Bots - Continuation

Original PR: #18

Bot support was a tough one to tackle, and laid idle in another branch with low visibility while I was allocating my contribution time to other projects. I can't wait to bring the first Swift Discord library with slash command support (and now the only maintained one), so I'm moving the ever-growing bucket list to this long-running issue :D

Bucket List

  • Bot gateway identification with intents support
  • Correct user agent, properties and REST authentication
  • Sending basic messages
  • Event dispatching with NotificationCenter for message
    create and ready events
  • Application command registration with a resultBuilder - supported application command types:
    • chatInput - Slash commands
    • user - Actions that appear in context menu of users
    • message - Actions that appear in context menu of messages
  • Adding options to commands in the resultBuilder - supported types:
    • subCommand - A "sub-command" with no options
    • subCommandGroup - A group for nesting other options
    • string - An option accepting a String value
    • integer - An option accepting an Int value
    • boolean - An option accepting a Bool value
    • user - An option accepting a user as its value
    • channel - An option accepting a channel as its value
    • role - An option accepting a role as its value
    • mentionable - An option accepting a @mention as its value
    • number - An option accepting a Double value
    • attachment - An option accepting a file attachment as its value
  • Message components - supported types:
    • Button
    • Action row
    • Select Menu
    • Text Input
    • Modals
      • Text Input
  • Handling interactions with a closure, allowing responses
  • Support more types of interaction responses
    • Plain content responses
    • Ephemeral responses
    • Deferred responses
    • Embeds
      • Construct fields with a resultBuilder

Zlib compressed data header is not always stripped

The zlib header is currently only stripped for default level compression (0x78 0x9C). When I try logging in however, I'm getting a response back with a header of (0x78 0xDA) which is best compression level. This causes the header not to be stripped and decompression silently fails resulting in whatever garbage was in memory then being sent to the JSON decoder.

I'm running this from swiftcord. From DecompressionEngine decompress(_ data: Data) -> Data:

lldb> e data.map { String(format: "%02x ", $0) }.joined()
(String) $R1 = "78 da 34 c9 41 0a 83 30 10 05 d0 bb fc 75 52 92 52 29 cc 55 8c c8 34 0e 55 48 a3 24 a3 a5 48 ee de 6e ba 7b f0 4e 28 28 ef 29 19 d4 3f d6 0d e4 9d c1 04 3a 31 0b 17 7d 08 eb b8 64 95 72 70 02 dd fc b5 fb fd a8 85 a3 80 7a f4 01 4f 56 79 f3 c7 6e 65 b2 7b b5 c2 55 bd 8d f6 9e bb 39 c0 9c 01 af 25 96 b5 06 90 bb b8 36 60 68 ed 0b 00 00 ff ff "

After I strip off the two byte header when the first two bytes == 0x78 0xda, decoding gives me the proper response:

lldb> e String(decoding: decompressed, as: UTF8.self)
$R24: String = "{\"t\":null,\"s\":null,\"op\":10,\"d\":{\"heartbeat_interval\":41250,\"_trace\":[\"[\\\"gateway-prd-us-east1-c-7n5h\\\",{\\\"micros\\\":0.0}]\"]}}"

Unexpected Discord Gateway Disconnection

2023-09-03T18:19:06+0200 info RobustWebSocket : version=10 ws=wss://gateway.discord.gg/?v=10&encoding=json&compress=zlib-stream [DiscordKitCore] [CONNECT]
2023-09-03T18:19:06+0200 debug RobustWebSocket : reason=Hello payload received [DiscordKitCore] Invalidating conn timeout
2023-09-03T18:19:06+0200 info RobustWebSocket : heartbeat_interval=41250 [DiscordKitCore] [HELLO]
2023-09-03T18:19:06+0200 debug RobustWebSocket : interval=41.25 [DiscordKitCore] Start heartbeating
2023-09-03T18:19:06+0200 info RobustWebSocket : intents=Optional(DiscordKitCore.Intents(rawValue: 1146621)) [DiscordKitCore] [IDENTIFY]
2023-09-03T18:19:06+0200 trace RobustWebSocket : data=nil opcode=identify seq=-1 [DiscordKitCore] Outgoing Payload
2023-09-03T18:19:06+0200 info RobustWebSocket : session=81fcfab4f5f71a93df4ed8aee4442226 [DiscordKitCore] [READY]
2023-09-03T18:19:06+0200 info Client : application.id=1147885099979919514 user.id=1147885099979919514 [DiscordKitBot] Bot client ready
Registering interactions...
2023-09-03T18:19:06+0200 trace DiscordREST : method=put path=applications/1147885099979919514/guilds/840575490238840843/commands [DiscordKitCore] Making request
Registered interactions!
Successfully logged in as swifttest#1500!
2023-09-03T18:19:41+0200 debug RobustWebSocket : [DiscordKitCore] [HEARTBEAT] Sending heartbeat
2023-09-03T18:19:41+0200 trace RobustWebSocket : data=Optional(DiscordKitCore.GatewayHeartbeat(seq: Optional(1))) opcode=heartbeat seq=1 [DiscordKitCore] Outgoing Payload
2023-09-03T18:19:41+0200 error RobustWebSocket : error=disconnected [DiscordKitCore] Receive error
2023-09-03T18:19:41+0200 warning RobustWebSocket : [DiscordKitCore] Forcibly closing connection
2023-09-03T18:19:51+0200 warning RobustWebSocket : reason=socket timed out [DiscordKitCore] [HEARTBEAT] Force-closing connection
2023-09-03T18:19:51+0200 warning RobustWebSocket : [DiscordKitCore] Forcibly closing connection

License

Hi,
Thanks for releasing this library! Would you mind adding a license, ie MIT or ISC?
Thank you!

Decoding JSON is Corrupted

2023-11-30T21:57:49-0800 info RobustWebSocket : version=10 ws=wss://gateway.discord.gg/?v=10&encoding=json&compress=zlib-stream [DiscordKitCore] [CONNECT]
2023-11-30T21:57:49-0800 debug RobustWebSocket : reason=connection is reachable [DiscordKitCore] Reset backoff
2023-11-30T21:57:49-0800 warning RobustWebSocket : [DiscordKitCore] Reconnection in progress, not reconnecting
2023-11-30T21:57:49-0800 info RobustWebSocket : [DiscordKitCore] [CONNECTED]
2023-11-30T21:57:49-0800 trace DecompressionEngine : decompressed.count=109 original.count=114 [DiscordKitCore] Decompressed data
2023-11-30T21:57:49-0800 warning RobustWebSocket : error=dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Unexpected character 'ï' around line 2, column 1." UserInfo={NSJSONSerializationErrorIndex=1, NSDebugDescription=Unexpected character 'ï' around line 2, column 1.}))) [DiscordKitCore] Error decoding message
2023-11-30T21:57:53-0800 warning RobustWebSocket : timeout=4.0 [DiscordKitCore] Connection timed out
2023-11-30T21:57:53-0800 warning RobustWebSocket : [DiscordKitCore] Forcibly closing connection
2023-11-30T21:57:53-0800 info RobustWebSocket : [DiscordKitCore] [RECONNECT] Preemptively attempting reconnection
2023-11-30T21:57:53-0800 info RobustWebSocket : attempt=1 connectIn=3.8000000000000003 [DiscordKitCore] Retrying connection
2023-11-30T21:57:53-0800 warning RobustWebSocket : [DiscordKitCore] Already reconnecting, not reconnecting
2023-11-30T21:57:53-0800 warning RobustWebSocket : [DiscordKitCore] [WS CLOSED] closeCode: 1006
2023-11-30T21:57:53-0800 error RobustWebSocket : [DiscordKitCore] [WS CLOSED] closed with error: no error description
2023-11-30T21:57:53-0800 warning RobustWebSocket : [DiscordKitCore] Already reconnecting, not reconnecting
2023-11-30T21:57:53-0800 error RobustWebSocket : error=The operation couldn’t be completed. Socket is not connected [DiscordKitCore] Receive error
2023-11-30T21:57:53-0800 warning RobustWebSocket : [DiscordKitCore] Forcibly closing connection```

Can't add DiscordKit

I'm following: https://swiftcord.gitbook.io/discordkit-guide/getting-started/creating-a-project/creating-a-bot-using-a-spm-project-recommended

Package.swift

// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "bot",
    dependencies: [
        .package(url: "https://github.com/SwiftcordApp/DiscordKit", branch: "main")
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products from dependencies.
        .executableTarget(
            name: "bot",
            dependencies: [
                .product(name: "DiscordKitBot", package: "DiscordKitBot")
            ],
            path: "Sources"
        ),
    ]
)
x-xcode-log://4CB20058-71E5-4643-891E-FF22F232FDF0 unknown package 'DiscordKitBot' in dependencies of target 'bot'; valid packages are: 'DiscordKit' (from 'https://github.com/SwiftcordApp/DiscordKit')
/Users/evrensen/Developer/AppleDiscord/bot/Sources/main.swift:1:8 Compiling for macOS 10.13, but module 'DiscordKit' has a minimum deployment target of macOS 11.0: /Users/evrensen/Library/Developer/Xcode/DerivedData/bot-gxezfrehrcvywzfmgvthqndfyqni/Index.noindex/Build/Products/Debug/DiscordKit.swiftmodule/arm64-apple-macos.swiftmodule

Support providing an image in bot embeds

Bot responses embedding images is quite a common and useful feature. By adding this feature, developers can have access to a more complete range of features offered by bot embeds.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.