From 947dc6884af486a89d52c29344a3f8e198d469e8 Mon Sep 17 00:00:00 2001 From: SeanOMik Date: Wed, 17 Jun 2020 22:18:22 -0500 Subject: [PATCH] Move some request things into nimcordutils --- src/nimcordutils.nim | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/nimcordutils.nim b/src/nimcordutils.nim index c1ec066..afd892e 100644 --- a/src/nimcordutils.nim +++ b/src/nimcordutils.nim @@ -6,9 +6,22 @@ proc getIDFromJson*(str: string): uint64 = discard parseBiggestUInt(str, num) return num +proc parseIntEasy*(str: string): int = + var num: int + discard parseInt(str, num) + return num + proc endpoint*(url: string): string = return fmt("https://discord.com/api/v6{url}") +var globalToken*: string + +proc defaultHeaders*(added: HttpHeaders = newHttpHeaders()): HttpHeaders = + added.add("Authorization", fmt("Bot {globalToken}")) + added.add("User-Agent", "NimCord (https://github.com/SeanOMik/nimcord, v0.0.0)") + added.add("X-RateLimit-Precision", "millisecond") + return added; + type RateLimitBucketType* = enum channel, @@ -94,4 +107,21 @@ proc waitForRateLimits*(objectID: snowflake, bucketType: RateLimitBucketType) = if (millisecondTime > 0): echo fmt("Rate limit wait time: {millisecondTime} miliseconds") - discard sleepAsync(millisecondTime) \ No newline at end of file + discard sleepAsync(millisecondTime) + +proc sendRequest*(endpoint: string, httpMethod: HttpMethod, headers: HttpHeaders, objectID: snowflake = 0, + bucketType: RateLimitBucketType = global, jsonBody: JsonNode = %*{}): JsonNode = + var client = newHttpClient() + # Add headers + client.headers = headers + + var strPayload: string + if ($jsonBody == "{}"): + strPayload = "" + else: + strPayload = $jsonBody + echo "Sending ", httpMethod, " request, URL: ", endpoint, ", body: ", strPayload + + waitForRateLimits(objectID, bucketType) + let response = client.request(endpoint, httpMethod, strPayload) + return handleResponse(response, objectId, bucketType) \ No newline at end of file