Skip to main content

whatsrook_sdk/
lib.rs

1//! # whatsrook-sdk
2//!
3//! Rust SDK for building [WhatsRook](https://github.com/Thruqe/whatsrook) external plugins.
4//!
5//! External plugins are standalone executables — written in any language — that WhatsRook
6//! spawns as child processes. This crate provides everything a Rust plugin author needs:
7//!
8//! - **[`Request`]** — deserializes the incoming JSON payload from `stdin`.
9//! - **[`Action`]** — typed, serializable frames for every response the protocol supports.
10//! - **High-level helpers** — `send_reply_live`, `send_image`, `send_poll`, etc.
11//! - **[`create_http_client`]** — preconfigured blocking HTTP client.
12//!
13//! ## Communication Protocol
14//!
15//! WhatsRook writes one JSON line to the plugin's `stdin` when a command is triggered.
16//! The plugin reads it, does its work, and writes newline-delimited JSON *action frames*
17//! to `stdout`. WhatsRook executes each frame and, for actions that return a message ID,
18//! writes an [`Ack`] back to the plugin's `stdin`.
19//!
20//! ```text
21//! WhatsRook  ──stdin──▶  plugin (reads Request)
22//! plugin     ──stdout─▶  WhatsRook (reads Action frames)
23//! WhatsRook  ──stdin──▶  plugin (reads Ack, for live actions)
24//! ```
25//!
26//! ## Quick Start
27//!
28//! ```no_run
29//! use whatsrook_sdk::{respond, Request};
30//!
31//! fn main() {
32//!     let req = Request::load();
33//!     let query = req.query();
34//!
35//!     if query.is_empty() {
36//!         respond("Usage: .hello <name>");
37//!         return;
38//!     }
39//!
40//!     respond(format!("Hello, {}! 👋", query));
41//! }
42//! ```
43//!
44//! See the [`examples/`](https://github.com/Thruqe/whatsrook-sdk/tree/master/examples) directory
45//! for more complete plugin examples.
46
47use serde::{Deserialize, Serialize};
48use std::io::{self, BufRead, IsTerminal, Write};
49use std::time::Duration;
50
51pub use reqwest;
52pub use reqwest::blocking::Client as HttpClient;
53
54/// Default browser User-Agent used by [`create_http_client`].
55pub const DEFAULT_USER_AGENT: &str =
56    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36";
57
58// ─── Request ─────────────────────────────────────────────────────────────────
59
60/// Quoted message context payload — the message the user was replying to.
61#[derive(Debug, Clone, Serialize, Deserialize, Default)]
62pub struct QuotedMessage {
63    /// WhatsApp message ID of the quoted message.
64    #[serde(default)]
65    pub id: String,
66    /// JID of the sender of the quoted message.
67    #[serde(default)]
68    pub sender: String,
69    /// Text content of the quoted message.
70    #[serde(default)]
71    pub text: String,
72}
73
74/// Incoming request payload written by WhatsRook to the plugin's `stdin`.
75///
76/// Load it at the start of `main` with [`Request::load`]:
77///
78/// ```no_run
79/// use whatsrook_sdk::Request;
80///
81/// fn main() {
82///     let req = Request::load();
83///     println!("command: {}", req.command);
84///     println!("args: {:?}", req.args);
85/// }
86/// ```
87#[derive(Debug, Clone, Serialize, Deserialize, Default)]
88pub struct Request {
89    /// The installed plugin command name (e.g. `"weather"`).
90    #[serde(default)]
91    pub command: String,
92    /// Whitespace-split arguments following the command.
93    #[serde(default)]
94    pub args: Vec<String>,
95    /// Full unparsed argument string following the command.
96    #[serde(default)]
97    pub raw_args: String,
98    /// JID of the WhatsApp chat where the command was triggered.
99    #[serde(default)]
100    pub chat: String,
101    /// JID of the user who triggered the command.
102    #[serde(default)]
103    pub sender: String,
104    /// The bot's active command prefix (e.g. `"."` or `"/"`).
105    #[serde(default)]
106    pub prefix: String,
107    /// The configured bot display name.
108    #[serde(default)]
109    pub bot_name: String,
110    /// The WhatsApp push name (display name) of the sender.
111    #[serde(default)]
112    pub push_name: String,
113    /// `true` if the command was triggered inside a group chat.
114    #[serde(default)]
115    pub is_group: bool,
116    /// `true` if the sender is in the bot's sudoers list or is the owner.
117    #[serde(default)]
118    pub is_sudo: bool,
119    /// `true` if the sender is the primary bot owner.
120    #[serde(default)]
121    pub is_owner: bool,
122    /// `true` if the sender is a group admin in the triggering chat.
123    #[serde(default)]
124    pub is_admin: bool,
125    /// `true` if a live session is already active for this plugin in this chat.
126    #[serde(default)]
127    pub live_session: bool,
128    /// `true` if the user is requesting cancellation of an active live session.
129    #[serde(default)]
130    pub is_cancel_request: bool,
131    /// Quoted message context, present only when the triggering message is a reply.
132    #[serde(default)]
133    pub quoted_message: Option<QuotedMessage>,
134    /// JIDs of users mentioned in the triggering message.
135    #[serde(default)]
136    pub mentioned_jids: Vec<String>,
137}
138
139impl Request {
140    /// Loads the plugin request from `stdin` (first line as JSON).
141    ///
142    /// When `stdin` is not a terminal (i.e. the plugin is invoked by WhatsRook),
143    /// the first line is read and parsed as the JSON payload. If reading or
144    /// parsing fails, or if `stdin` is a terminal (direct invocation), the
145    /// function falls back to building a minimal [`Request`] from CLI arguments,
146    /// which is useful for local development and testing.
147    ///
148    /// # Example
149    ///
150    /// ```no_run
151    /// use whatsrook_sdk::Request;
152    ///
153    /// fn main() {
154    ///     let req = Request::load();
155    ///     println!("query: {}", req.query());
156    /// }
157    /// ```
158    pub fn load() -> Self {
159        if !io::stdin().is_terminal() {
160            let stdin = io::stdin();
161            let mut line = String::new();
162            if stdin.lock().read_line(&mut line).is_ok() && !line.trim().is_empty() {
163                if let Ok(req) = serde_json::from_str::<Request>(line.trim()) {
164                    if !req.command.is_empty()
165                        || !req.args.is_empty()
166                        || !req.raw_args.is_empty()
167                        || !req.chat.is_empty()
168                    {
169                        return req;
170                    }
171                }
172            }
173        }
174
175        // Fallback: build a minimal request from CLI args for local testing.
176        let cli_args: Vec<String> = std::env::args().collect();
177        let command = cli_args
178            .first()
179            .and_then(|p| std::path::Path::new(p).file_name()?.to_str())
180            .unwrap_or("plugin")
181            .to_string();
182        let args = if cli_args.len() > 1 {
183            cli_args[1..].to_vec()
184        } else {
185            Vec::new()
186        };
187        let raw_args = args.join(" ");
188        Request {
189            command,
190            args,
191            raw_args,
192            chat: String::new(),
193            sender: String::new(),
194            prefix: String::from("."),
195            bot_name: String::from("WhatsRook"),
196            push_name: String::new(),
197            is_group: false,
198            is_sudo: false,
199            is_owner: false,
200            is_admin: false,
201            live_session: false,
202            is_cancel_request: false,
203            quoted_message: None,
204            mentioned_jids: Vec::new(),
205        }
206    }
207
208    /// Alias for [`load`](Request::load) — loads the request from `stdin`.
209    ///
210    /// Useful in streaming / live-session plugin contexts to make the intent explicit.
211    pub fn load_streaming() -> Self {
212        Self::load()
213    }
214
215    /// Returns the trimmed `raw_args` string, falling back to joining `args` with spaces.
216    ///
217    /// This is the primary way to get the user's input to a plugin:
218    ///
219    /// ```no_run
220    /// use whatsrook_sdk::Request;
221    ///
222    /// fn main() {
223    ///     let req = Request::load();
224    ///     let q = req.query();
225    ///     if q.is_empty() {
226    ///         whatsrook_sdk::respond("Usage: .myplugin <query>");
227    ///         return;
228    ///     }
229    ///     whatsrook_sdk::respond(format!("You said: {}", q));
230    /// }
231    /// ```
232    pub fn query(&self) -> String {
233        let trimmed = self.raw_args.trim();
234        if !trimmed.is_empty() {
235            trimmed.to_string()
236        } else {
237            self.args.join(" ").trim().to_string()
238        }
239    }
240
241    /// Returns the effective command prefix. Falls back to `"."` if the field is empty.
242    pub fn prefix(&self) -> &str {
243        if self.prefix.is_empty() {
244            "."
245        } else {
246            &self.prefix
247        }
248    }
249
250    /// Returns the bot display name. Falls back to `"WhatsRook"` if the field is empty.
251    pub fn bot_name(&self) -> &str {
252        if self.bot_name.is_empty() {
253            "WhatsRook"
254        } else {
255            &self.bot_name
256        }
257    }
258
259    /// Returns the sender's WhatsApp push name. Falls back to `"User"` if empty.
260    pub fn push_name(&self) -> &str {
261        if self.push_name.is_empty() {
262            "User"
263        } else {
264            &self.push_name
265        }
266    }
267
268    /// Returns the text of the quoted message, if present.
269    pub fn quoted_text(&self) -> Option<&str> {
270        self.quoted_message.as_ref().map(|q| q.text.as_str())
271    }
272
273    /// Returns the JID of the sender of the quoted message, if present.
274    pub fn quoted_sender(&self) -> Option<&str> {
275        self.quoted_message.as_ref().map(|q| q.sender.as_str())
276    }
277
278    /// Returns the message ID of the quoted message, if present.
279    pub fn quoted_id(&self) -> Option<&str> {
280        self.quoted_message.as_ref().map(|q| q.id.as_str())
281    }
282
283    /// Returns `true` if the command was triggered inside a group chat.
284    pub fn is_group(&self) -> bool {
285        self.is_group
286    }
287
288    /// Returns `true` if the sender is a sudo user or the bot owner.
289    pub fn is_sudo(&self) -> bool {
290        self.is_sudo
291    }
292
293    /// Returns `true` if the sender is the primary bot owner.
294    pub fn is_owner(&self) -> bool {
295        self.is_owner
296    }
297
298    /// Returns `true` if the sender is a group admin in the triggering chat.
299    pub fn is_admin(&self) -> bool {
300        self.is_admin
301    }
302}
303
304// ─── Action Protocol ──────────────────────────────────────────────────────────
305
306/// A single action frame written to `stdout` for WhatsRook to execute.
307///
308/// Use [`send_action`] to serialize and flush a frame, or use the high-level
309/// helpers (`send_reply_live`, `send_image`, `send_poll`, etc.) which call it
310/// internally.
311///
312/// # Wire Format
313///
314/// Each variant is serialized as a JSON object with an `"action"` field that
315/// identifies the type (snake_case), plus any variant-specific fields:
316///
317/// ```json
318/// { "action": "reply", "text": "Hello world" }
319/// { "action": "send_image", "data": "https://example.com/img.png", "caption": "Look!" }
320/// { "action": "done" }
321/// ```
322#[derive(Debug, Serialize)]
323#[serde(tag = "action", rename_all = "snake_case")]
324pub enum Action<'a> {
325    /// Send a text reply.
326    ///
327    /// WhatsRook sends back an [`Ack`] on `stdin` with the `msg_id` of the sent
328    /// message, which can be used for subsequent [`Edit`](Action::Edit) frames.
329    Reply { text: &'a str },
330
331    /// Edit an existing message by its ID, replacing the text in-place.
332    ///
333    /// Requires the `msg_id` returned by a prior [`Reply`](Action::Reply) ack.
334    Edit { msg_id: &'a str, text: &'a str },
335
336    /// React to the triggering message (or a specific message) with an emoji.
337    ///
338    /// Omitting `msg_id` reacts to the command message that triggered the plugin.
339    React {
340        /// Target message ID. `None` reacts to the triggering message.
341        #[serde(skip_serializing_if = "Option::is_none")]
342        msg_id: Option<&'a str>,
343        /// Emoji character to react with (e.g. `"🔥"`).
344        emoji: &'a str,
345    },
346
347    /// Revoke (delete for everyone) a message by its ID.
348    Delete { msg_id: &'a str },
349
350    /// Send an image from a base64-encoded string or an HTTP/HTTPS URL.
351    SendImage {
352        /// Image data — base64 string or a URL.
353        data: &'a str,
354        /// Optional caption displayed below the image.
355        #[serde(skip_serializing_if = "Option::is_none")]
356        caption: Option<&'a str>,
357        /// Optional MIME type override (e.g. `"image/webp"`).
358        #[serde(skip_serializing_if = "Option::is_none")]
359        mimetype: Option<&'a str>,
360    },
361
362    /// Send audio or a voice note (PTT) from a base64-encoded string or a URL.
363    SendAudio {
364        /// Audio data — base64 string or a URL.
365        data: &'a str,
366        /// Optional MIME type override (e.g. `"audio/ogg; codecs=opus"`).
367        #[serde(skip_serializing_if = "Option::is_none")]
368        mimetype: Option<&'a str>,
369        /// `true` to send as a push-to-talk voice note.
370        #[serde(default)]
371        ptt: bool,
372    },
373
374    /// Send a video or looping GIF from a base64-encoded string or a URL.
375    SendVideo {
376        /// Video data — base64 string or a URL.
377        data: &'a str,
378        /// Optional caption displayed below the video.
379        #[serde(skip_serializing_if = "Option::is_none")]
380        caption: Option<&'a str>,
381        /// Optional MIME type override.
382        #[serde(skip_serializing_if = "Option::is_none")]
383        mimetype: Option<&'a str>,
384        /// `true` to render the video as a looping GIF.
385        #[serde(default)]
386        gif_playback: bool,
387    },
388
389    /// Send a document file from a base64-encoded string or a URL.
390    SendDocument {
391        /// Document data — base64 string or a URL.
392        data: &'a str,
393        /// Filename shown in the WhatsApp document message (e.g. `"report.pdf"`).
394        #[serde(skip_serializing_if = "Option::is_none")]
395        filename: Option<&'a str>,
396        /// Optional caption displayed below the document.
397        #[serde(skip_serializing_if = "Option::is_none")]
398        caption: Option<&'a str>,
399        /// Optional MIME type override.
400        #[serde(skip_serializing_if = "Option::is_none")]
401        mimetype: Option<&'a str>,
402    },
403
404    /// Send a WebP sticker from a base64-encoded string or a URL.
405    SendSticker {
406        /// Sticker data — base64 string or a URL to a `.webp` file.
407        data: &'a str,
408    },
409
410    /// Send an interactive poll.
411    Poll {
412        /// The poll question shown to participants.
413        question: &'a str,
414        /// The list of answer options. Maximum of 12 options.
415        options: &'a [&'a str],
416        /// Number of options a participant may select (`1` = single-select).
417        #[serde(default)]
418        selectable: usize,
419    },
420
421    /// Show or update the typing / processing loader indicator.
422    ///
423    /// Pass `None` to show a generic loader, or `Some(text)` for a status message.
424    Loader {
425        /// Optional status text shown alongside the indicator.
426        #[serde(skip_serializing_if = "Option::is_none")]
427        text: Option<&'a str>,
428    },
429
430    /// Signal that the plugin has finished all work and the session is complete.
431    ///
432    /// Always send this as the last frame of a live session.
433    Done,
434}
435
436/// Acknowledgement sent by WhatsRook on `stdin` following actions that return a message ID.
437///
438/// Currently returned after [`Action::Reply`]. Read it with [`await_ack`].
439#[derive(Debug, Deserialize)]
440pub struct Ack {
441    /// `true` if the action succeeded.
442    pub ok: bool,
443    /// The message ID of the sent message. Present when `ok` is `true`.
444    pub msg_id: Option<String>,
445    /// Human-readable error description. Present when `ok` is `false`.
446    pub error: Option<String>,
447}
448
449// ─── Low-Level I/O ───────────────────────────────────────────────────────────
450
451/// Serialize an [`Action`] frame to `stdout` and flush immediately.
452///
453/// Each frame is a single JSON line followed by a newline character. WhatsRook
454/// reads frames as they arrive, so flushing after each write is essential for
455/// correct live-session behavior.
456///
457/// Prefer the high-level helpers (`send_reply_live`, `send_image`, etc.) over
458/// calling this function directly unless you need fine-grained control.
459pub fn send_action(action: &Action) {
460    let json = serde_json::to_string(action).unwrap_or_default();
461    let stdout = io::stdout();
462    let mut handle = stdout.lock();
463    let _ = writeln!(handle, "{}", json);
464    let _ = handle.flush();
465}
466
467/// Read one [`Ack`] line from `stdin`. Returns `None` on EOF or parse error.
468///
469/// Call this immediately after [`send_reply_live`] (which calls it internally)
470/// when you need the raw `Ack` for error inspection. In most cases the
471/// high-level helpers handle the round-trip for you.
472pub fn await_ack() -> Option<Ack> {
473    let stdin = io::stdin();
474    let mut line = String::new();
475    stdin.lock().read_line(&mut line).ok()?;
476    serde_json::from_str(line.trim()).ok()
477}
478
479// ─── High-Level Action Helpers ────────────────────────────────────────────────
480
481/// Send a text `reply` action, await the acknowledgement, and return the
482/// `msg_id` on success.
483///
484/// The returned `msg_id` is required for subsequent in-place edits via
485/// [`send_edit_live`]. Returns `None` if the reply failed or the ACK could
486/// not be read.
487///
488/// # Example
489///
490/// ```no_run
491/// use whatsrook_sdk::{send_edit_live, send_reply_live};
492///
493/// fn main() {
494///     if let Some(msg_id) = send_reply_live("⏳ Processing...") {
495///         // ... do work ...
496///         send_edit_live(&msg_id, "✅ Done!");
497///     }
498/// }
499/// ```
500pub fn send_reply_live(text: &str) -> Option<String> {
501    send_action(&Action::Reply { text });
502    let ack = await_ack()?;
503    if ack.ok { ack.msg_id } else { None }
504}
505
506/// Send an `edit` frame to update a previously sent message in-place.
507///
508/// `msg_id` must be a value returned by [`send_reply_live`].
509pub fn send_edit_live(msg_id: &str, text: &str) {
510    send_action(&Action::Edit { msg_id, text });
511}
512
513/// React to the triggering message with an emoji.
514///
515/// # Example
516///
517/// ```no_run
518/// whatsrook_sdk::send_react("🚀");
519/// ```
520pub fn send_react(emoji: &str) {
521    send_action(&Action::React { msg_id: None, emoji });
522}
523
524/// Revoke (delete for everyone) a message by its ID.
525pub fn send_delete(msg_id: &str) {
526    send_action(&Action::Delete { msg_id });
527}
528
529/// Send an image from a URL or base64-encoded data with an optional caption.
530///
531/// # Example
532///
533/// ```no_run
534/// whatsrook_sdk::send_image("https://example.com/chart.png", Some("📊 Market chart"));
535/// ```
536pub fn send_image(data_or_url: &str, caption: Option<&str>) {
537    send_action(&Action::SendImage {
538        data: data_or_url,
539        caption,
540        mimetype: None,
541    });
542}
543
544/// Send audio or a voice note (PTT) from a URL or base64-encoded data.
545///
546/// Set `is_ptt` to `true` to render the message as a push-to-talk voice note
547/// instead of a standard audio attachment.
548pub fn send_audio(data_or_url: &str, is_ptt: bool) {
549    send_action(&Action::SendAudio {
550        data: data_or_url,
551        mimetype: None,
552        ptt: is_ptt,
553    });
554}
555
556/// Send a video from a URL or base64-encoded data with an optional caption.
557pub fn send_video(data_or_url: &str, caption: Option<&str>) {
558    send_action(&Action::SendVideo {
559        data: data_or_url,
560        caption,
561        mimetype: None,
562        gif_playback: false,
563    });
564}
565
566/// Send a GIF (looping video) from a URL or base64-encoded data.
567pub fn send_gif(data_or_url: &str, caption: Option<&str>) {
568    send_action(&Action::SendVideo {
569        data: data_or_url,
570        caption,
571        mimetype: None,
572        gif_playback: true,
573    });
574}
575
576/// Send a document file from a URL or base64-encoded data.
577///
578/// `filename` is the name shown in the WhatsApp document bubble (e.g. `"report.pdf"`).
579pub fn send_document(data_or_url: &str, filename: &str, caption: Option<&str>) {
580    send_action(&Action::SendDocument {
581        data: data_or_url,
582        filename: Some(filename),
583        caption,
584        mimetype: None,
585    });
586}
587
588/// Send a WebP sticker from a URL or base64-encoded data.
589pub fn send_sticker(data_or_url: &str) {
590    send_action(&Action::SendSticker { data: data_or_url });
591}
592
593/// Send an interactive single-select poll.
594///
595/// # Example
596///
597/// ```no_run
598/// whatsrook_sdk::send_poll("Which network?", &["Bitcoin", "Ethereum", "Solana"]);
599/// ```
600pub fn send_poll(question: &str, options: &[&str]) {
601    send_action(&Action::Poll {
602        question,
603        options,
604        selectable: 1,
605    });
606}
607
608/// Show the typing / processing loader indicator with an optional status message.
609///
610/// Call this before starting a long-running operation to give the user
611/// immediate feedback that the plugin is working.
612///
613/// # Example
614///
615/// ```no_run
616/// whatsrook_sdk::send_loader(Some("Fetching data..."));
617/// // ... long operation ...
618/// whatsrook_sdk::send_done();
619/// ```
620pub fn send_loader(text: Option<&str>) {
621    send_action(&Action::Loader { text });
622}
623
624/// Signal that the plugin session is complete.
625///
626/// Always send this as the final frame in a live session so WhatsRook can
627/// clean up session state for the chat.
628pub fn send_done() {
629    send_action(&Action::Done);
630}
631
632// ─── Simple Mode ─────────────────────────────────────────────────────────────
633
634/// Send a plain-text response to WhatsRook via `stdout` (simple mode).
635///
636/// Simple mode is the easiest output method: write a single string to `stdout`
637/// and WhatsRook sends it as a text message. No JSON framing is required.
638///
639/// Do **not** mix simple-mode output (`respond`) with action-frame output
640/// (`send_action` / `send_reply_live`) in the same plugin run.
641///
642/// # Example
643///
644/// ```no_run
645/// use whatsrook_sdk::{respond, Request};
646///
647/// fn main() {
648///     let req = Request::load();
649///     respond(format!("Hello, {}!", req.push_name()));
650/// }
651/// ```
652pub fn respond(output: impl AsRef<str>) {
653    print!("{}", output.as_ref().trim());
654}
655
656/// Send an error message to `stderr` (for logs) and `stdout` (to reply to the user),
657/// then exit the process with code `1`.
658///
659/// # Panics / Exits
660///
661/// This function **never returns** — it always calls [`std::process::exit`] with code `1`.
662pub fn respond_err(error_msg: impl AsRef<str>) -> ! {
663    eprintln!("{}", error_msg.as_ref());
664    print!("{}", error_msg.as_ref().trim());
665    std::process::exit(1)
666}
667
668// ─── HTTP Client ──────────────────────────────────────────────────────────────
669
670/// Build a preconfigured blocking [`HttpClient`] with a timeout and standard browser headers.
671///
672/// The client uses `rustls` for TLS and sets a browser-like `User-Agent` by default.
673/// Most external plugins that make HTTP requests should use this instead of
674/// constructing their own client.
675///
676/// # Arguments
677///
678/// * `timeout_secs` — maximum time in seconds for a single HTTP request to complete.
679///
680/// # Example
681///
682/// ```no_run
683/// let client = whatsrook_sdk::create_http_client(10);
684/// let body = client.get("https://api.example.com/data").send()?.text()?;
685/// # Ok::<(), Box<dyn std::error::Error>>(())
686/// ```
687pub fn create_http_client(timeout_secs: u64) -> reqwest::blocking::Client {
688    reqwest::blocking::Client::builder()
689        .user_agent(DEFAULT_USER_AGENT)
690        .timeout(Duration::from_secs(timeout_secs))
691        .build()
692        .unwrap_or_default()
693}