From e87241d7a610dac11d8d4fdab5585ad1918235e5 Mon Sep 17 00:00:00 2001 From: SeanOMik Date: Thu, 28 May 2020 00:50:53 -0500 Subject: [PATCH] Get the client connected but nothing else. --- nimcord.nimble | 10 +++++++++ src/client.nim | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 nimcord.nimble create mode 100644 src/client.nim diff --git a/nimcord.nimble b/nimcord.nimble new file mode 100644 index 0000000..6331425 --- /dev/null +++ b/nimcord.nimble @@ -0,0 +1,10 @@ +# Package + +version = "0.0.0" +author = "SeanOMik, Intexisty" +description = "Discord API wrapper written in nim. Inspired by discord.py" +license = "MIT" + +# Dependencies + +requires "nim >= 1.0.4", "websocket >= 0.4.1" \ No newline at end of file diff --git a/src/client.nim b/src/client.nim new file mode 100644 index 0000000..7f20e20 --- /dev/null +++ b/src/client.nim @@ -0,0 +1,60 @@ +import websocket, asyncnet, asyncdispatch, json, httpClient, strformat + +type + DiscordClient* = ref object ## Discord Client + token*: string + #user*: User + #cache: Cache + ws: AsyncWebSocket + httpClient: AsyncHttpClient + +#[ proc heartbeat() {.async.} = + while true: + await sleepAsync(35000) + echo "heartbeat now" ]# + +proc read(client: DiscordClient) {.async.} = + while true: + var packet: tuple[opcode: Opcode, data: string] + + packet = await client.ws.readData(); + echo "(opcode: ", packet.opcode, ", data: ", packet.data, ")" + + var json: JsonNode = parseJson(packet.data); + + case json["op"].num + of 10: + echo "Received 'HELLO' from the gateway." + # Start heartbeat here! + else: + discard + +proc Endpoint(url: string): string = + return fmt("https://discord.com/api/v6{url}") + +proc startConnection(client: DiscordClient) {.async.} = + client.httpClient = newAsyncHttpClient() + client.httpClient.headers = newHttpHeaders({"Authorization": fmt("Bot {client.token}")}) + + let result = parseJson(await client.httpClient.getContent(Endpoint("/gateway/bot"))) + echo "Got result: ", $result + + if (result.contains("url")): + let url = result["url"].getStr() + + client.ws = await newAsyncWebsocketClient(url[6..url.high], Port 443 , + path = "/v=6&encoding=json", true) + echo "Connected!" + + asyncCheck client.read() + #asyncCheck heartbeat() + runForever() + else: + var e: ref IOError + new(e) + e.msg = "Failed to get gateway url, token may of been incorrect!" + raise e + +var bot = DiscordClient(token: + "TOKEN") +waitFor bot.startConnection() \ No newline at end of file