pub struct Client {
pub group_cache: Mutex<Option<Arc<TypedCache<Jid, GroupInfo>>>>,
pub device_cache: Mutex<Option<Arc<TypedCache<Jid, Vec<Jid>>>>>,
pub enable_auto_reconnect: Arc<AtomicBool>,
pub auto_reconnect_errors: Arc<AtomicU32>,
pub custom_enc_handlers: Arc<RwLock<HashMap<String, Arc<dyn EncHandler>>>>,
pub http_client: Arc<dyn HttpClient>,
/* private fields */
}Fields§
§group_cache: Mutex<Option<Arc<TypedCache<Jid, GroupInfo>>>>§device_cache: Mutex<Option<Arc<TypedCache<Jid, Vec<Jid>>>>>§enable_auto_reconnect: Arc<AtomicBool>§auto_reconnect_errors: Arc<AtomicU32>§custom_enc_handlers: Arc<RwLock<HashMap<String, Arc<dyn EncHandler>>>>Custom handlers for encrypted message types
http_client: Arc<dyn HttpClient>HTTP client for making HTTP requests (media upload/download, version fetching)
Implementations§
Source§impl Client
impl Client
Sourcepub const RECONNECT_BACKOFF_STEP: u32 = 4
pub const RECONNECT_BACKOFF_STEP: u32 = 4
Backoff step used by [reconnect()] to create an offline window.
fibonacci_backoff(RECONNECT_BACKOFF_STEP) determines the delay before
the run loop re-connects. This must be longer than the mock server’s
chatstate TTL (CHATSTATE_TTL_SECS=3) so TTL-expiry tests pass.
Sequence: fib(0)=1s, fib(1)=1s, fib(2)=2s, fib(3)=3s, fib(4)=5s.
Sourcepub fn set_skip_history_sync(&self, enabled: bool)
pub fn set_skip_history_sync(&self, enabled: bool)
Enable or disable skipping of history sync notifications at runtime.
When enabled, the client will acknowledge incoming history sync notifications but will not download or process the data.
Sourcepub async fn process_sync_task(self: &Arc<Self>, task: MajorSyncTask)
pub async fn process_sync_task(self: &Arc<Self>, task: MajorSyncTask)
Public entry point for processing MajorSyncTask from the sync channel.
Sourcepub fn skip_history_sync_enabled(&self) -> bool
pub fn skip_history_sync_enabled(&self) -> bool
Returns true if history sync notifications are currently being skipped.
Sourcepub async fn new(
runtime: Arc<dyn Runtime>,
persistence_manager: Arc<PersistenceManager>,
transport_factory: Arc<dyn TransportFactory>,
http_client: Arc<dyn HttpClient>,
override_version: Option<(u32, u32, u32)>,
) -> (Arc<Self>, Receiver<MajorSyncTask>)
pub async fn new( runtime: Arc<dyn Runtime>, persistence_manager: Arc<PersistenceManager>, transport_factory: Arc<dyn TransportFactory>, http_client: Arc<dyn HttpClient>, override_version: Option<(u32, u32, u32)>, ) -> (Arc<Self>, Receiver<MajorSyncTask>)
Create a new Client with default cache configuration.
This is the standard constructor. Use Client::new_with_cache_config
if you need to customise cache TTL / capacity.
Sourcepub async fn new_with_cache_config(
runtime: Arc<dyn Runtime>,
persistence_manager: Arc<PersistenceManager>,
transport_factory: Arc<dyn TransportFactory>,
http_client: Arc<dyn HttpClient>,
override_version: Option<(u32, u32, u32)>,
cache_config: CacheConfig,
) -> (Arc<Self>, Receiver<MajorSyncTask>)
pub async fn new_with_cache_config( runtime: Arc<dyn Runtime>, persistence_manager: Arc<PersistenceManager>, transport_factory: Arc<dyn TransportFactory>, http_client: Arc<dyn HttpClient>, override_version: Option<(u32, u32, u32)>, cache_config: CacheConfig, ) -> (Arc<Self>, Receiver<MajorSyncTask>)
Create a new Client with a custom CacheConfig.
Sourcepub fn register_handler(&self, handler: Arc<dyn EventHandler>)
pub fn register_handler(&self, handler: Arc<dyn EventHandler>)
Registers an external event handler to the core event bus.
Sourcepub async fn register_chatstate_handler(
&self,
handler: Arc<dyn Fn(ChatStateEvent) + Send + Sync>,
)
pub async fn register_chatstate_handler( &self, handler: Arc<dyn Fn(ChatStateEvent) + Send + Sync>, )
Register a chatstate handler which will be invoked when a <chatstate> stanza is received.
The handler receives a ChatStateEvent with the parsed chat state information.
pub async fn run(self: &Arc<Self>)
pub async fn connect(self: &Arc<Self>) -> Result<(), Error>
pub async fn disconnect(self: &Arc<Self>)
Sourcepub async fn reconnect(self: &Arc<Self>)
pub async fn reconnect(self: &Arc<Self>)
Drop the current connection and trigger the auto-reconnect loop.
Unlike [disconnect], this does not stop the run loop. The client
will reconnect automatically using the same persisted identity/store,
just as it would after a network interruption. Use
[wait_for_connected] to wait for the new connection to be ready.
This is useful for:
- Handling network changes (e.g., Wi-Fi → cellular)
- Forcing a fresh server session
- Testing offline message delivery
Sourcepub async fn reconnect_immediately(self: &Arc<Self>)
pub async fn reconnect_immediately(self: &Arc<Self>)
Drop the current connection and reconnect immediately with no delay.
Unlike [reconnect], which introduces a deliberate offline window,
this method sets the expected_disconnect flag so the run loop
skips the backoff delay and reconnects as fast as possible.
pub async fn set_passive(&self, passive: bool) -> Result<(), IqError>
pub async fn clean_dirty_bits( &self, type_: &str, timestamp: Option<&str>, ) -> Result<(), IqError>
pub async fn fetch_props(&self) -> Result<(), IqError>
pub async fn fetch_privacy_settings( &self, ) -> Result<PrivacySettingsResponse, IqError>
Sourcepub async fn set_privacy_setting(
&self,
category: &str,
value: &str,
) -> Result<(), IqError>
pub async fn set_privacy_setting( &self, category: &str, value: &str, ) -> Result<(), IqError>
Set a privacy setting (e.g. “last” → “contacts”).
Sourcepub async fn set_default_disappearing_mode(
&self,
duration: u32,
) -> Result<(), IqError>
pub async fn set_default_disappearing_mode( &self, duration: u32, ) -> Result<(), IqError>
Set the default disappearing messages duration (seconds). Pass 0 to disable.
Sourcepub async fn get_business_profile(
&self,
jid: &Jid,
) -> Result<Option<BusinessProfile>, IqError>
pub async fn get_business_profile( &self, jid: &Jid, ) -> Result<Option<BusinessProfile>, IqError>
Get business profile for a WhatsApp Business account.
Sourcepub async fn reject_call(
&self,
call_id: &str,
call_from: &Jid,
) -> Result<(), Error>
pub async fn reject_call( &self, call_id: &str, call_from: &Jid, ) -> Result<(), Error>
Reject an incoming call. Fire-and-forget — no server response is expected.
pub async fn send_digest_key_bundle(&self) -> Result<(), IqError>
pub fn is_connected(&self) -> bool
pub fn is_logged_in(&self) -> bool
Sourcepub fn wait_for_node(&self, filter: NodeFilter) -> Receiver<Arc<Node>>
pub fn wait_for_node(&self, filter: NodeFilter) -> Receiver<Arc<Node>>
Register a waiter for an incoming node matching the given filter.
Returns a receiver that resolves when a matching node arrives. The waiter starts buffering immediately, so register it before performing the action that triggers the expected node.
When multiple waiters match the same node, each matching waiter receives a clone of the node (broadcast within a single resolve pass).
§Example
let waiter = client.wait_for_node(
NodeFilter::tag("notification").attr("type", "w:gp2"),
);
client.groups().add_participants(&group_jid, &[jid_c]).await?;
let node = waiter.await.expect("notification arrived");Sourcepub async fn wait_for_socket(&self, timeout: Duration) -> Result<(), Error>
pub async fn wait_for_socket(&self, timeout: Duration) -> Result<(), Error>
Waits for the noise socket to be established.
Returns Ok(()) when the socket is ready, or Err on timeout.
This is useful for code that needs to send messages before login,
such as requesting a pair code during initial pairing.
If the socket is already connected, returns immediately.
Sourcepub async fn wait_for_connected(&self, timeout: Duration) -> Result<(), Error>
pub async fn wait_for_connected(&self, timeout: Duration) -> Result<(), Error>
Waits for the client to establish a connection and complete login.
Returns Ok(()) when connected, or Err on timeout.
This is useful for code that needs to run after connection is established
and authentication is complete.
If the client is already connected and logged in, returns immediately.
Sourcepub fn persistence_manager(&self) -> Arc<PersistenceManager>
pub fn persistence_manager(&self) -> Arc<PersistenceManager>
Get access to the PersistenceManager for this client. This is useful for multi-account scenarios to get the device ID.
pub async fn edit_message( &self, to: Jid, original_id: impl Into<String>, new_content: Message, ) -> Result<String, Error>
pub async fn send_node(&self, node: Node) -> Result<(), ClientError>
pub async fn get_push_name(&self) -> String
pub async fn get_pn(&self) -> Option<Jid>
pub async fn get_lid(&self) -> Option<Jid>
Source§impl Client
impl Client
pub async fn download(&self, downloadable: &dyn Downloadable) -> Result<Vec<u8>>
pub async fn download_to_file<W: Write + Seek + Send + Unpin>( &self, downloadable: &dyn Downloadable, writer: W, ) -> Result<()>
Sourcepub async fn download_from_params(
&self,
direct_path: &str,
media_key: &[u8],
file_sha256: &[u8],
file_enc_sha256: &[u8],
file_length: u64,
media_type: MediaType,
) -> Result<Vec<u8>>
pub async fn download_from_params( &self, direct_path: &str, media_key: &[u8], file_sha256: &[u8], file_enc_sha256: &[u8], file_length: u64, media_type: MediaType, ) -> Result<Vec<u8>>
Downloads and decrypts media from raw parameters without needing the original message.
Sourcepub async fn download_to_writer<W: Write + Seek + Send + 'static>(
&self,
downloadable: &dyn Downloadable,
writer: W,
) -> Result<W>
pub async fn download_to_writer<W: Write + Seek + Send + 'static>( &self, downloadable: &dyn Downloadable, writer: W, ) -> Result<W>
Downloads and decrypts media with streaming (constant memory usage).
The entire HTTP download, decryption, and file write happen in a single blocking thread. The writer is seeked back to position 0 before returning.
Memory usage: ~40KB regardless of file size (8KB read buffer + decrypt state).
Sourcepub async fn download_from_params_to_writer<W: Write + Seek + Send + 'static>(
&self,
direct_path: &str,
media_key: &[u8],
file_sha256: &[u8],
file_enc_sha256: &[u8],
file_length: u64,
media_type: MediaType,
writer: W,
) -> Result<W>
pub async fn download_from_params_to_writer<W: Write + Seek + Send + 'static>( &self, direct_path: &str, media_key: &[u8], file_sha256: &[u8], file_enc_sha256: &[u8], file_length: u64, media_type: MediaType, writer: W, ) -> Result<W>
Streaming variant of download_from_params that writes to a writer
instead of buffering in memory.
Source§impl Client
impl Client
Sourcepub async fn pair_with_code(
self: &Arc<Self>,
options: PairCodeOptions,
) -> Result<String, PairCodeError>
pub async fn pair_with_code( self: &Arc<Self>, options: PairCodeOptions, ) -> Result<String, PairCodeError>
Initiates pair code authentication as an alternative to QR code pairing.
This method starts the phone number linking process. The returned code should be displayed to the user, who then enters it on their phone in: WhatsApp > Linked Devices > Link a Device > Link with phone number instead
This can run concurrently with QR code pairing - whichever completes first wins.
§Arguments
options- Configuration for pair code authentication
§Returns
Ok(String)- The 8-character pairing code to displayErr- If validation fails, not connected, or server error
§Example
use whatsapp_rust::pair_code::PairCodeOptions;
let options = PairCodeOptions {
phone_number: "15551234567".to_string(),
show_push_notification: true,
custom_code: None, // Generate random code
..Default::default()
};
let code = client.pair_with_code(options).await?;
println!("Enter this code on your phone: {}", code);Source§impl Client
impl Client
Sourcepub async fn generate_message_id(&self) -> String
pub async fn generate_message_id(&self) -> String
Generates a unique message ID that conforms to the WhatsApp protocol format.
This is an advanced function that allows library users to generate message IDs that are compatible with the WhatsApp protocol. The generated ID includes timestamp, user JID, and random components to ensure uniqueness.
§Advanced Use Case
This function is intended for advanced users who need to build custom protocol
interactions or manage message IDs manually. Most users should use higher-level
methods like send_message which handle ID generation automatically.
§Returns
A string containing the generated message ID in the format expected by WhatsApp.
Sourcepub async fn send_iq(&self, query: InfoQuery<'_>) -> Result<Node, IqError>
pub async fn send_iq(&self, query: InfoQuery<'_>) -> Result<Node, IqError>
Sends a custom IQ (Info/Query) stanza to the WhatsApp server.
This is an advanced function that allows library users to send custom IQ stanzas for protocol interactions that are not covered by higher-level methods. Common use cases include live location updates, custom presence management, or other advanced WhatsApp features.
§Advanced Use Case
This function bypasses some of the higher-level abstractions and safety checks provided by other client methods. Users should be familiar with the WhatsApp protocol and IQ stanza format before using this function.
§Arguments
query- The IQ query to send, containing the stanza type, namespace, content, and optional timeout
§Returns
Ok(Node)- The response node from the serverErr(IqError)- Various error conditions including timeout, connection issues, or server errors
§Example
use wacore::request::{InfoQuery, InfoQueryType};
use wacore_binary::builder::NodeBuilder;
use wacore_binary::node::NodeContent;
use wacore_binary::jid::{Jid, SERVER_JID};
// This is a simplified example - real usage requires proper setup
let query_node = NodeBuilder::new("presence")
.attr("type", "available")
.build();
let server_jid = Jid::new("", SERVER_JID);
let query = InfoQuery {
query_type: InfoQueryType::Set,
namespace: "presence",
to: server_jid,
target: None,
content: Some(NodeContent::Nodes(vec![query_node])),
id: None,
timeout: None,
};
let response = client.send_iq(query).await?;Sourcepub async fn execute<S>(&self, spec: S) -> Result<S::Response, IqError>where
S: IqSpec,
pub async fn execute<S>(&self, spec: S) -> Result<S::Response, IqError>where
S: IqSpec,
Executes an IQ specification and returns the typed response.
This is a convenience method that combines building the IQ request, sending it, and parsing the response into a single operation.
§Example
use wacore::iq::groups::GroupQueryIq;
let group_info = client.execute(GroupQueryIq::new(&group_jid)).await?;
println!("Group subject: {}", group_info.subject);Source§impl Client
impl Client
Sourcepub async fn send_message(
&self,
to: Jid,
message: Message,
) -> Result<String, Error>
pub async fn send_message( &self, to: Jid, message: Message, ) -> Result<String, Error>
Send an end-to-end encrypted message to a user or group.
Returns the message ID on success. For status/story updates use
Client::status() instead.
Sourcepub async fn send_message_with_options(
&self,
to: Jid,
message: Message,
options: SendOptions,
) -> Result<String, Error>
pub async fn send_message_with_options( &self, to: Jid, message: Message, options: SendOptions, ) -> Result<String, Error>
Send a message with additional options.
Sourcepub async fn revoke_message(
&self,
to: Jid,
message_id: impl Into<String>,
revoke_type: RevokeType,
) -> Result<(), Error>
pub async fn revoke_message( &self, to: Jid, message_id: impl Into<String>, revoke_type: RevokeType, ) -> Result<(), Error>
Delete a message for everyone in the chat (revoke).
This sends a revoke protocol message that removes the message for all participants. The message will show as “This message was deleted” for recipients.
§Arguments
to- The chat JID (DM or group)message_id- The ID of the message to deleterevoke_type- UseRevokeType::Senderto delete your own message, orRevokeType::Admin { original_sender }to delete another user’s message as group admin
Source§impl Client
impl Client
Sourcepub async fn send_pdo_placeholder_resend_request(
self: &Arc<Self>,
info: &MessageInfo,
) -> Result<(), Error>
pub async fn send_pdo_placeholder_resend_request( self: &Arc<Self>, info: &MessageInfo, ) -> Result<(), Error>
Sends a PDO (Peer Data Operation) request to our own primary phone to get the decrypted content of a message that we failed to decrypt.
This is called when decryption fails and we want to ask our phone for the message. The phone will respond with a PeerDataOperationRequestResponseMessage containing the full WebMessageInfo which we can then dispatch as a normal message event.
§Arguments
info- The MessageInfo for the message that failed to decrypt
§Returns
Ok(())if the request was sent successfullyErrif we couldn’t send the request (e.g., not logged in)
Sourcepub async fn fetch_message_history(
self: &Arc<Self>,
chat_jid: &Jid,
oldest_msg_id: &str,
oldest_msg_from_me: bool,
oldest_msg_timestamp_ms: i64,
count: i32,
) -> Result<String, Error>
pub async fn fetch_message_history( self: &Arc<Self>, chat_jid: &Jid, oldest_msg_id: &str, oldest_msg_from_me: bool, oldest_msg_timestamp_ms: i64, count: i32, ) -> Result<String, Error>
Request on-demand message history from the primary phone via PDO.
Sourcepub async fn handle_pdo_response(
self: &Arc<Self>,
response: &PeerDataOperationRequestResponseMessage,
_pdo_msg_info: &MessageInfo,
)
pub async fn handle_pdo_response( self: &Arc<Self>, response: &PeerDataOperationRequestResponseMessage, _pdo_msg_info: &MessageInfo, )
Handles a PDO response message from our primary phone. This is called when we receive a PeerDataOperationRequestResponseMessage.
§Arguments
response- The PDO response messageinfo- The MessageInfo for the PDO response message itself
Source§impl Client
impl Client
pub fn chat_actions(&self) -> ChatActions<'_>
Source§impl Client
impl Client
Sourcepub fn media_reupload(&self) -> MediaReupload<'_>
pub fn media_reupload(&self) -> MediaReupload<'_>
Access media reupload operations.
Source§impl Client
impl Client
Sourcepub async fn send_spam_report(
&self,
request: SpamReportRequest,
) -> Result<SpamReportResult, IqError>
pub async fn send_spam_report( &self, request: SpamReportRequest, ) -> Result<SpamReportResult, IqError>
Send a spam report to WhatsApp.
This sends a spam_list IQ stanza to report one or more messages as spam.
§Arguments
request- The spam report request containing message details
§Returns
Ok(SpamReportResult)- If the report was successfully submittedErr- If there was an error sending or processing the report
§Example
let result = client.send_spam_report(SpamReportRequest {
message_id: "MSG_ID".to_string(),
message_timestamp: 1234567890,
from_jid: Some(sender_jid),
spam_flow: SpamFlow::MessageMenu,
..Default::default()
}).await?;Trait Implementations§
Source§impl SendContextResolver for Client
impl SendContextResolver for Client
fn resolve_devices<'life0, 'life1, 'async_trait>(
&'life0 self,
jids: &'life1 [Jid],
) -> Pin<Box<dyn Future<Output = Result<Vec<Jid>, Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
fn fetch_prekeys<'life0, 'life1, 'async_trait>(
&'life0 self,
jids: &'life1 [Jid],
) -> Pin<Box<dyn Future<Output = Result<HashMap<Jid, PreKeyBundle>, Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
fn fetch_prekeys_for_identity_check<'life0, 'life1, 'async_trait>(
&'life0 self,
jids: &'life1 [Jid],
) -> Pin<Box<dyn Future<Output = Result<HashMap<Jid, PreKeyBundle>, Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
fn resolve_group_info<'life0, 'life1, 'async_trait>(
&'life0 self,
jid: &'life1 Jid,
) -> Pin<Box<dyn Future<Output = Result<GroupInfo, Error>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
Source§fn get_lid_for_phone<'life0, 'life1, 'async_trait>(
&'life0 self,
phone_user: &'life1 str,
) -> Pin<Box<dyn Future<Output = Option<String>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
fn get_lid_for_phone<'life0, 'life1, 'async_trait>(
&'life0 self,
phone_user: &'life1 str,
) -> Pin<Box<dyn Future<Output = Option<String>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
Auto Trait Implementations§
impl !Freeze for Client
impl !RefUnwindSafe for Client
impl Send for Client
impl Sync for Client
impl Unpin for Client
impl UnsafeUnpin for Client
impl !UnwindSafe for Client
Blanket Implementations§
Source§impl<T> AggregateExpressionMethods for T
impl<T> AggregateExpressionMethods for T
Source§fn aggregate_distinct(self) -> Self::Outputwhere
Self: DistinctDsl,
fn aggregate_distinct(self) -> Self::Outputwhere
Self: DistinctDsl,
DISTINCT modifier for aggregate functions Read moreSource§fn aggregate_all(self) -> Self::Outputwhere
Self: AllDsl,
fn aggregate_all(self) -> Self::Outputwhere
Self: AllDsl,
ALL modifier for aggregate functions Read moreSource§fn aggregate_filter<P>(self, f: P) -> Self::Output
fn aggregate_filter<P>(self, f: P) -> Self::Output
Source§fn aggregate_order<O>(self, o: O) -> Self::Outputwhere
Self: OrderAggregateDsl<O>,
fn aggregate_order<O>(self, o: O) -> Self::Outputwhere
Self: OrderAggregateDsl<O>,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> IntoSql for T
impl<T> IntoSql for T
Source§fn into_sql<T>(self) -> Self::Expression
fn into_sql<T>(self) -> Self::Expression
self to an expression for Diesel’s query builder. Read moreSource§fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
&self to an expression for Diesel’s query builder. Read more