wuapi 0.15.0

Rust SDK for wuapi, a WhatsApp API for developers. Link numbers by QR or pairing code, send and receive messages, manage chats, contacts, groups and channels, split them into projects and verify webhooks.
Documentation
// Generated by wuapi-codegen from the OpenAPI spec. Do not edit: run `bun run codegen`.

use crate::http::{HttpClient, Method, Request, RequestParts, encode_path};
use crate::pagination::Paginator;
use crate::types;

/// The `messages` methods.
#[derive(Clone, Debug)]
pub struct MessagesResource {
    http: HttpClient,
}

impl MessagesResource {
    pub(crate) fn new(http: HttpClient) -> Self {
        Self { http }
    }

    /// Send a message
    ///
    /// Queue a message from a `ready` account to a contact, a group, or a channel the account administers. It is returned with `status: queued`; the outcome arrives as `message.sent` / `message.failed`, or read it with `GET /v1/messages/{messageId}`. An account that dropped from `ready` for a reconnect less than the offline tolerance ago (currently 3 minutes) still takes it: it waits for the account, is sent once the account is back (in order, with the same WhatsApp message id if an earlier attempt was cut off), and fails with `account_offline` if the account is not back within the tolerance or goes down for good (logged out, banned, replaced, deleted). The account's pacing (12 per minute and 5 per minute to first contacts by default, see `pacing` on the account) keeps it queued and retried for up to `pacing.queueTimeoutMinutes` (60 by default) before it fails with `rate_limited`. A recipient without WhatsApp fails with `error.code: not_on_whatsapp`.
    ///
    /// Send `Idempotency-Key` so a retry never sends twice.
    ///
    /// Media types take `media.url` (a public URL our servers download) or `media.uploadId` (a file uploaded with `POST /v1/uploads`: a local file, a pasted image, a recorded voice note). An upload that does not exist, expired or belongs to another organization or project answers `404`; one that is still `pending` answers `400`.
    ///
    /// To reply to a contact's story, send the message to the story's author (`to`: its `contactId`) with `replyToStoryId`.
    ///
    /// `POST /v1/messages`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn send(&self, params: impl Into<types::MessagesSendParams>) -> Request<types::Message> {
        let params = params.into();
        let parts = RequestParts::new(Method::Post, "/v1/messages").body(&params).keyed();
        self.http.request(parts)
    }

    /// List messages
    ///
    /// Messages in scope, newest first.
    ///
    /// `GET /v1/messages`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn list(&self, params: types::MessagesListParams) -> Paginator<types::MessageList> {
        let parts = RequestParts::new(Method::Get, "/v1/messages")
            .query_opt("accountId", params.account_id.as_ref())
            .query_opt("chatId", params.chat_id.as_ref())
            .query_opt("direction", params.direction.as_ref())
            .query_opt("limit", params.limit.as_ref())
            .query_opt("projectId", params.project_id.as_ref())
            .retryable();
        Paginator::new(self.http.clone(), parts, "cursor", params.cursor)
    }

    /// Get a message
    ///
    /// A message and its current status.
    ///
    /// `GET /v1/messages/{messageId}`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn get(&self, message_id: &str) -> Request<types::Message> {
        let parts = RequestParts::new(Method::Get, format!("/v1/messages/{}", encode_path(message_id)))
            .retryable();
        self.http.request(parts)
    }

    /// Get a message's media
    ///
    /// The message's file. By default the answer is `302 Found` to the file (no API key needed there), so `curl -L`, browsers and HTTP clients download it directly. With `redirect=false`, or an `Accept` header that names only `application/json` (the SDKs), the answer is this JSON with the file's URL instead.
    ///
    /// A received file still on WhatsApp (`media.downloaded: false`, on-demand media) is downloaded first, once, through the number's proxy, and kept: later requests are served from storage. Concurrent requests for the same file wait for that one download. WhatsApp keeps files for a limited time (about two weeks), after which the answer is `410 media_expired`. The account must be `ready` for a first download.
    ///
    /// `GET /v1/messages/{messageId}/media`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn get_media(
        &self,
        message_id: &str,
        params: types::MessagesGetMediaParams,
    ) -> Request<types::MessageMediaFile> {
        let parts = RequestParts::new(Method::Get, format!("/v1/messages/{}/media", encode_path(message_id)))
            .query_opt("redirect", params.redirect.as_ref())
            .retryable();
        self.http.request(parts)
    }

    /// Edit a message
    ///
    /// Outbound text messages only, within WhatsApp's edit window (about 15 minutes; WhatsApp's refusal is returned as is). Fires `message.edited`.
    ///
    /// A text message still `queued` (never sent) is sent with the new text instead: `editedAt` stays `null` and `message.edited` does not fire. While a queued message is being handed to WhatsApp this answers `409 message_sending` for a few seconds.
    ///
    /// `PATCH /v1/messages/{messageId}`
    ///
    /// Not idempotent: retried only when the request never reached the API or was refused with `429`.
    pub fn edit(
        &self,
        message_id: &str,
        params: types::MessagesEditParams,
    ) -> Request<types::Message> {
        let parts = RequestParts::new(Method::Patch, format!("/v1/messages/{}", encode_path(message_id)))
            .body(&params);
        self.http.request(parts)
    }

    /// Delete a message
    ///
    /// Outbound messages only. For everyone by default: the row stays with `deletedAt` set and its content cleared, and `message.deleted` fires.
    ///
    /// A message still `queued` (never sent) is cancelled instead: it never goes out, it ends `failed` with `error.code: cancelled`, and `message.failed` fires. While a queued message is being handed to WhatsApp this answers `409 message_sending` for a few seconds.
    ///
    /// `DELETE /v1/messages/{messageId}`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn delete(&self, message_id: &str, params: types::MessagesDeleteParams) -> Request<()> {
        let parts = RequestParts::new(Method::Delete, format!("/v1/messages/{}", encode_path(message_id)))
            .query_opt("forEveryone", params.for_everyone.as_ref())
            .retryable()
            .no_content();
        self.http.request(parts)
    }

    /// React to a message
    ///
    /// An empty `emoji` removes the reaction.
    ///
    /// `POST /v1/messages/{messageId}/react`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn react(&self, message_id: &str, params: types::MessagesReactParams) -> Request<()> {
        let parts = RequestParts::new(Method::Post, format!("/v1/messages/{}/react", encode_path(message_id)))
            .body(&params)
            .keyed()
            .no_content();
        self.http.request(parts)
    }

    /// Vote in a poll
    ///
    /// Options are validated against the stored poll. Returns the poll with its tally, your vote included.
    ///
    /// `POST /v1/messages/{messageId}/vote`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn vote(
        &self,
        message_id: &str,
        params: types::MessagesVoteParams,
    ) -> Request<types::Message> {
        let parts = RequestParts::new(Method::Post, format!("/v1/messages/{}/vote", encode_path(message_id)))
            .body(&params)
            .keyed();
        self.http.request(parts)
    }

    /// Forward a message
    ///
    /// Forward a message wuapi stores (received, sent through the API or sent from the phone) to one or several chats of the same account, the way WhatsApp forwards: the recipients get the original content with the "Forwarded" label, and "Forwarded many times" once it went through five forwards.
    ///
    /// You send no content and no bytes. Text (with its link preview when wuapi stored one), images, videos, GIFs, audio, voice notes (they stay voice notes), documents, stickers, locations and contact cards are forwarded, captions included. Media is not downloaded or uploaded again while WhatsApp still serves the original file: the new message names the same file. When it no longer does, wuapi uploads its stored copy, or fetches the file from WhatsApp first when it never stored it. Nothing of the original's context travels: no reply quote, no mentions, no disappearing timer.
    ///
    /// The answer is a list with one `queued` message per chat, in the order of `to`, each an ordinary message from there on: `forwarded: true`, its own id, the same outcome events (`message.sent`, `message.delivered`, `message.read`, `message.failed`), the same pacing, queue timeout and offline tolerance as `POST /v1/messages`, and it counts as one sent message each. The request is all or nothing: a refusal queues no message. What can still go wrong per chat (a recipient without WhatsApp, an account that stays offline) is that message's own `failed` status and `error`.
    ///
    /// Send `Idempotency-Key`. A repeated request answers the stored response; if the first one never completed, the key also identifies each chat's message, so the retry returns the messages already queued and queues only the missing ones. A chat is never forwarded to twice.
    ///
    /// Polls, calendar events, reactions, view-once and deleted messages answer `400 not_forwardable`. So does a contact's story (`details.reason: story`): its id is a story id, and WhatsApp forwards only the stories the account posted, which are messages and forward like any other. Reply to a contact's story with `replyToStoryId` on `POST /v1/messages` instead. `to` takes at most 5 chats (WhatsApp's limit per forward), and exactly 1 when the message is `forwardedManyTimes`. To label content of your own as forwarded, send it with `POST /v1/messages` and `forwarded: true` instead.
    ///
    /// `POST /v1/messages/{messageId}/forward`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn forward(
        &self,
        message_id: &str,
        params: types::MessagesForwardParams,
    ) -> Request<types::MessageList> {
        let parts = RequestParts::new(Method::Post, format!("/v1/messages/{}/forward", encode_path(message_id)))
            .body(&params)
            .keyed();
        self.http.request(parts)
    }

    /// Star a message
    ///
    /// Star the message on the phone and other devices.
    ///
    /// `POST /v1/messages/{messageId}/star`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn star(&self, message_id: &str) -> Request<types::Message> {
        let parts = RequestParts::new(Method::Post, format!("/v1/messages/{}/star", encode_path(message_id)))
            .keyed();
        self.http.request(parts)
    }

    /// Unstar a message
    ///
    /// Remove the star.
    ///
    /// `POST /v1/messages/{messageId}/unstar`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn unstar(&self, message_id: &str) -> Request<types::Message> {
        let parts = RequestParts::new(Method::Post, format!("/v1/messages/{}/unstar", encode_path(message_id)))
            .keyed();
        self.http.request(parts)
    }

    /// Label a message
    ///
    /// WhatsApp Business accounts only. The message must have reached WhatsApp and not be deleted.
    ///
    /// `POST /v1/messages/{messageId}/labels`
    ///
    /// Sends `Idempotency-Key` (a random key, or your own with `.idempotency_key(..)`), so it is retried on timeouts, network errors, `429` and `5xx` without repeating its effect.
    pub fn add_label(
        &self,
        message_id: &str,
        params: types::MessagesAddLabelParams,
    ) -> Request<()> {
        let parts = RequestParts::new(Method::Post, format!("/v1/messages/{}/labels", encode_path(message_id)))
            .body(&params)
            .keyed()
            .no_content();
        self.http.request(parts)
    }

    /// Remove a label from a message
    ///
    /// WhatsApp Business accounts only.
    ///
    /// `DELETE /v1/messages/{messageId}/labels/{labelId}`
    ///
    /// Safe to repeat: retried on timeouts, network errors, `429` and `5xx`.
    pub fn remove_label(&self, message_id: &str, label_id: &str) -> Request<()> {
        let parts = RequestParts::new(Method::Delete, format!("/v1/messages/{}/labels/{}", encode_path(message_id), encode_path(label_id)))
            .retryable()
            .no_content();
        self.http.request(parts)
    }
}