This repository has been archived on 2023-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
nimcord/src/eventdispatcher.nim

49 lines
2.3 KiB
Nim
Raw Normal View History

2020-06-18 03:19:13 +00:00
import eventhandler, json, tables, message, user, nimcordutils, httpClient, strformat, cache, guild, sequtils, asyncdispatch, clientobjects
2020-05-30 04:59:23 +00:00
2020-06-18 03:19:13 +00:00
proc readyEvent(discordClient: DiscordClient, json: JsonNode) =
var readyEvent = ReadyEvent(client: discordClient, readyPayload: json, name: $EventType.evtReady)
# Get client user
var client = newHttpClient()
# Add headers
client.headers = newHttpHeaders({"Authorization": fmt("Bot {discordClient.token}"),
"User-Agent": "NimCord (https://github.com/SeanOMik/nimcord, v0.0.0)",
"X-RateLimit-Precision": "millisecond"})
echo "Sending GET request, URL: body: {}"
waitForRateLimits(0, RateLimitBucketType.global)
var json = handleResponse(client.request(endpoint("/users/@me"), HttpGet, ""), 0, RateLimitBucketType.global)
let clientUser: User = newUser(json)
readyEvent.clientUser = clientUser
2020-05-30 04:59:23 +00:00
dispatchEvent(readyEvent)
2020-06-18 03:19:13 +00:00
proc messageCreateEvent(discordClient: DiscordClient, json: JsonNode) =
2020-05-31 05:09:30 +00:00
let msg = newMessage(json)
2020-06-18 03:19:13 +00:00
let messageCreateEvnt = MessageCreateEvent(client: discordClient, message: msg, name: $EventType.evtMessageCreate)
2020-05-31 05:09:30 +00:00
dispatchEvent(messageCreateEvnt)
2020-06-18 03:19:13 +00:00
proc guildCreateEvent(discordClient: DiscordClient, json: JsonNode) =
let g = newGuild(json)
let guildCreateEvnt = GuildCreateEvent(client: discordClient, guild: g, name: $EventType.evtGuildCreate)
discordClient.cache.guilds.insert(g)
discordClient.cache.channels = concat(discordClient.cache.channels, g.channels)
discordClient.cache.members = concat(discordClient.cache.members, g.members)
dispatchEvent(guildCreateEvnt)
let internalEventTable: Table[string, proc(discordClient: DiscordClient, json: JsonNode) {.nimcall.}] = {
2020-05-31 05:09:30 +00:00
"READY": readyEvent,
2020-06-18 03:19:13 +00:00
"MESSAGE_CREATE": messageCreateEvent,
"GUILD_CREATE": guildCreateEvent
2020-05-30 04:59:23 +00:00
}.toTable
2020-06-18 03:19:13 +00:00
proc handleDiscordEvent*(discordClient: DiscordClient, json: JsonNode, eventName: string) {.async.} =
## Handles, and dispatches, a gateway event. Only used internally.
2020-05-30 04:59:23 +00:00
if (internalEventTable.hasKey(eventName)):
2020-06-18 03:19:13 +00:00
let eventProc: proc(discordClient: DiscordClient, json: JsonNode) = internalEventTable[eventName]
eventProc(discordClient, json)
2020-05-30 04:59:23 +00:00
else:
2020-06-18 03:19:13 +00:00
echo "Failed to find event: ", eventName