Send an SMS with Thinwrap (Gleam)

Send an SMS via thinwrap_notifications's send_sms/2 in Gleam — one call shape for Twilio, Vonage, MessageBird and every other provider.

1. Install

gleam add thinwrap_notifications gleam_erlang envoy

2. Send the call

import envoy
import gleam/dynamic.{type Dynamic}
import gleam/dynamic/decode
import gleam/erlang/atom
import gleam/io
import gleam/list

@external(erlang, "thinwrap_notifications", "send_sms")
fn send_sms(config: Dynamic, input: Dynamic) -> Result(Dynamic, Dynamic)

pub fn main() -> Nil {
  let assert Ok(sid) = envoy.get("TWILIO_ACCOUNT_SID")
  let assert Ok(auth_token) = envoy.get("TWILIO_AUTH_TOKEN")
  let config =
    obj([
      #("provider", atom("twilio")),
      #("account_sid", dynamic.string(sid)),
      #("auth_token", dynamic.string(auth_token)),
      #("from", dynamic.string("+15551112222")),
    ])
  let input =
    obj([
      #("to", dynamic.string("+15552223333")),
      #("body", dynamic.string("Hello from Thinwrap")),
    ])

  case send_sms(config, input) {
    Ok(res) -> {
      let sent = {
        use status <- decode.field(key("status"), atom.decoder())
        use id <- decode.field(key("provider_message_id"), decode.string)
        decode.success(atom.to_string(status) <> " " <> id)
      }
      let assert Ok(line) = decode.run(res, sent)
      io.println(line)
    }
    Error(err) -> io.println(describe(err))
  }
}

// The library speaks atom-keyed Erlang maps; these helpers build and read them.
fn key(name: String) -> atom.Atom {
  atom.create(name)
}

fn atom(name: String) -> Dynamic {
  atom.to_dynamic(atom.create(name))
}

fn obj(fields: List(#(String, Dynamic))) -> Dynamic {
  dynamic.properties(list.map(fields, fn(f) { #(atom(f.0), f.1) }))
}

fn describe(err: Dynamic) -> String {
  let error = {
    use code <- decode.field(key("code"), atom.decoder())
    use message <- decode.field(key("message"), decode.string)
    decode.success(atom.to_string(code) <> ": " <> message)
  }
  let assert Ok(line) = decode.run(err, error)
  line
}

Same code works for all supported providers — just change the provider ID.