Packages

A simple Gleam library for sending Discord webhook.

Current section

Files

Jump to
discord_webhook src discord_webhook.gleam
Raw

src/discord_webhook.gleam

import gleam/http
import gleam/http/request
import gleam/httpc
import gleam/int
import gleam/io
import gleam/json
// Main webhook object
pub opaque type Webhook {
Webhook(url: String)
}
// Message type
type Message {
Message(content: String)
}
// .new() function to declare a webhook
pub fn new(url: String) -> Webhook {
Webhook(url: url)
}
// Private helper to convert Message type into raw JSON text format
fn convert_json(message: Message) -> String {
json.object([#("content", json.string(message.content))])
|> json.to_string
}
// .send() function to send the webhook
pub fn send(webhook: Webhook, content: String) -> Nil {
let message_data = Message(content: content)
let json_payload = convert_json(message_data)
case request.to(webhook.url) {
Error(_) -> io.println("Failed to parse webhook URL.")
Ok(base_req) -> {
let req =
base_req
|> request.set_method(http.Post)
|> request.set_header("content-type", "application/json")
|> request.set_body(json_payload)
case httpc.send(req) {
Ok(response) ->
io.println("Response Status: " <> int.to_string(response.status))
Error(_) ->
io.println("Failed to fire HTTP request entirely.")
}
}
}
}