krisppurg / dimscord

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

better syntax for api requests and helping procs #112

Closed nayr7 closed 1 year ago

nayr7 commented 1 year ago

(this issue is made in order to track https://github.com/krisppurg/dimscord/pull/101 and https://github.com/krisppurg/dimscord/pull/113 more easily)

statu quo

Currently, interacting with the discord api is done "the verbose way":

proc messageCreate(s: Shard, m: Message) {.event(discord).} =
    if m.author.bot: return
    if m.content == "!ping": 
        let
            before = epochTime() * 1000
            msg = await discord.api.sendMessage(m.channel_id, "ping?")
            after = epochTime() * 1000
        discard await discord.api.editMessage(
            m.channel_id,
            msg.id, 
            "Pong! took " & $int(after - before) & "ms | " & $s.latency() & "ms."
        )

For example, it can quickly becomes tedious to write sendMessage or editMessage all over again and the majority of the procs currently in the library that interact with the api similarly suffer from this as well. The library also lacks helpful procs like defer when handling Interaction events for example that are present in other libraries and relies on building long objects to achieve it instead.

solution

A new syntax that would abstract the above code would look like this:

 proc messageCreate(s: Shard, m: Message) {.event(discord).} =
    if m.author.bot: return
    if m.content == "!ping": 
        let
            before = epochTime() * 1000
            msg = await m.reply("ping?")
            after = epochTime() * 1000
        discard await m.edit("Pong! took " & $int(after - before) & "ms | " & $s.latency() & "ms.")

The disappearing discord may introduce some challenge to solve this issue since we need RestApi information, hence a potential compromise would be:

 proc messageCreate(s: Shard, m: Message) {.event(discord).} =
    let ctx = s.client.api # or let ctx = discord.api
    if m.author.bot: return
    if m.content == "!ping": 
        let
            before = epochTime() * 1000
            msg = await m.reply(ctx, "ping?")
            after = epochTime() * 1000
        discard await m.edit(ctx, "Pong! took " & $int(after - before) & "ms | " & $s.latency() & "ms.")