Basic example
Here’s a minimal bot that responds to “ping” messages:src/main.rs
Step-by-step breakdown
1
Set up the storage backend
The bot needs persistent storage for session data, keys, and state:This creates a SQLite database file named
whatsapp.db in your current directory. The session will persist across restarts.2
Configure the bot builder
The
Bot::builder() pattern lets you configure all required components:All four components (backend, transport, HTTP client, runtime) are required. The builder uses a typestate pattern — your code won’t compile if any are missing.
3
Handle events
Use The event handler receives two parameters:
.on_event() to handle incoming events from WhatsApp:event: AnArc<Event>— use&*eventorevent.as_ref()to pattern-match on the inner event typeclient: AnArc<Client>you can use to send messages or call API methods
4
Build and run the bot
Build the bot and start the event loop:The double
.await? is intentional:- First
.await?starts the bot and returns aBotHandle - Second
.await?waits for the bot to finish running
Responding to messages
Let’s extend the bot to respond to “ping” with “pong”:Key methods
msg.text_content()- Extract text from any message type (conversation, extended text, etc.)client.send_message()- Send a message to a chatinfo.source.chat- The JID (identifier) of the chat where the message came frominfo.source.sender- The JID of the user who sent the message
Authentication methods
QR code pairing (default)
The bot automatically generates QR codes when not authenticated. Scan with your phone to link:Pair code (phone number)
Alternatively, link using a phone number and 8-digit code:PairCodeOptions derives companion_platform_id and companion_platform_display from the device’s PlatformType by default (Chrome with Chrome (Linux) for the stock web profile). You can override the wire id when needed:
platform_id accepts the CompanionWebClientType wire enum (single-byte ASCII ids). The display string is always derived — there is no separate platform_display field.Pair code and QR code authentication run concurrently. Whichever method completes first will be used.
Running the bot
1
First run - Authentication
On the first run, the bot will generate a QR code:Scan the QR code with WhatsApp on your phone:
- Open WhatsApp on your phone
- Go to Settings → Linked Devices
- Tap “Link a Device”
- Scan the QR code displayed in your terminal
2
Subsequent runs - Auto-login
After pairing, the session is saved. The bot will automatically reconnect:You should see:
3
Test the bot
Send “ping” to your bot from any WhatsApp chat. It should reply with “pong”!
Demo binary CLI flags
The repository includes a demo bot binary (src/main.rs) that supports CLI arguments for authentication:
🦀ping with a quoted 🏓 Pong! reply, edits the reply to append the send latency, and supports media ping/pong via CDN reuse.
Using MessageContext
For cleaner message handling, useMessageContext to wrap the message, metadata, and client together. This provides convenience methods like send_message (auto-targets the source chat), build_quote_context, edit_message, and revoke_message:
Media forwarding with CDN reuse
You can also forward media instantly by reusing the original CDN fields — no download or re-upload needed:Complete example with logging
Here’s a production-ready example with proper logging, reactions, message editing, and media CDN reuse:src/main.rs
Configuring log targets
whatsapp-rust uses thelog crate with module-specific targets for fine-grained filtering. You can use RUST_LOG to control which components emit log output.
Available log targets
Filtering examples
During shutdown or disconnect, the client automatically downgrades sync errors from
error to debug level to reduce noise. This means you won’t see spurious error logs when the client is intentionally disconnecting.Running with Docker
You can also run the bot using Docker instead of compiling locally:/data directory inside the container. Mount a volume to persist it across restarts. The container shuts down gracefully on docker stop — the bot disconnects cleanly from WhatsApp before exiting. See the installation guide for more details.
Benchmarking
The repository includes a benchmark example atexamples/benchmark.rs that you can use for quick integration-level performance testing. It uses an in-memory backend and supports a custom WebSocket URL via the WHATSAPP_WS_URL environment variable:
The benchmark example requires the
danger-skip-tls-verify feature flag because it’s designed for use with local test servers.bench-integration test suite measures real-world scenarios (connect, send, receive, reconnect) and reports wall-clock time plus heap allocation counts per operation:
wacore crate includes an iai-callgrind benchmark suite that measures instruction counts for the full send/receive pipeline (DM and group messaging with various participant counts), binary protocol encoding, Signal Protocol operations, and reporting token generation:
Next steps
Sending messages
Learn about different message types and how to send them
Media handling
Upload and download images, videos, and documents
Group management
Create and manage WhatsApp groups
Client API reference
Explore all available client methods