Low-level Discord REST client shared by every module: request building (auth, User-Agent, audit-log reason, JSON or multipart bodies), body and query helpers that never send unset fields, and error handling that surfaces Discord's rate-limit retry_after.

Per-call credentials. Every API-calling function in this package takes an optional trailing opts Map, resolved by resolve: opts first, then the discord.bot.token context variable. Nothing from opts is written to ctx, so one run can act as many bots and parallel flows don't share credentials. A token from opts is masked in call records. A token present but blank or null is an error, never a fallback to discord.bot.token.

  • token: the bot token for this call

Webhook-token and interaction-token routes authenticate with the token in their path and never send a bot token, so they ignore a token in opts. The tokens in their paths are masked in call records too.

Context Vars

Optional
  • discord.bot.token

Values

CONTROL_KEYS

CONTROL_KEYS: Vec [
  "reason",
  "clear",
  "files"
]

Functions

attachments-for

fn (files: Vec<Map>): Vec<Map>

The attachments array describing files by index ({id, filename, description?}), for payload_json.

Example

::discord::api/attachments-for([{filename: "a.png", description: "Logo"}, {filename: "b.txt"}])
// [{id: 0, filename: "a.png", description: "Logo"}, {id: 1, filename: "b.txt"}]

auth-headers

fn (options: Map): Map

The Authorization header for a call's options. With auth: false it's always {}: a token there is still checked and masked, but never sent. An Err when resolve has no usable token.

Example

headers ::discord::api/auth-headers({token: ::hot::ctx/get("discord.bot.token")})
headers.Authorization

// Token-in-path routes send no Authorization header
::discord::api/auth-headers({auth: false})

body

fn (request: Any, path-keys: Vec<Str>): Map

Build a JSON body from a request record. Drops the path parameters named in path-keys, the control fields (reason, clear, files), and every unset or null field: Discord reads JSON null as "clear this field", so an unset optional must never be sent.

To clear a field on purpose, list it in the request's clear field: clear: ["nick"] sends "nick": null and wins over a value set for the same field.

Example

::discord::api/body({guild_id: "1", user_id: "2", nick: "Ada", roles: null}, ["guild_id", "user_id"])
// => {nick: "Ada"}

::discord::api/body({guild_id: "1", clear: ["communication_disabled_until"]}, ["guild_id"])
// => {communication_disabled_until: null}

build-request

fn (method: Str, path: Str, options: Map): ::hot::http/HttpRequest

Build (without sending) the HttpRequest for method and path (relative to the API base URL). options:

  • query: Map of query params; null entries are dropped
  • body: JSON body (sent as payload_json when files is set)
  • files: Vec of FileUpload; switches to multipart/form-data
  • form: {fields, file_field, file} for plain multipart forms (no payload_json)
  • reason: audit-log reason, sent as X-Audit-Log-Reason
  • auth: false for webhook-token and interaction routes, which take no bot token
  • token: explicit bot token instead of discord.bot.token
  • boundary: fixed multipart boundary (tests)

Returns an Err when the call has no usable bot token.

Example

req ::discord::api/build-request("GET", "/users/@me/guilds", {query: {limit: 10, after: null}, token: "test"})
req.url  // => "https://discord.com/api/v10/users/@me/guilds?limit=10"

call

fn (method: Str, path: Str): Any
fn (method: Str, path: Str, options: Map): Any
fn (method: Str, path: Str, options: Map, opts: Map): Any

Send a request built by build-request and return the parsed body (null for 204), or an Err(HttpError) for non-2xx responses. The last argument is per-call opts (see resolve).

Example

me ::discord::api/call("GET", "/users/@me")
guilds ::discord::api/call("GET", "/users/@me/guilds", {query: {limit: 50}})
other ::discord::api/call("GET", "/users/@me", {}, {token: "tenant-b-bot-token"})

call-ok

fn (method: Str, path: Str): Bool
fn (method: Str, path: Str, options: Map): Bool
fn (method: Str, path: Str, options: Map, opts: Map): Bool

Like call, but returns true on success. For endpoints that answer 204 No Content.

Example

::discord::api/call-ok("POST", "/channels/1100000000000000000/typing")

// With an audit-log reason and a per-call token
::discord::api/call-ok("DELETE", "/channels/1100000000000000000", {reason: "Cleanup"}, {token: ::hot::ctx/get("tenant-b.discord.bot.token")})

emoji-segment

fn (emoji: Str): Str

Encode a reaction emoji for the URL path. Pass a Unicode emoji as is ("👍") or a custom emoji as name:id; already-encoded input ("%F0%9F%91%8D") is passed through unchanged.

Example

::discord::api/emoji-segment("👍")  // "%F0%9F%91%8D"
::discord::api/emoji-segment("%F0%9F%91%8D")  // "%F0%9F%91%8D"

is-rate-limited

fn (error: Any): Bool

True when error is a Discord 429. Wait error.retry_after seconds before retrying.

Example

::discord::api/is-rate-limited({status: 429, retry_after: 1.5})  // true
::discord::api/is-rate-limited({status: 404})  // false

multipart-body

fn (payload: Map, files: Vec<Map>, boundary: Str): Bytes

Build a Discord multipart/form-data body: the JSON payload as payload_json, then each file as files[n]. Built as Bytes so binary content survives. Exposed for testing; endpoints that take files use it.

Example

body ::discord::api/multipart-body({content: "hi"}, [{filename: "a.txt", content: "x"}], "boundary")
text Str(body)
contains(text, "name=\"payload_json\"")  // true
contains(text, "name=\"files[0]\"; filename=\"a.txt\"")  // true

multipart-form

fn (fields: Map, file-field: Str, file: Map, boundary: Str): Bytes

Build a plain multipart/form-data body: one text part per non-null entry of fields, then file under the part name file-field. Used by endpoints that take form fields instead of payload_json (sticker upload).

Example

body ::discord::api/multipart-form({name: "shipit", tags: "rocket"}, "file", {filename: "a.png", content: "x"}, "boundary")
text Str(body)
contains(text, "name=\"tags\"")  // true
contains(text, "name=\"file\"; filename=\"a.png\"")  // true

paginate

fn (fetch: Fn, next-cursor: Fn, page-size: Int, max-items: Int): Vec

Collect cursor pages until a short page or max-items. fetch takes the cursor (null first) and returns one page (Vec); next-cursor takes that page and returns the next cursor. A failed page comes back as its Err. The module helpers (::discord::guilds/list-all-guild-members, ::discord::messages/get-message-history, ...) are built on it.

Example

guilds ::discord::api/paginate(
  (after) { ::discord::api/call("GET", "/users/@me/guilds", {query: {limit: 200, after: after}}) },
  (page) { last(page).id },
  200,
  1000
)

query

fn (params: Map): Str

Build a ?a=1&b=2 query suffix from the non-null entries of params (URL-encoded); "" when none are set.

Example

::discord::api/query({limit: 10, after: null})  // "?limit=10"
::discord::api/query({after: null})  // ""

reason-headers

fn (reason: Any): Map

{X-Audit-Log-Reason: ...} (URL-encoded, as Discord requires) when reason is set, otherwise {}.

Example

::discord::api/reason-headers("Spam wave")  // {X-Audit-Log-Reason: "Spam%20wave"}
::discord::api/reason-headers(null)  // {}

request

fn (method: Str, url: Str): ::hot::http/HttpResponse
fn (method: Str, url: Str, additional-headers: Map): ::hot::http/HttpResponse
fn (method: Str, url: Str, additional-headers: Map, body: Any): ::hot::http/HttpResponse
fn (method: Str, url: Str, additional-headers: Map, body: Any, token: Str): ::hot::http/HttpResponse
fn (method: Str, url: Str, additional-headers: Map, body: Any, opts: Map): ::hot::http/HttpResponse

Make an authenticated request to an absolute Discord API URL and return the raw HttpResponse. Adds the bot token (from per-call opts, or discord.bot.token unless passed) and the User-Agent; Map/Vec bodies are sent as JSON and Bytes bodies as is (set Content-Type yourself). Prefer call for new code.

Example

::api ::discord::api

response ::api/request("GET", "https://discord.com/api/v10/users/@me")
response ::api/request("POST", "https://discord.com/api/v10/channels/123/messages", {}, {content: "Hello"})
response ::api/request("GET", "https://discord.com/api/v10/users/@me", {}, "", "my-bot-token")
response ::api/request("GET", "https://discord.com/api/v10/users/@me", {}, "", {token: "my-bot-token"})

resolve

fn (opts: Map): Map

The bot token for one call (see resolve-from). A token from opts is masked in call records with ::hot::ctx/mark-secret, and opts values are never written to ctx.

Example

::discord::api/resolve({token: "tenant-b-bot-token"}).token
Context Vars: discord.bot.token

resolve-from

fn (opts: Map, ctx-values: Map): Map

The one resolver, pure: {token} for a call from opts first, then ctx-values (a Map of context variables). An Err when no token is set, or when token is in opts but blank or null (that never falls back to context). Exposed for testing; resolve feeds it the context.

Example

::discord::api/resolve-from({}, {"discord.bot.token": "from-ctx"})  // {token: "from-ctx"}
::discord::api/resolve-from({token: "from-opts"}, {"discord.bot.token": "from-ctx"})  // {token: "from-opts"}

// A blank token in opts never falls back to context
is-err(::discord::api/resolve-from({token: ""}, {"discord.bot.token": "from-ctx"}))  // true

seg

fn (value: Any): Str

URL-encode one path segment (ids, emoji). Use token-seg for tokens.

Example

::discord::api/seg("a b")  // "a%20b"
::discord::api/seg(123)  // "123"

send

fn (method: Str, path: Str, options: Map, opts: Map, finish: Fn): Any

Build and send a call, then return finish of the response. opts is the caller's per-call credentials. An Err from building or from the transport comes back as is.

Example

// Package internals: prefer call or call-ok
::discord::api/send("GET", "/users/@me", {}, {}, ::discord::api/to-result)

to-ok

fn (response: Result): Bool

Return true for a 2xx response, otherwise an Err(HttpError). Used by endpoints that return 204 No Content.

Example

::discord::api/to-ok(::hot::http/HttpResponse({status: 204, headers: {}, body: ""}))  // true
is-err(::discord::api/to-ok(::hot::http/HttpResponse({status: 403, headers: {}, body: {code: 50013}})))  // true

to-result

fn (response: Result): Any

Return the response body for a 2xx (null for 204 No Content), otherwise an Err(HttpError). Exposed for testing; every endpoint uses it.

Example

::discord::api/to-result(::hot::http/HttpResponse({status: 200, headers: {}, body: {id: "1"}}))  // {id: "1"}
::discord::api/to-result(::hot::http/HttpResponse({status: 204, headers: {}, body: ""}))  // null

// A 429 carries the wait in retry_after
limited ::discord::api/to-result(::hot::http/HttpResponse({status: 429, headers: {}, body: {retry_after: 1.5, global: false}}))
if-err(limited, (e) { e.retry_after })  // 1.5

token-seg

fn (token: Str): Str

URL-encode a webhook or interaction token for the path, and mask it in call records first. These routes carry their credential in the URL.

Example

::discord::api/token-seg("abc/def")  // "abc%2Fdef"

Types

FileUpload

FileUpload type {
    filename: Str,
    content: Bytes | Str,
    content_type: Str?,
    description: Str?
}

A file to attach. content is the raw file (Bytes, e.g. from ::hot::file/read-file-bytes, or text). content_type defaults from the filename's extension. description becomes the attachment's alt text.

HttpError

HttpError type {
    status: Int,
    headers: Map,
    body: Any,
    retry_after: Dec?,
    global: Bool?,
    scope: Str?
}

A non-2xx Discord response. body is Discord's JSON error ({code, message, errors?}). On HTTP 429, retry_after holds the seconds to wait (from the body's retry_after, falling back to the Retry-After header), global says whether the global limit was hit, and scope is X-RateLimit-Scope (user, global or shared).

Example

result ::discord::messages/create-message(::discord::messages/CreateMessageRequest({
  channel_id: "1100000000000000000",
  content: "hi"
}))
if-err(result, (e) {
  if(::discord::api/is-rate-limited(e), `retry in ${e.retry_after}s`, e.body.message)
})