krisppurg / dimscord

A Discord Bot & REST Library for Nim.
https://krisppurg.github.io/dimscord/
MIT License
222 stars 22 forks source link

new `Context` type to allow shortening code #117

Closed nayr7 closed 10 months ago

nayr7 commented 11 months ago

This PR improves the library's API by allowing users to directly pass Shard or DiscordClient to procs that interact with Discord's Rest API. RestApi is part of Context in order to maintain compatibility with old code.

Before:

let discord = newDiscordClient("token")

var cmd = discord.newHandler() 

cmd.addSlash("ping", guildID = "0000000000000000000") do (s: Shard, i: Interaction):
    ## Ping the bot 
    let
        ch = s.cache.guildChannels[i.channel_id.get]

        before = epochTime() * 1000
        msg = await discord.api.sendMessage(ch.id, "Success!")
        after = epochTime() * 1000

    discard await discord.api.editMessage(ch.id, msg.id, "Pong! took " & $int(after - before) & "ms | " & $s.latency() & "ms.")

After:

 let discord = newDiscordClient("token")

var cmd = discord.newHandler() 

cmd.addSlash("ping", guildID = "0000000000000000000") do (s: Shard, i: Interaction):
    ## Ping the bot 
    let
        ch = s.cache.guildChannels[i.channel_id.get]

        before = epochTime() * 1000
        msg = await s.sendMessage(ch.id, "Success!")
        after = epochTime() * 1000

    discard await discord.editMessage(ch.id, msg.id, "Pong! took " & $int(after - before) & "ms | " & $s.latency() & "ms.")

Notice how I can pass discord or s variables directly. Users can call the discord variable anything they want so it could be ctx to match the name of the type in question (could also be demonstrated in documentation).

Note: This is a two-part PR, a followup PR is to be expected that would make use of this feature across the library.