grottohub / glyph

A purely Gleam Discord library built from the ground up with stratus.
24 stars 4 forks source link

finish defining `Message` and related models for `MESSAGE_CREATE` events #4

Open grottohub opened 3 months ago

grottohub commented 3 months ago

when a bot has either the GuildMessages or DirectMessages intent, the gateway will send a MESSAGE_CREATE event for us to consume. right now we extract some basic data from the event, but not all of it.

this one is a bit of a doozy, because it can contain so many nested objects that should also be transformed into models. take this one on only if you're very comfortable with dynamic decoding and understand what's going on in decoders.gleam.

see the Discord docs for the event and the message

dixtel commented 3 months ago

I will take this one

grottohub commented 3 months ago

awesome, feel free to ask any questions!

dixtel commented 3 months ago

@grottohub

what do you think about creating a simple package that will generate json decoders? I see that these code is repeated all over the place:


type MessageDecoder(message) =
  fn(Dynamic) -> Result(message, DecodeErrors)

fn message(
  constructor: fn(
    // ... rest
  ) ->
    discord.Message,
  // ... rest
) -> MessageDecoder(discord.Message) {
  fn(message: Dynamic) {
    case
      // fields
    {
      Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f), Ok(g), Ok(h) ->
        Ok(constructor(a, b, c, d, e, f, g, h))
      a, b, c, d, e, f, g, h ->
        // error handling ...
    }
  }
}

pub fn message_decoder(dyn: Dynamic) -> Result(discord.Message, DecodeErrors) {
  message(
    discord.Message,
    // fields ...
  )(dyn)
}

Do you want add some auto-generated code to the codebase or you want do it dead simple?

grottohub commented 3 months ago

the main reason ive been doing it manually is because gleam doesn't have codegen - i think ive heard a few people mention someone working on something for generating decoders as an external CLI, but haven't really cared enough to go searching for one since copy/paste/edit is fast enough for my workflow. it wouldn't necessarily be a gleam package because, as mentioned, gleam doesn't have codegen - so that code wouldn't be part of this codebase or even a dev dependency.

if you're interested in making something like that, go for it! i just don't view it as a necessity, so personally i would not prioritize writing something like that myself - i.e. if it gets the point where i want to release v0.3, i would probably just make the decoders myself :)