remove DiscordBM dependency

This commit is contained in:
2026-03-17 06:33:26 -04:00
parent c6b92d968a
commit 29a2b0370b
9 changed files with 361 additions and 370 deletions

View File

@@ -11,9 +11,7 @@ public struct Bot {
let gatewayURL = try await client.getGatewayURL()
print(gatewayURL.absoluteURL)
let gateway = GatewayClient(gatewayURL: gatewayURL)
try await gateway.openConnection()
}
}

View File

@@ -3,40 +3,30 @@ import Foundation
import FoundationNetworking
#endif
struct GatewayClient {
let gatewayURL: URL
class GatewayClient {
let ws: URLSessionWebSocketTask
var sequenceNum: Int? = nil
init(gatewayURL: URL) {
self.gatewayURL = gatewayURL
ws = URLSession.shared.webSocketTask(with: gatewayURL.appending(component: "?v=10&encoding=json"))
}
func openConnection() {
listen()
func openConnection() async throws {
ws.resume()
RunLoop.current.run()
guard case .hello(let helloMessage) = try await getMessage().d else { throw GatewayError.mismatchedOpcode }
dump(helloMessage)
Timer.scheduledTimer(withTimeInterval: (helloMessage.heartbeat_interval / 1000.0), repeats: true) {
}
}
func listen() {
ws.receive { result in
defer { listen() }
do {
if case .failure(let err) = result { throw err }
guard case .success(let message) = result else { return }
guard case .string(let str) = message else { throw GatewayError.invalidMessage }
let json = JSONDecoder()
let gwMessage = try json.decode(GatewayMessage.self, from: Data(str.utf8))
switch gwMessage.d {
case .hello(let hello):
dump(hello)
case .none:
return
}
} catch {
print(error)
}
}
func getMessage() async throws -> GatewayMessage {
let wsMessage = try await ws.receive()
guard case .string(let str) = wsMessage else { throw GatewayError.invalidMessage }
let json = JSONDecoder()
let gwMessage = try json.decode(GatewayMessage.self, from: Data(str.utf8))
sequenceNum = gwMessage.s ?? sequenceNum
return gwMessage
}
}
@@ -44,4 +34,5 @@ struct GatewayClient {
public enum GatewayError: Error {
case invalidMessage
case invalidOpcode
case mismatchedOpcode
}

View File

@@ -23,6 +23,8 @@ public enum GatewayPayload: Decodable {
public struct GatewayMessage: Decodable {
let op: Int
let d: GatewayPayload?
let s: Int?
let t: String?
enum CodingKeys: String, CodingKey {
case t
@@ -34,6 +36,8 @@ public struct GatewayMessage: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
op = try container.decode(Int.self, forKey: .op)
s = try container.decode(Int?.self, forKey: .s)
t = try container.decode(String?.self, forKey: .t)
switch op {
case 10:
let hello = try container.decode(HelloPayload.self, forKey: .d)