Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

55.5 KB
Raw Blame
//! Discord REST client with 429 handling.

use crate::model::{Gif, GuildProfile, Id, Message, OutgoingMessage, ReactionEmoji, UploadData, User, UserProfile};
use crate::{guard, ratelimit, reqlog};
use anyhow::{anyhow, Result};
use reqwest::{Client, Method, StatusCode};
use serde_json::{json, Value};
use std::time::{Duration, Instant};

/// The API version Discord's web client speaks (`GLOBAL_ENV.API_VERSION`).
/// v10 also refuses some of its calls (ringing: "Missing Permissions").
pub const API_BASE: &str = "https://discord.com/api/v9";
/// Discord's answer when a file is over what this account may upload here.
const FILE_TOO_LARGE: u64 = 40005;

/// Discord's answer to accepting a friend request from a stranger (no mutual
/// friends or small mutual servers): it wants that confirmed first
/// (RELATIONSHIP_INVALID_NO_CONFIRMATION).
pub const STRANGER_REQUEST_NEEDS_CONFIRMATION: u64 = 80013;

/// A request Discord refused. Shown as "Discord returned 400: why"; `code`
/// is Discord's JSON error code, for callers that act on a particular one.
#[derive(Debug)]
pub struct ApiError {
    pub status: u16,
    pub code: Option<u64>,
    pub message: String,
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Discord returned {}: {}", self.status, self.message)
    }
}

impl std::error::Error for ApiError {}

impl ApiError {
    /// Discord's error code behind `e`, if Discord refused the request.
    pub fn code_of(e: &anyhow::Error) -> Option<u64> {
        e.downcast_ref::<ApiError>().and_then(|a| a.code)
    }
}

#[derive(Clone)]
pub struct Http {
    /// Talks to discord.com with the web client's headers.
    client: Client,
    /// Plain client for everything else (CDN downloads, themes): no Discord headers.
    plain: Client,
    /// The login token, shared by every copy of this client: when Discord
    /// replaces it (READY's `auth_token`), the copies that tasks already hold
    /// send the new one too, never the one Discord has just retired.
    token: std::sync::Arc<std::sync::RwLock<Option<String>>>,
    /// Discord's token for your Spotify connection, kept a while (see `spotify`).
    pub(crate) spotify: std::sync::Arc<crate::spotify::TokenCache>,
}

/// Percent-encode a query-string value.
/// A message search, as Discord web's search box sends it: the words, then
/// what its filters (`from:`, `has:`, `before:`, ...) turned into.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SearchQuery {
    pub content: String,
    /// `from:`
    pub author_id: Vec<Id>,
    /// `mentions:`
    pub mentions: Vec<Id>,
    /// `has:`, by the API's names (`forward` is `snapshot`).
    pub has: Vec<String>,
    /// `in:`
    pub channel_id: Vec<Id>,
    /// `before:` / `during:` / `after:`, as message IDs at local midnights.
    pub max_id: Option<Id>,
    pub min_id: Option<Id>,
    /// `pinned:`
    pub pinned: Option<bool>,
    /// `authorType:` (user, bot, webhook)
    pub author_type: Vec<String>,
}

impl SearchQuery {
    /// The URL query, in the order Discord web writes it (read from its
    /// requests, 2026-12-04), newest results first.
    pub fn to_query_string(&self) -> String {
        let mut out: Vec<String> = Vec::new();
        if !self.content.is_empty() {
            out.push(format!("content={}", url_encode(&self.content)));
        }
        out.extend(self.author_id.iter().map(|id| format!("author_id={id}")));
        out.extend(self.mentions.iter().map(|id| format!("mentions={id}")));
        out.extend(self.has.iter().map(|h| format!("has={}", url_encode(h))));
        out.extend(self.channel_id.iter().map(|id| format!("channel_id={id}")));
        out.extend(self.max_id.map(|id| format!("max_id={id}")));
        out.extend(self.min_id.map(|id| format!("min_id={id}")));
        out.extend(self.pinned.map(|p| format!("pinned={p}")));
        out.extend(self.author_type.iter().map(|t| format!("author_type={}", url_encode(t))));
        out.push("sort_by=timestamp&sort_order=desc&offset=0".into());
        out.join("&")
    }
}

pub(crate) fn url_encode(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

/// A path as it may be logged: without its query string (search text, IDs).
fn log_path(path: &str) -> &str {
    path.split('?').next().unwrap_or(path)
}

/// Log the first few 401s of a run: which request Discord refused the login
/// on, and when (a login Discord ends shows here first). IDs are left out.
fn note_unauthorized(method: &Method, path: &str, message: &str) {
    static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
    if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 5 {
        let shape: Vec<&str> = log_path(path).split('/').map(|p| if p.len() > 6 && p.bytes().all(|b| b.is_ascii_digit()) { ":id" } else { p }).collect();
        log::warn!("http: Discord refused the login on {method} {}: {message}", shape.join("/"));
    }
}

/// Endpoint path for closing a DM or leaving a group DM.
pub fn leave_group_path(channel: Id, silent: bool) -> String {
    format!("/channels/{channel}?silent={silent}")
}

/// A file on disk as a request body, read a piece at a time while it is sent.
fn file_body(path: std::path::PathBuf) -> reqwest::Body {
    use tokio::io::AsyncReadExt;
    let pieces = futures_util::stream::try_unfold(None::<tokio::fs::File>, move |file| {
        let path = path.clone();
        async move {
            let mut file = match file {
                Some(f) => f,
                None => tokio::fs::File::open(&path).await?,
            };
            let mut buf = vec![0u8; 256 * 1024];
            let n = file.read(&mut buf).await?;
            if n == 0 {
                return Ok::<_, std::io::Error>(None);
            }
            buf.truncate(n);
            Ok(Some((bytes::Bytes::from(buf), Some(file))))
        }
    });
    reqwest::Body::wrap_stream(pieces)
}

/// A failed request as text: "error sending request: operation timed out"
/// instead of just the first line, and without the address it went to (which
/// can carry a query string or a signed upload link).
fn net_error(e: reqwest::Error) -> String {
    error_chain(&e.without_url())
}

fn error_chain(e: &(dyn std::error::Error + 'static)) -> String {
    let mut out = e.to_string();
    let mut source = e.source();
    while let Some(s) = source {
        out.push_str(": ");
        out.push_str(&s.to_string());
        source = s.source();
    }
    out
}

/// The field messages in an error's `errors` tree
/// (`{"name": {"_errors": [{"message": "…"}]}}` → "name: …").
fn form_errors(v: &Value, path: &str) -> Vec<String> {
    let mut out = Vec::new();
    let Some(map) = v.as_object() else { return out };
    for e in map.get("_errors").and_then(Value::as_array).into_iter().flatten() {
        if let Some(m) = e.get("message").and_then(Value::as_str) {
            out.push(if path.is_empty() { m.to_string() } else { format!("{path}: {m}") });
        }
    }
    for (k, child) in map.iter().filter(|(k, _)| k.as_str() != "_errors") {
        let p = if path.is_empty() { k.clone() } else { format!("{path}.{k}") };
        out.extend(form_errors(child, &p));
    }
    out
}

/// Your account's language ("en-GB"): Discord's web client sends it as
/// `X-Discord-Locale` on every request, and the API answers in it (badge
/// labels like "Subscriber since 03/09/2025" are formatted server-side).
static ACCOUNT_LOCALE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);

/// Use the account's language for API requests (from READY's user object or
/// a changed Language setting). Ignores anything that isn't a locale tag.
pub fn set_account_locale(locale: &str) {
    let ok = (2..=10).contains(&locale.len()) && locale.chars().all(|c| c.is_ascii_alphabetic() || c == '-');
    if ok {
        if let Ok(mut l) = ACCOUNT_LOCALE.write() {
            *l = Some(locale.to_string());
        }
    }
}

/// `X-Context-Properties`: Discord's client sends `{"location": …}` (as
/// base64 JSON) with every friend request it accepts, sends, declines or
/// removes, naming the part of the app the click came from. Relationship
/// writes without it look like a script to Discord's anti-spam.
pub fn context_header(location: &str) -> (&'static str, String) {
    use base64::Engine;
    let json = json!({ "location": location }).to_string();
    ("X-Context-Properties", base64::engine::general_purpose::STANDARD.encode(json))
}

/// A captcha the person solved goes back the way Discord's client sends it:
/// as headers on the same request, sent again.
fn captcha_headers(captcha: Option<&crate::model::CaptchaAnswer>) -> Vec<(&'static str, String)> {
    let Some(c) = captcha else { return Vec::new() };
    let mut h = vec![("X-Captcha-Key", c.key.clone())];
    if let Some(token) = &c.rqtoken {
        h.push(("X-Captcha-Rqtoken", token.clone()));
    }
    if let Some(session) = &c.session_id {
        h.push(("X-Captcha-Session-Id", session.clone()));
    }
    h
}

/// The code in an invite as typed: "hTKzmak", "discord.gg/hTKzmak",
/// "https://discord.com/invite/hTKzmak?event=1". `None` unless it is only
/// the characters a code is made of (it goes into the request's path).
pub fn invite_code(input: &str) -> Option<String> {
    let s = input.trim();
    let s = s.split(['?', '#']).next().unwrap_or(s).trim_end_matches('/');
    let code = s.rsplit('/').next().unwrap_or(s);
    let ok = !code.is_empty() && code.len() <= 64 && code.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-');
    ok.then(|| code.to_string())
}

/// A snowflake sent as a JSON string.
fn id_field(v: &Value) -> Option<Id> {
    v.as_str()?.parse().ok().map(Id)
}

/// How many times Discord has answered "slow down" (429) since start. The
/// friend-request queue watches it to back off further.
static RATE_LIMITED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

pub fn rate_limit_count() -> u64 {
    RATE_LIMITED.load(std::sync::atomic::Ordering::Relaxed)
}

/// A 429: count it, and hold its route (or, for Discord's global limit, every
/// request) for as long as Discord asks; the caller then tries again. Says
/// what Discord asked for.
async fn rate_limited(route: &str, resp: reqwest::Response) -> String {
    let header = resp.headers().get("retry-after").and_then(|v| v.to_str().ok()).and_then(|s| s.trim().parse::<f64>().ok());
    let v: Value = resp.json().await.unwrap_or(Value::Null);
    // A 429 without Discord's JSON comes from the network in front of it
    // (Cloudflare), which limits by address: everything waits, and without a
    // `Retry-After` for a good while, since pressing on is what gets banned.
    let from_discord = v.get("retry_after").is_some();
    let secs = v.get("retry_after").and_then(Value::as_f64).or(header).unwrap_or(if from_discord { 1.0 } else { 30.0 });
    let global = v.get("global").and_then(Value::as_bool).unwrap_or(!from_discord);
    RATE_LIMITED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    guard::rate_limited();
    log::warn!("rate limited{} on {route}, retrying in {secs}s", if global { " (global)" } else { "" });
    ratelimit::limited(route, secs, global);
    format!("rate limited{}: retry in {secs:.1} s", if global { " (everything)" } else { "" })
}

/// Send `req` and read its answer, noting both in the Request Log. A 429
/// holds the route and gives `None`: send it again.
async fn answer(req: reqwest::RequestBuilder, route: &str, trace: &mut Option<Sent>) -> Result<Option<(StatusCode, String)>> {
    let resp = match req.send().await {
        Ok(r) => r,
        Err(e) => {
            let e = net_error(e);
            Sent::done(trace, None, 0, Some(e.clone()));
            return Err(anyhow!("couldn't reach Discord ({e})"));
        }
    };
    let status = resp.status();
    ratelimit::update(route, resp.headers());
    if status == StatusCode::TOO_MANY_REQUESTS {
        let wait = rate_limited(route, resp).await;
        Sent::done(trace, Some(429), 0, Some(wait));
        return Ok(None);
    }
    match resp.text().await {
        Ok(text) => {
            Sent::done(trace, Some(status.as_u16()), text.len(), None);
            Ok(Some((status, text)))
        }
        Err(e) => {
            let e = net_error(e);
            Sent::done(trace, Some(status.as_u16()), 0, Some(e.clone()));
            Err(anyhow!("couldn't read Discord's answer ({e})"))
        }
    }
}

/// An API request on its way, for the Request Log (`None` while it's off).
struct Sent {
    entry: reqlog::Entry,
}

impl Sent {
    fn start(method: &Method, path: &str, held: Duration) -> Option<Self> {
        if !reqlog::enabled() {
            return None;
        }
        let target = path.to_string();
        Some(Self {
            entry: reqlog::Entry {
                seq: 0,
                kind: reqlog::Kind::Api,
                at: std::time::SystemTime::now(),
                sent: Instant::now(),
                method: method.to_string(),
                target,
                status: None,
                took: Duration::ZERO,
                held,
                bytes: 0,
                note: None,
            },
        })
    }

    /// The answer came (or didn't): record it, once.
    fn done(trace: &mut Option<Self>, status: Option<u16>, bytes: usize, note: Option<String>) {
        let Some(Sent { mut entry }) = trace.take() else { return };
        entry.status = status;
        entry.took = entry.sent.elapsed();
        entry.bytes = bytes as u64;
        entry.note = note;
        reqlog::record(entry);
    }
}

/// The account's language as last set ("en-GB"), for dates and spellings.
pub fn account_locale() -> Option<String> {
    ACCOUNT_LOCALE.read().ok().and_then(|l| l.clone())
}

/// Redirects for clients that fetch addresses from elsewhere (images, theme
/// files, uploads): those are checked to be https before the request, so a
/// redirect may not lead to plain http either. Otherwise reqwest's usual limit
/// of 10.
pub fn https_only_redirects() -> reqwest::redirect::Policy {
    reqwest::redirect::Policy::custom(|attempt| {
        if attempt.url().scheme() != "https" {
            attempt.error("redirected to an address that isn't https")
        } else if attempt.previous().len() > 10 {
            attempt.error("too many redirects")
        } else {
            attempt.follow()
        }
    })
}

fn discord_headers() -> reqwest::header::HeaderMap {
    use reqwest::header::{HeaderMap, HeaderValue};
    let mut h = HeaderMap::new();
    let mut put = |name: &'static str, value: String| {
        if let Ok(v) = HeaderValue::from_str(&value) {
            h.insert(name, v);
        }
    };
    put("x-super-properties", crate::fingerprint::super_properties());
    put("x-discord-locale", crate::fingerprint::LOCALE.into());
    put("x-discord-timezone", crate::fingerprint::TIMEZONE.into());
    put("x-debug-options", crate::fingerprint::DEBUG_OPTIONS.into());
    put("accept-language", crate::fingerprint::ACCEPT_LANGUAGE.into());
    put("origin", "https://discord.com".into());
    put("referer", "https://discord.com/channels/@me".into());
    h
}

impl Http {
    pub fn new(token: Option<String>) -> Self {
        let client = Client::builder()
            .user_agent(crate::fingerprint::user_agent())
            .default_headers(discord_headers())
            .timeout(Duration::from_secs(30))
            .build()
            .expect("failed to build HTTP client");
        let plain = Client::builder()
            .user_agent(concat!("RustCord/", env!("CARGO_PKG_VERSION")))
            .timeout(Duration::from_secs(60))
            .redirect(https_only_redirects())
            .build()
            .expect("failed to build HTTP client");
        Self { client, plain, token: std::sync::Arc::new(std::sync::RwLock::new(token)), spotify: Default::default() }
    }

    /// Discord replaced the login token (see the gateway's `TokenRefreshed`):
    /// this client and every copy of it send the new one from now on.
    pub fn set_token(&self, token: String) {
        *self.token.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(token);
    }

    fn token(&self) -> Option<String> {
        self.token.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
    }

    /// Client for non-Discord requests (themes, CDN files). Sends no token
    /// and none of the Discord headers: the only client that may be pointed
    /// at an address that came from someone else.
    pub fn plain_client(&self) -> &Client {
        &self.plain
    }

    pub async fn request(&self, method: Method, path: &str, body: Option<Value>) -> Result<Value> {
        self.request_with(method, path, body, &[]).await
    }

    /// `request` with extra headers (a solved captcha's answer).
    pub async fn request_with(&self, method: Method, path: &str, body: Option<Value>, extra: &[(&str, String)]) -> Result<Value> {
        self.send_json(method, path, body, extra, Duration::ZERO).await
    }

    /// The request behind `request_with`; `held` is how long the caller
    /// already waited before it (history pacing), for the Request Log.
    async fn send_json(&self, method: Method, path: &str, body: Option<Value>, extra: &[(&str, String)], held: Duration) -> Result<Value> {
        let url = format!("{API_BASE}{path}");
        let route = ratelimit::route_key(&method, path);
        guard::note(&method, path, body.as_ref());
        let mut held = held;
        for attempt in 0..5 {
            let waiting = Instant::now();
            ratelimit::acquire(&route).await;
            let mut trace = Sent::start(&method, path, held + waiting.elapsed());
            held = Duration::ZERO;
            let mut req = self.client.request(method.clone(), &url);
            if let Some(token) = self.token() {
                req = req.header("Authorization", token);
            }
            if let Some(locale) = account_locale() {
                req = req.header("x-discord-locale", locale);
            }
            for (name, value) in extra {
                req = req.header(*name, value);
            }
            if let Some(body) = &body {
                req = req.json(body);
            } else if method == Method::PUT || method == Method::POST {
                // Discord wants an explicit Content-Length: 0 on bodyless writes.
                req = req.body(Vec::<u8>::new());
            }
            let resp = match req.send().await {
                Ok(r) => r,
                // Connection hiccup: retry reads once or twice, report writes.
                Err(e) if method == Method::GET && attempt < 2 => {
                    let e = net_error(e);
                    Sent::done(&mut trace, None, 0, Some(e.clone()));
                    log::warn!("GET {} failed ({e}), retrying", log_path(path));
                    tokio::time::sleep(Duration::from_millis(500 * (attempt as u64 + 1))).await;
                    continue;
                }
                Err(e) => {
                    let e = net_error(e);
                    Sent::done(&mut trace, None, 0, Some(e.clone()));
                    return Err(anyhow!("couldn't reach Discord ({e})"));
                }
            };
            let status = resp.status();
            ratelimit::update(&route, resp.headers());

            if status == StatusCode::TOO_MANY_REQUESTS {
                let wait = rate_limited(&route, resp).await;
                Sent::done(&mut trace, Some(429), 0, Some(wait));
                continue;
            }
            if status == StatusCode::NO_CONTENT {
                Sent::done(&mut trace, Some(204), 0, None);
                return Ok(Value::Null);
            }

            let text = match resp.text().await {
                Ok(t) => t,
                Err(e) => {
                    let e = net_error(e);
                    Sent::done(&mut trace, Some(status.as_u16()), 0, Some(e.clone()));
                    return Err(anyhow!("couldn't read Discord's answer ({e})"));
                }
            };
            Sent::done(&mut trace, Some(status.as_u16()), text.len(), None);
            if !status.is_success() {
                let parsed = serde_json::from_str::<Value>(&text).ok();
                let mut message = parsed
                    .as_ref()
                    .and_then(|v| v.get("message").and_then(Value::as_str).map(String::from))
                    .unwrap_or(text);
                // "Invalid Form Body": say which fields and why.
                let fields = parsed.as_ref().map(|v| form_errors(&v["errors"], "")).unwrap_or_default();
                if !fields.is_empty() {
                    message = format!("{message} ({})", fields.join("; "));
                }
                let code = parsed.as_ref().and_then(|v| v["code"].as_u64());
                if status == StatusCode::UNAUTHORIZED {
                    note_unauthorized(&method, path, &message);
                }
                return Err(ApiError { status: status.as_u16(), code, message }.into());
            }
            return Ok(if text.is_empty() {
                Value::Null
            } else {
                serde_json::from_str(&text)?
            });
        }
        Err(anyhow!("rate limited too many times on {}", log_path(path)))
    }

    /// A multipart form POST (sticker and soundboard uploads): text `fields`
    /// plus one file part named `file`.
    pub async fn upload_form(&self, path: &str, fields: &[(String, String)], file: (String, Vec<u8>, String)) -> Result<Value> {
        use reqwest::multipart::{Form, Part};
        let url = format!("{API_BASE}{path}");
        let route = ratelimit::route_key(&Method::POST, path);
        guard::note(&Method::POST, path, None);
        for _ in 0..3 {
            let waiting = Instant::now();
            ratelimit::acquire(&route).await;
            let mut trace = Sent::start(&Method::POST, path, waiting.elapsed());
            let mut form = Form::new();
            for (k, v) in fields {
                form = form.text(k.clone(), v.clone());
            }
            let (name, bytes, mime) = &file;
            form = form.part("file", Part::bytes(bytes.clone()).file_name(name.clone()).mime_str(mime)?);
            let mut req = self.client.post(&url).multipart(form).timeout(Duration::from_secs(120));
            if let Some(token) = self.token() {
                req = req.header("Authorization", token);
            }
            let (status, text) = match answer(req, &route, &mut trace).await? {
                Some(answer) => answer,
                None => continue,
            };
            if !status.is_success() {
                let parsed = serde_json::from_str::<Value>(&text).ok();
                let mut message = parsed.as_ref().and_then(|v| v.get("message").and_then(Value::as_str).map(String::from)).unwrap_or(text);
                let fields = parsed.as_ref().map(|v| form_errors(&v["errors"], "")).unwrap_or_default();
                if !fields.is_empty() {
                    message = format!("{message} ({})", fields.join("; "));
                }
                let code = parsed.as_ref().and_then(|v| v["code"].as_u64());
                return Err(ApiError { status: status.as_u16(), code, message }.into());
            }
            return Ok(if text.is_empty() { Value::Null } else { serde_json::from_str(&text)? });
        }
        Err(anyhow!("rate limited too many times while uploading"))
    }

    /// One request, no retries, answered whatever the status: (status, body).
    /// For account changes, where a 401 can be "verify it's you first".
    pub async fn request_raw(&self, method: Method, path: &str, body: Option<Value>, extra: &[(&str, String)]) -> Result<(u16, Value)> {
        let mut req = self.client.request(method.clone(), format!("{API_BASE}{path}"));
        if let Some(token) = self.token() {
            req = req.header("Authorization", token);
        }
        if let Some(locale) = account_locale() {
            req = req.header("x-discord-locale", locale);
        }
        for (name, value) in extra {
            req = req.header(*name, value);
        }
        if let Some(body) = &body {
            req = req.json(body);
        } else if method == Method::PUT || method == Method::POST {
            req = req.body(Vec::<u8>::new());
        }
        let route = ratelimit::route_key(&method, path);
        guard::note(&method, path, body.as_ref());
        let mut trace = Sent::start(&method, path, Duration::ZERO);
        match answer(req, &route, &mut trace).await? {
            Some((status, text)) => Ok((status.as_u16(), serde_json::from_str(&text).unwrap_or(Value::Null))),
            None => Ok((429, json!({ "message": "You are being rate limited." }))),
        }
    }

    /// What an error body says, with the fields it complains about.
    pub fn error_message(body: &Value) -> String {
        let mut message = body.get("message").and_then(Value::as_str).unwrap_or("Discord refused that.").to_string();
        let fields = form_errors(&body["errors"], "");
        if !fields.is_empty() {
            message = format!("{message} ({})", fields.join("; "));
        }
        message
    }

    pub async fn current_user(&self) -> Result<User> {
        Ok(serde_json::from_value(
            self.request(Method::GET, "/users/@me", None).await?,
        )?)
    }

    /// Newest-first page of messages, like the API returns. Older pages
    /// (`before`) wait their turn (see `ratelimit::history_page`).
    pub async fn messages(&self, channel: Id, before: Option<Id>, limit: u8) -> Result<Vec<Message>> {
        let mut path = format!("/channels/{channel}/messages?limit={limit}");
        let mut held = Duration::ZERO;
        if let Some(before) = before {
            held = ratelimit::history_page().await;
            path.push_str(&format!("&before={before}"));
        }
        Ok(serde_json::from_value(self.send_json(Method::GET, &path, None, &[], held).await?)?)
    }

    pub async fn send_message(&self, msg: &OutgoingMessage) -> Result<Message> {
        let body = serde_json::to_value(msg)?;
        let path = format!("/channels/{}/messages", msg.channel_id);
        // Files go the way the official client sends them: straight to
        // Discord's storage, then the message names them.
        if !msg.uploads.is_empty() {
            return self.send_with_stored_files(&path, body, msg).await;
        }
        let extra = captcha_headers(msg.captcha.as_ref());
        Ok(serde_json::from_value(
            self.request_with(Method::POST, &path, Some(body), &extra).await?,
        )?)
    }

    /// Ask for an upload address per file (`/attachments`), PUT each file
    /// there, then send the message with the stored files' names. Discord
    /// checks the sizes against this account's limit in this channel when
    /// it hands out the addresses, before any file is sent.
    async fn send_with_stored_files(&self, path: &str, mut payload: Value, msg: &OutgoingMessage) -> Result<Message> {
        let mut sizes = Vec::with_capacity(msg.uploads.len());
        for u in &msg.uploads {
            sizes.push(match &u.data {
                UploadData::Memory(b) => b.len() as u64,
                UploadData::Disk(p) => std::fs::metadata(p).map_err(|e| anyhow!("couldn't read {}: {e}", u.filename))?.len(),
            });
        }
        let files: Vec<Value> = msg
            .uploads
            .iter()
            .zip(&sizes)
            .enumerate()
            .map(|(i, (u, size))| json!({ "filename": u.filename, "file_size": size, "id": i.to_string(), "is_clip": false }))
            .collect();
        let slots = match self.request(Method::POST, &format!("/channels/{}/attachments", msg.channel_id), Some(json!({ "files": files }))).await {
            Ok(v) => v,
            Err(e) if ApiError::code_of(&e) == Some(FILE_TOO_LARGE) => {
                let said = e.downcast_ref::<ApiError>().map(|a| a.message.clone()).unwrap_or_default();
                return Err(anyhow!("Discord won't take a file this big from you here ({said})"));
            }
            Err(e) => return Err(e),
        };
        let slots = slots["attachments"].as_array().cloned().unwrap_or_default();
        if slots.len() != msg.uploads.len() {
            return Err(anyhow!("Discord didn't accept the upload"));
        }
        let mut attachments = Vec::new();
        for (i, ((u, slot), size)) in msg.uploads.iter().zip(&slots).zip(&sizes).enumerate() {
            let (Some(url), Some(stored)) = (slot["upload_url"].as_str(), slot["upload_filename"].as_str()) else {
                return Err(anyhow!("Discord didn't say where to upload {}", u.filename));
            };
            if !url.starts_with("https://") {
                return Err(anyhow!("Discord's upload address for {} isn't secure (https)", u.filename));
            }
            // (No token: this goes to the storage service, not to Discord's API.
            // The address is a signed link, so it stays out of the error.)
            let sent = Instant::now();
            // The file is streamed (never all in memory); the length is the
            // size Discord was told, so the storage service knows when it's done.
            let body = match &u.data {
                UploadData::Memory(b) => reqwest::Body::from(bytes::Bytes::from_owner(b.clone())),
                UploadData::Disk(p) => file_body(p.clone()),
            };
            let resp = self
                .plain
                .put(url)
                .header("Content-Type", "application/octet-stream")
                .header("Content-Length", size.to_string())
                .body(body)
                .timeout(Duration::from_secs(1800))
                .send()
                .await;
            let resp = match resp {
                Ok(r) => r,
                Err(e) => {
                    let e = net_error(e);
                    reqlog::record_media("PUT", url, sent, None, 0, Some(e.clone()));
                    return Err(anyhow!("uploading {} failed ({e})", u.filename));
                }
            };
            reqlog::record_media("PUT", url, sent, Some(resp.status().as_u16()), 0, Some(format!("{:.1} MB sent", *size as f64 / 1_048_576.0)));
            if !resp.status().is_success() {
                return Err(anyhow!("uploading {} failed ({})", u.filename, resp.status().as_u16()));
            }
            attachments.push(json!({ "id": i.to_string(), "filename": u.filename, "uploaded_filename": stored }));
        }
        payload["attachments"] = Value::Array(attachments);
        Ok(serde_json::from_value(self.request(Method::POST, path, Some(payload)).await?)?)
    }

    pub async fn user_profile(&self, user: Id, guild: Option<Id>) -> Result<UserProfile> {
        let mut path = format!("/users/{user}/profile?with_mutual_guilds=true&with_mutual_friends=true&with_mutual_friends_count=true");
        if let Some(g) = guild {
            path.push_str(&format!("&guild_id={g}"));
        }
        let v = self.request(Method::GET, &path, None).await?;
        // Once per run: which profile sections Discord sends (names only).
        static LOGGED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
        if !LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
            let keys = |o: &Value| o.as_object().map(|m| m.keys().cloned().collect::<Vec<_>>().join(",")).unwrap_or_default();
            log::debug!("profile sections: [{}] user_profile: [{}]", keys(&v), keys(&v["user_profile"]));
        }
        Ok(serde_json::from_value(v)?)
    }

    /// Open (or fetch) the DM channel with a user. Returns the channel object.
    pub async fn open_dm(&self, user: Id) -> Result<Value> {
        self.request(Method::POST, "/users/@me/channels", Some(json!({ "recipients": [user] })))
            .await
    }

    /// Pinned messages, newest pin first. Discord's current endpoint
    /// (`/messages/pins`, `{items: [{message, pinned_at}]}`), falling back to
    /// the older `/pins` list.
    pub async fn pins(&self, channel: Id) -> Result<Vec<Message>> {
        match self.request(Method::GET, &format!("/channels/{channel}/messages/pins?limit=50"), None).await {
            Ok(v) if v["items"].is_array() => Ok(v["items"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|i| serde_json::from_value::<Message>(i["message"].clone()).ok())
                .collect()),
            _ => Ok(serde_json::from_value(self.request(Method::GET, &format!("/channels/{channel}/pins"), None).await?)?),
        }
    }

    /// Give (`add`) or take away a role.
    pub async fn set_member_role(&self, guild: Id, user: Id, role: Id, add: bool) -> Result<()> {
        let path = format!("/guilds/{guild}/members/{user}/roles/{role}");
        self.request(if add { Method::PUT } else { Method::DELETE }, &path, None).await?;
        Ok(())
    }

    /// Edit a channel (name, topic, slowmode, NSFW…).
    pub async fn edit_channel(&self, channel: Id, patch: Value) -> Result<()> {
        self.request(Method::PATCH, &format!("/channels/{channel}"), Some(patch)).await?;
        Ok(())
    }

    pub async fn delete_channel(&self, channel: Id) -> Result<()> {
        self.request(Method::DELETE, &format!("/channels/{channel}"), None).await?;
        Ok(())
    }

    /// Close a DM or leave a group DM (`silent`: suppress the leave system message).
    pub async fn leave_group(&self, channel: Id, silent: bool) -> Result<()> {
        self.request(Method::DELETE, &leave_group_path(channel, silent), None).await?;
        Ok(())
    }

    /// Create a channel or category (`kind` 0 text, 2 voice, 4 category).
    pub async fn create_channel(&self, guild: Id, body: Value) -> Result<Value> {
        self.request(Method::POST, &format!("/guilds/{guild}/channels"), Some(body)).await
    }

    /// Invite link for a channel (7 days, unlimited uses — Discord's default).
    /// A new invite to `channel` (Discord's invite modal defaults: 30 days,
    /// no use limit, not temporary).
    pub async fn create_invite(&self, channel: Id, max_age: u32, max_uses: u32, temporary: bool) -> Result<String> {
        let v = self
            .request(Method::POST, &format!("/channels/{channel}/invites"), Some(json!({ "max_age": max_age, "max_uses": max_uses, "temporary": temporary })))
            .await?;
        v["code"].as_str().map(|c| format!("https://discord.gg/{c}")).ok_or_else(|| anyhow!("Discord didn't return an invite code"))
    }

    /// Accept (`true`) or ignore a message request.
    pub async fn answer_message_request(&self, channel: Id, accept: bool) -> Result<()> {
        let path = format!("/channels/{channel}/recipients/@me");
        if accept {
            self.request(Method::PUT, &path, Some(json!({ "consent_status": 2 }))).await?;
        } else {
            self.request(Method::DELETE, &path, None).await?;
        }
        Ok(())
    }

    /// The message that started each request (up to 25 channels).
    pub async fn message_request_previews(&self, channels: &[Id]) -> Result<Vec<(Id, Message)>> {
        let q: Vec<String> = channels.iter().take(25).map(|c| format!("channel_ids={c}")).collect();
        let v = self.request(Method::GET, &format!("/users/@me/message-requests/supplemental-data?{}", q.join("&")), None).await?;
        Ok(v.as_array()
            .into_iter()
            .flatten()
            .filter_map(|e| Some((Id::from_value(&e["channel_id"])?, serde_json::from_value(e["message_preview"].clone()).ok()?)))
            .collect())
    }

    /// Friend request by username (the Add Friend box).
    pub async fn send_friend_request(&self, username: &str) -> Result<()> {
        let body = json!({ "username": username, "discriminator": null });
        self.request_with(Method::POST, "/users/@me/relationships", Some(body), &[context_header("Add Friend")]).await?;
        Ok(())
    }

    pub async fn leave_guild(&self, guild: Id) -> Result<()> {
        self.request(Method::DELETE, &format!("/users/@me/guilds/{guild}"), Some(json!({ "lurking": false }))).await?;
        Ok(())
    }

    /// Per-server settings (mute, hide muted channels…).
    pub async fn guild_settings(&self, guild: Id, patch: Value) -> Result<()> {
        self.request(Method::PATCH, &format!("/users/@me/guilds/{guild}/settings"), Some(patch)).await?;
        Ok(())
    }

    /// Names and icons of games (applications), for Game Collection.
    pub async fn apps_public(&self, ids: &[Id]) -> Result<Vec<crate::model::AppInfo>> {
        let q: Vec<String> = ids.iter().take(25).map(|i| format!("application_ids={i}")).collect();
        let v = self.request(Method::GET, &format!("/applications/public?{}", q.join("&")), None).await?;
        Ok(v.as_array().into_iter().flatten().filter_map(|a| serde_json::from_value(a.clone()).ok()).collect())
    }

    /// Ignore someone, or stop: Discord's `PUT` / `DELETE
    /// /users/@me/relationships/{id}/ignore`, with where it was clicked as
    /// the context, like its client.
    pub async fn set_ignored(&self, user: Id, on: bool, location: &str) -> Result<()> {
        let method = if on { Method::PUT } else { Method::DELETE };
        self.request_with(method, &format!("/users/@me/relationships/{user}/ignore"), None, &[context_header(location)]).await?;
        Ok(())
    }

    /// Discord's game database entries for these ids (box art for the Board):
    /// `GET /games?game_ids=…`, twenty at a time like the web client.
    pub async fn games(&self, ids: &[Id]) -> Result<Vec<crate::model::AppInfo>> {
        let q: Vec<String> = ids.iter().take(20).map(|i| format!("game_ids={i}")).collect();
        let v = self.request(Method::GET, &format!("/games?{}", q.join("&")), None).await?;
        Ok(v.as_array().into_iter().flatten().filter_map(crate::model::AppInfo::from_game).collect())
    }

    /// The server card behind a server tag.
    pub async fn guild_profile(&self, guild: Id) -> Result<GuildProfile> {
        let v = self.request(Method::GET, &format!("/guilds/{guild}/profile"), None).await?;
        log::debug!("guild profile {guild}: traits {} features {}", v["traits"], v["features"]);
        Ok(serde_json::from_value(v)?)
    }

    /// Recent mentions (the inbox), newest first.
    pub async fn mentions(&self) -> Result<Vec<Message>> {
        let path = "/users/@me/mentions?limit=25&roles=true&everyone=true";
        Ok(serde_json::from_value(self.request(Method::GET, path, None).await?)?)
    }

    /// Discord's GIF picker: trending GIFs (no query) or a search, via Tenor.
    /// Click a bot's button or pick from its select menu (`values`), the way
    /// the official client does: an interaction of type 3.
    #[allow(clippy::too_many_arguments)]
    pub async fn component_interaction(
        &self,
        application: Id,
        guild: Option<Id>,
        channel: Id,
        message: Id,
        message_flags: u64,
        session_id: &str,
        component_type: u8,
        custom_id: &str,
        values: Option<Vec<String>>,
    ) -> Result<()> {
        let mut data = json!({ "component_type": component_type, "custom_id": custom_id });
        if let Some(v) = values {
            data["type"] = json!(component_type);
            data["values"] = json!(v);
        }
        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
        let nonce = crate::model::Id::from_timestamp_ms(now).0.to_string();
        let body = json!({
            "type": 3,
            "nonce": nonce,
            "guild_id": guild.map(|g| g.to_string()),
            "channel_id": channel.to_string(),
            "message_flags": message_flags,
            "message_id": message.to_string(),
            "application_id": application.to_string(),
            "session_id": session_id,
            "data": data,
        });
        self.request(Method::POST, "/interactions", Some(body)).await?;
        Ok(())
    }

    // ---- Quests, Shop, Nitro ------------------------------------------------

    pub async fn quests(&self) -> Result<crate::commerce::QuestList> {
        let v = self.request(Method::GET, "/quests/@me", None).await?;
        Ok(serde_json::from_value(v)?)
    }

    /// Your Orbs (Discord's quest currency).
    pub async fn orb_balance(&self) -> Result<u64> {
        let v = self.request(Method::GET, "/users/@me/virtual-currency/balance", None).await?;
        Ok(v["balance"].as_u64().unwrap_or(0))
    }

    /// "Accept Quest", as from the desktop Quests page.
    pub async fn enroll_quest(&self, quest: Id, traffic_sealed: Option<&str>) -> Result<()> {
        let body = json!({
            "location": 11,
            "is_targeted": false,
            "metadata_raw": null,
            "metadata_sealed": null,
            "traffic_metadata_raw": null,
            "traffic_metadata_sealed": traffic_sealed,
        });
        self.request(Method::POST, &format!("/quests/{quest}/enroll"), Some(body)).await?;
        Ok(())
    }

    /// The collectibles Shop's home tab (featured categories and products).
    pub async fn collectibles_shop(&self) -> Result<crate::commerce::Shop> {
        let path = "/collectibles-shop?tab=home&include_bundles=true&include_dynamic_blocks=true&variants_return_style=2&skip_num_categories=0";
        let v = self.request(Method::GET, path, None).await?;
        Ok(serde_json::from_value(v)?)
    }

    pub async fn subscriptions(&self) -> Result<Vec<crate::commerce::Subscription>> {
        let v = self.request(Method::GET, "/users/@me/billing/subscriptions", None).await?;
        Ok(serde_json::from_value(v)?)
    }

    /// GIF search / trending, as MP4 clips (`src` and `preview`): Discord's own
    /// picker asks for video too (webm). A clip is a fraction of the GIF
    /// file's size, and Windows decodes it on the GPU.
    pub async fn gifs(&self, query: Option<&str>) -> Result<Vec<Gif>> {
        let path = match query {
            Some(q) => format!("/gifs/search?q={}&media_format=mp4&provider=tenor&locale=en-US", url_encode(q)),
            None => "/gifs/trending-gifs?media_format=mp4&provider=tenor&locale=en-US".to_string(),
        };
        let v = self.request(Method::GET, &path, None).await?;
        Ok(v.as_array()
            .into_iter()
            .flatten()
            .filter_map(|g| serde_json::from_value::<Gif>(g.clone()).ok())
            .filter(|g| !g.url.is_empty() && !g.src.is_empty())
            .collect())
    }

    /// Message search in a server (or a DM channel). Returns (total, hits).
    pub async fn search(&self, guild: Option<Id>, channel: Id, query: &SearchQuery) -> Result<(u64, Vec<Message>)> {
        let q = query.to_query_string();
        let path = match guild {
            Some(g) => format!("/guilds/{g}/messages/search?{q}"),
            None => format!("/channels/{channel}/messages/search?{q}"),
        };
        let v = self.request(Method::GET, &path, None).await?;
        if v.get("messages").is_none() {
            // 202: Discord is still indexing this server.
            return Err(anyhow!("Discord is still indexing this server's messages. Try again in a few seconds."));
        }
        let total = v["total_results"].as_u64().unwrap_or(0);
        let mut hits = Vec::new();
        for group in v["messages"].as_array().into_iter().flatten() {
            let arr = group.as_array().cloned().unwrap_or_default();
            let hit = arr.iter().find(|m| m["hit"].as_bool() == Some(true)).or_else(|| arr.first());
            if let Some(m) = hit {
                if let Ok(m) = serde_json::from_value::<Message>(m.clone()) {
                    hits.push(m);
                }
            }
        }
        Ok((total, hits))
    }

    /// Mark a channel read up to `message`. Returns the ack token to send next time.
    pub async fn ack(&self, channel: Id, message: Id, token: Option<String>) -> Result<Option<String>> {
        let path = format!("/channels/{channel}/messages/{message}/ack");
        let v = self.request(Method::POST, &path, Some(json!({ "token": token, "manual": false }))).await?;
        Ok(v.get("token").and_then(Value::as_str).map(String::from))
    }

    /// "Mark Unread": move the read marker back to just before `message`.
    pub async fn ack_manual(&self, channel: Id, message: Id, mention_count: u32) -> Result<()> {
        let path = format!("/channels/{channel}/messages/{message}/ack");
        self.request(Method::POST, &path, Some(json!({ "manual": true, "mention_count": mention_count }))).await?;
        Ok(())
    }

    pub async fn settings_proto(&self) -> Result<crate::settings_proto::UserSettings> {
        let v = self.request(Method::GET, "/users/@me/settings-proto/1", None).await?;
        let b64 = v.get("settings").and_then(Value::as_str).unwrap_or_default();
        Ok(crate::settings_proto::decode(b64)?)
    }

    /// Persist status / custom status (re-reads settings first for the data version).
    pub async fn save_status(&self, status: &str, custom: Option<&crate::settings_proto::CustomStatus>) -> Result<()> {
        let current = self.settings_proto().await?;
        let patch = crate::settings_proto::encode_status_patch(&current, status, custom)?;
        self.request(
            Method::PATCH,
            "/users/@me/settings-proto/1",
            Some(json!({ "settings": patch, "required_data_version": current.version })),
        )
        .await?;
        Ok(())
    }

    /// Accept a friend request (or send one) by user id. `location`: where in
    /// the client it was clicked, as Discord's own client names it ("Friends",
    /// "User Profile", "DM Channel", "Context Menu"); see [`context_header`].
    pub async fn add_friend(&self, user: Id, location: &str) -> Result<()> {
        self.add_friend_with(user, None, false, location).await
    }

    /// `add_friend`, with the answer to a captcha Discord demanded for it, and
    /// `stranger` once you've confirmed accepting a request from someone you
    /// share no friends or small servers with (Discord's "Accept friend request?").
    pub async fn add_friend_with(&self, user: Id, captcha: Option<&crate::model::CaptchaAnswer>, stranger: bool, location: &str) -> Result<()> {
        let mut extra = vec![context_header(location)];
        extra.extend(captcha_headers(captcha));
        let body = if stranger { json!({ "confirm_stranger_request": true }) } else { json!({}) };
        self.request_with(Method::PUT, &format!("/users/@me/relationships/{user}"), Some(body), &extra).await?;
        Ok(())
    }

    /// Remove a friend / decline or cancel a request (`location` as in [`Http::add_friend`]).
    pub async fn remove_relationship(&self, user: Id, location: &str) -> Result<()> {
        self.request_with(Method::DELETE, &format!("/users/@me/relationships/{user}"), None, &[context_header(location)]).await?;
        Ok(())
    }

    /// "Create Your Server": `body` is Discord's (name, icon, the template's
    /// channels, `guild_template_code`). Returns the new server's ID; the
    /// server itself arrives over the gateway (GUILD_CREATE).
    pub async fn create_guild(&self, body: &Value, captcha: Option<&crate::model::CaptchaAnswer>) -> Result<Id> {
        let v = self.request_with(Method::POST, "/guilds", Some(body.clone()), &captcha_headers(captcha)).await?;
        id_field(&v["id"]).ok_or_else(|| anyhow!("Discord didn't say which server it made"))
    }

    /// "Join a Server": look the invite up, then accept it the way Discord's
    /// client does (gateway `session` in the body, "Join Guild" as the
    /// context). `input` is what was typed; Discord sends it along. Returns
    /// the server's ID.
    pub async fn join_invite(&self, code: &str, input: &str, session: Option<&str>, captcha: Option<&crate::model::CaptchaAnswer>) -> Result<Id> {
        let lookup = format!("/invites/{code}?inputValue={}&with_counts=true&with_expiration=true&with_permissions=true", url_encode(input));
        let invite = match self.request(Method::GET, &lookup, None).await {
            Ok(v) => v,
            Err(e) if e.downcast_ref::<ApiError>().is_some_and(|a| a.status == 404) => {
                return Err(anyhow!("The invite is invalid or has expired."));
            }
            Err(e) => return Err(e),
        };
        let guild = id_field(&invite["guild"]["id"]).or_else(|| id_field(&invite["guild_id"])).ok_or_else(|| anyhow!("That invite isn't to a server."))?;
        let context = json!({
            "location": "Join Guild",
            "location_guild_id": guild.to_string(),
            "location_channel_id": invite["channel"]["id"],
            "location_channel_type": invite["channel"]["type"],
        });
        let mut extra = vec![("X-Context-Properties", {
            use base64::Engine;
            base64::engine::general_purpose::STANDARD.encode(context.to_string())
        })];
        extra.extend(captcha_headers(captcha));
        let body = match session {
            Some(s) => json!({ "session_id": s }),
            None => json!({}),
        };
        self.request_with(Method::POST, &format!("/invites/{code}"), Some(body), &extra).await?;
        Ok(guild)
    }

    pub async fn set_pinned(&self, channel: Id, id: Id, pinned: bool) -> Result<()> {
        let path = format!("/channels/{channel}/pins/{id}");
        let method = if pinned { Method::PUT } else { Method::DELETE };
        self.request(method, &path, None).await?;
        Ok(())
    }

    pub async fn edit_message(&self, channel: Id, id: Id, content: &str) -> Result<Message> {
        let path = format!("/channels/{channel}/messages/{id}");
        Ok(serde_json::from_value(
            self.request(Method::PATCH, &path, Some(json!({ "content": content })))
                .await?,
        )?)
    }

    pub async fn delete_message(&self, channel: Id, id: Id) -> Result<()> {
        let path = format!("/channels/{channel}/messages/{id}");
        self.request(Method::DELETE, &path, None).await?;
        Ok(())
    }

    pub async fn trigger_typing(&self, channel: Id) -> Result<()> {
        let path = format!("/channels/{channel}/typing");
        self.request(Method::POST, &path, None).await?;
        Ok(())
    }

    /// Add (`add = true`) or remove your reaction.
    pub async fn react(&self, channel: Id, message: Id, emoji: &ReactionEmoji, add: bool) -> Result<()> {
        let path = format!("/channels/{channel}/messages/{message}/reactions/{}/@me", emoji.api_path());
        let method = if add { Method::PUT } else { Method::DELETE };
        self.request(method, &path, None).await?;
        Ok(())
    }

    /// End this session at Discord, the way its own client logs out: the token
    /// stops working everywhere. Nothing to do without a token.
    pub async fn logout(&self) -> Result<()> {
        if self.token().is_none() {
            return Ok(());
        }
        self.request(Method::POST, "/auth/logout", Some(json!({ "provider": null, "voip_provider": null }))).await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A token Discord replaced reaches the copies tasks already hold.
    #[test]
    fn replaced_token_reaches_every_copy() {
        let http = Http::new(Some("old".into()));
        let held = http.clone();
        http.set_token("new".into());
        assert_eq!(held.token().as_deref(), Some("new"));
        // Another session's client keeps its own.
        assert_eq!(Http::new(Some("other".into())).token().as_deref(), Some("other"));
    }

    /// The request Discord web made for `hello has:forward has:sound
    /// before:2026-12-01 after:2026-11-01 during:2026-11-15 pinned:false
    /// authorType:bot` (2026-12-04).
    #[test]
    fn a_search_asks_like_discord_web() {
        let q = SearchQuery {
            content: "hello".into(),
            has: vec!["snapshot".into(), "sound".into()],
            max_id: Some(Id(1571676173107200000)),
            min_id: Some(Id(1571313785241600000)),
            pinned: Some(false),
            author_type: vec!["bot".into()],
            ..Default::default()
        };
        assert_eq!(
            q.to_query_string(),
            "content=hello&has=snapshot&has=sound&max_id=1571676173107200000&min_id=1571313785241600000&pinned=false&author_type=bot&sort_by=timestamp&sort_order=desc&offset=0"
        );
    }

    /// A file from disk goes out whole, with the length given up front
    /// (storage upload links want Content-Length, not chunks).
    #[test]
    fn a_file_on_disk_is_sent_whole_with_its_length() {
        use std::io::{Read, Write};
        let data: Vec<u8> = (0..700_000u32).map(|i| (i * 31 % 251) as u8).collect();
        let path = std::env::temp_dir().join(format!("rustcord-upload-test-{}.bin", std::process::id()));
        std::fs::write(&path, &data).unwrap();
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let server = std::thread::spawn(move || {
            let (mut s, _) = listener.accept().unwrap();
            let mut got = Vec::new();
            let mut buf = [0u8; 65536];
            let body_at = loop {
                let n = s.read(&mut buf).unwrap();
                got.extend_from_slice(&buf[..n]);
                if let Some(i) = got.windows(4).position(|w| w == b"\r\n\r\n") {
                    break i + 4;
                }
            };
            let head = String::from_utf8_lossy(&got[..body_at]).to_lowercase();
            let len: usize = head.lines().find_map(|l| l.strip_prefix("content-length: ")).unwrap().trim().parse().unwrap();
            while got.len() < body_at + len {
                let n = s.read(&mut buf).unwrap();
                got.extend_from_slice(&buf[..n]);
            }
            s.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n").unwrap();
            (head, got[body_at..].to_vec())
        });
        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        let status = rt.block_on(async {
            reqwest::Client::new()
                .put(format!("http://127.0.0.1:{port}/upload"))
                .header("Content-Length", data.len().to_string())
                .body(file_body(path.clone()))
                .send()
                .await
                .unwrap()
                .status()
        });
        let (head, body) = server.join().unwrap();
        std::fs::remove_file(&path).ok();
        assert!(status.is_success());
        assert!(!head.contains("transfer-encoding"), "sent in chunks: {head}");
        assert!(body == data, "the file arrived changed");
    }

    #[test]
    fn invite_codes_from_what_people_paste() {
        assert_eq!(invite_code("hTKzmak").as_deref(), Some("hTKzmak"));
        assert_eq!(invite_code(" https://discord.gg/hTKzmak ").as_deref(), Some("hTKzmak"));
        assert_eq!(invite_code("https://discord.com/invite/wumpus-friends?event=1").as_deref(), Some("wumpus-friends"));
        assert_eq!(invite_code("discord.gg/abc/").as_deref(), Some("abc"));
        assert_eq!(invite_code("../../users/@me"), None);
        assert_eq!(invite_code(""), None);
    }

    #[test]
    fn logged_paths_have_no_query() {
        assert_eq!(log_path("/guilds/1/messages/search?content=private%20words"), "/guilds/1/messages/search");
        assert_eq!(log_path("/users/@me"), "/users/@me");
    }

    #[test]
    fn leave_group_path_formats_silent_flag() {
        assert_eq!(leave_group_path(Id(42), false), "/channels/42?silent=false");
        assert_eq!(leave_group_path(Id(42), true), "/channels/42?silent=true");
    }

    #[test]
    fn api_errors_keep_their_text_and_code() {
        let e: anyhow::Error = ApiError { status: 400, code: Some(STRANGER_REQUEST_NEEDS_CONFIRMATION), message: "Confirm it".into() }.into();
        assert_eq!(ApiError::code_of(&e), Some(80013));
        assert_eq!(format!("{e:#}"), "Discord returned 400: Confirm it");
        // Through added context too.
        let e = e.context("adding a friend");
        assert_eq!(ApiError::code_of(&e), Some(80013));
        assert_eq!(ApiError::code_of(&anyhow!("couldn't reach Discord")), None);
    }
}