1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use chrono::{Local, Utc};
use log::{error, info};
use std::io::Cursor;
use std::sync::Arc;
use wacore::download::{Downloadable, MediaType};
use wacore::proto_helpers::MessageExt;
use wacore::types::events::Event;
use waproto::whatsapp as wa;
use whatsapp_rust::TokioRuntime;
use whatsapp_rust::bot::{Bot, MessageContext};
use whatsapp_rust::pair_code::PairCodeOptions;
use whatsapp_rust::store::SqliteStore;
use whatsapp_rust::upload::UploadResponse;
use whatsapp_rust_tokio_transport::TokioWebSocketTransportFactory;
use whatsapp_rust_ureq_http_client::UreqHttpClient;
const PING_TRIGGER: &str = "π¦ping";
const MEDIA_PING_TRIGGER: &str = "ping";
const PONG_TEXT: &str = "π Pong!";
const MEDIA_PONG_TEXT: &str = "pong";
const REACTION_EMOJI: &str = "π";
// This is a demo of a simple ping-pong bot with every type of media.
//
// Usage:
// cargo run # QR code pairing only
// cargo run -- --phone 15551234567 # Pair code + QR code (concurrent)
// cargo run -- -p 15551234567 # Short form
// cargo run -- -p 15551234567 --code MYCODE12 # Custom 8-char pair code
// cargo run -- -p 15551234567 -c MYCODE12 # Short form
fn main() {
// Parse CLI arguments for phone number and optional custom code
let args: Vec<String> = std::env::args().collect();
let phone_number = parse_arg(&args, "--phone", "-p");
let custom_code = parse_arg(&args, "--code", "-c");
if let Some(ref phone) = phone_number {
eprintln!("Phone number provided: {}", phone);
if let Some(ref code) = custom_code {
eprintln!("Custom pair code: {}", code);
}
eprintln!("Will use pair code authentication (concurrent with QR)");
}
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.format(|buf, record| {
use std::io::Write;
writeln!(
buf,
"{} [{:<5}] [{}] - {}",
Local::now().format("%H:%M:%S"),
record.level(),
record.target(),
record.args()
)
})
.init();
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("Failed to build tokio runtime");
rt.block_on(async {
let backend = match SqliteStore::new("whatsapp.db").await {
Ok(store) => Arc::new(store),
Err(e) => {
error!("Failed to create SQLite backend: {}", e);
return;
}
};
info!("SQLite backend initialized successfully.");
let transport_factory = TokioWebSocketTransportFactory::new();
let http_client = UreqHttpClient::new();
let mut builder = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport_factory)
.with_http_client(http_client)
.with_runtime(TokioRuntime);
// Optional: Override the WhatsApp version (normally auto-fetched)
// builder = builder.with_version((2, 3000, 1027868167));
// Add pair code authentication if phone number provided
if let Some(phone) = phone_number {
builder = builder.with_pair_code(PairCodeOptions {
phone_number: phone,
custom_code,
..Default::default()
});
}
let mut bot = builder
.on_event(move |event, client| {
async move {
match event {
Event::PairingQrCode { code, timeout } => {
info!("----------------------------------------");
info!(
"QR code received (valid for {} seconds):",
timeout.as_secs()
);
info!("\n{}\n", code);
info!("----------------------------------------");
}
Event::PairingCode { code, timeout } => {
info!("========================================");
info!("PAIR CODE (valid for {} seconds):", timeout.as_secs());
info!("Enter this code on your phone:");
info!("WhatsApp > Linked Devices > Link a Device");
info!("> Link with phone number instead");
info!("");
info!(" >>> {} <<<", code);
info!("");
info!("========================================");
}
Event::Message(msg, info) => {
let ctx = MessageContext {
message: msg,
info,
client,
};
if let Some(media_ping_request) = get_pingable_media(&ctx.message) {
handle_media_ping(&ctx, media_ping_request).await;
}
if let Some(text) = ctx.message.text_content() {
// Profile commands (temporary for testing)
if let Some(new_name) = text.strip_prefix("!setname ") {
let new_name = new_name.trim();
if !new_name.is_empty() {
info!("Setting push name to: {}", new_name);
match ctx.client.profile().set_push_name(new_name).await {
Ok(()) => {
info!("Push name set successfully");
let _ = ctx
.send_message(wa::Message {
conversation: Some(format!(
"β
Name set to: {}",
new_name
)),
..Default::default()
})
.await;
}
Err(e) => {
error!("Failed to set push name: {}", e);
let _ = ctx
.send_message(wa::Message {
conversation: Some(format!(
"β Failed: {}",
e
)),
..Default::default()
})
.await;
}
}
}
} else if let Some(new_status) = text.strip_prefix("!setstatus ") {
let new_status = new_status.trim();
info!("Setting status text to: {}", new_status);
match ctx.client.profile().set_status_text(new_status).await {
Ok(()) => {
info!("Status text set successfully");
let _ = ctx
.send_message(wa::Message {
conversation: Some(format!(
"β
Status set to: {}",
new_status
)),
..Default::default()
})
.await;
}
Err(e) => {
error!("Failed to set status text: {}", e);
let _ = ctx
.send_message(wa::Message {
conversation: Some(format!("β Failed: {}", e)),
..Default::default()
})
.await;
}
}
}
}
if let Some(text) = ctx.message.text_content()
&& text == PING_TRIGGER
{
info!("Received text ping, sending pong...");
let message_key = wa::MessageKey {
remote_jid: Some(ctx.info.source.chat.to_string()),
id: Some(ctx.info.id.clone()),
from_me: Some(ctx.info.source.is_from_me),
participant: if ctx.info.source.is_group {
Some(ctx.info.source.sender.to_string())
} else {
None
},
};
let reaction_message = wa::message::ReactionMessage {
key: Some(message_key),
text: Some(REACTION_EMOJI.to_string()),
sender_timestamp_ms: Some(Utc::now().timestamp_millis()),
..Default::default()
};
let final_message_to_send = wa::Message {
reaction_message: Some(reaction_message),
..Default::default()
};
if let Err(e) = ctx.send_message(final_message_to_send).await {
error!("Failed to send reaction: {}", e);
}
let start = std::time::Instant::now();
let context_info = ctx.build_quote_context();
let reply_message = wa::Message {
extended_text_message: Some(Box::new(
wa::message::ExtendedTextMessage {
text: Some(PONG_TEXT.to_string()),
context_info: Some(Box::new(context_info)),
..Default::default()
},
)),
..Default::default()
};
let sent_msg_id = match ctx.send_message(reply_message).await {
Ok(id) => id,
Err(e) => {
error!("Failed to send initial pong message: {}", e);
return;
}
};
let duration = start.elapsed();
let duration_str = format!("{:.2?}", duration);
info!(
"Send took {}. Editing message {}...",
duration_str, &sent_msg_id
);
// WhatsApp Web does NOT resend quote context on edits.
// The edit only carries new content β no stanza_id,
// participant, or quoted_message.
let updated_content = wa::Message {
extended_text_message: Some(Box::new(
wa::message::ExtendedTextMessage {
text: Some(format!(
"{}\n`{}`",
PONG_TEXT, duration_str
)),
..Default::default()
},
)),
..Default::default()
};
if let Err(e) =
ctx.edit_message(sent_msg_id.clone(), updated_content).await
{
error!("Failed to edit message {}: {}", sent_msg_id, e);
} else {
info!("Successfully sent edit for message {}.", sent_msg_id);
}
}
}
Event::Connected(_) => {
info!("β
Bot connected successfully!");
}
Event::Receipt(_receipt) => {}
Event::LoggedOut(_) => {
error!("β Bot was logged out!");
}
_ => {
// debug!("Received unhandled event: {:?}", event);
}
}
}
})
.build()
.await
.expect("Failed to build bot");
// If you want and need, you can get the client:
// let client = bot.client();
let client = bot.client();
let bot_handle = match bot.run().await {
Ok(handle) => handle,
Err(e) => {
error!("Bot failed to start: {}", e);
return;
}
};
#[cfg(feature = "signal")]
{
tokio::select! {
_ = bot_handle => {}
_ = tokio::signal::ctrl_c() => {
info!("Received Ctrl+C, shutting down...");
client.disconnect().await;
}
}
}
#[cfg(not(feature = "signal"))]
{
bot_handle
.await
.expect("Bot task should complete without panicking");
}
});
}
trait MediaPing: Downloadable {
fn media_type(&self) -> MediaType;
fn build_pong_reply(&self, upload: UploadResponse) -> wa::Message;
}
impl MediaPing for wa::message::ImageMessage {
fn media_type(&self) -> MediaType {
MediaType::Image
}
fn build_pong_reply(&self, upload: UploadResponse) -> wa::Message {
wa::Message {
image_message: Some(Box::new(wa::message::ImageMessage {
mimetype: self.mimetype.clone(),
caption: Some(MEDIA_PONG_TEXT.to_string()),
url: Some(upload.url),
direct_path: Some(upload.direct_path),
media_key: Some(upload.media_key),
file_enc_sha256: Some(upload.file_enc_sha256),
file_sha256: Some(upload.file_sha256),
file_length: Some(upload.file_length),
..Default::default()
})),
..Default::default()
}
}
}
impl MediaPing for wa::message::VideoMessage {
fn media_type(&self) -> MediaType {
MediaType::Video
}
fn build_pong_reply(&self, upload: UploadResponse) -> wa::Message {
wa::Message {
video_message: Some(Box::new(wa::message::VideoMessage {
mimetype: self.mimetype.clone(),
caption: Some(MEDIA_PONG_TEXT.to_string()),
url: Some(upload.url),
direct_path: Some(upload.direct_path),
media_key: Some(upload.media_key),
file_enc_sha256: Some(upload.file_enc_sha256),
file_sha256: Some(upload.file_sha256),
file_length: Some(upload.file_length),
gif_playback: self.gif_playback,
height: self.height,
width: self.width,
seconds: self.seconds,
gif_attribution: self.gif_attribution,
..Default::default()
})),
..Default::default()
}
}
}
fn get_pingable_media<'a>(message: &'a wa::Message) -> Option<&'a (dyn MediaPing + 'a)> {
let base_message = message.get_base_message();
if let Some(msg) = &base_message.image_message
&& msg.caption.as_deref() == Some(MEDIA_PING_TRIGGER)
{
return Some(&**msg);
}
if let Some(msg) = &base_message.video_message
&& msg.caption.as_deref() == Some(MEDIA_PING_TRIGGER)
{
return Some(&**msg);
}
None
}
async fn handle_media_ping(ctx: &MessageContext, media: &(dyn MediaPing + '_)) {
info!(
"Received {:?} ping from {}",
media.media_type(),
ctx.info.source.sender
);
let mut data_buffer = Cursor::new(Vec::new());
if let Err(e) = ctx.client.download_to_file(media, &mut data_buffer).await {
error!("Failed to download media: {}", e);
let _ = ctx
.send_message(wa::Message {
conversation: Some("Failed to download your media.".to_string()),
..Default::default()
})
.await;
return;
}
info!(
"Successfully downloaded media. Size: {} bytes. Now uploading...",
data_buffer.get_ref().len()
);
let plaintext_data = data_buffer.into_inner();
let upload_response = match ctx.client.upload(plaintext_data, media.media_type()).await {
Ok(resp) => resp,
Err(e) => {
error!("Failed to upload media: {}", e);
let _ = ctx
.send_message(wa::Message {
conversation: Some("Failed to re-upload the media.".to_string()),
..Default::default()
})
.await;
return;
}
};
info!("Successfully uploaded media. Constructing reply message...");
let reply_msg = media.build_pong_reply(upload_response);
if let Err(e) = ctx.send_message(reply_msg).await {
error!("Failed to send media pong reply: {}", e);
} else {
info!("Media pong reply sent successfully.");
}
}
/// Parse a CLI argument by its long and short flags.
/// Supports: --flag VALUE, -f VALUE, --flag=VALUE
fn parse_arg(args: &[String], long: &str, short: &str) -> Option<String> {
let long_prefix = format!("{}=", long);
let mut iter = args.iter().skip(1); // Skip program name
while let Some(arg) = iter.next() {
if arg == long || arg == short {
return iter.next().cloned();
}
if let Some(value) = arg.strip_prefix(&long_prefix) {
return Some(value.to_string());
}
}
None
}