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
//! WhatsApp channel — HTTP API integration (WhatsApp Business Cloud API)
use async_trait::async_trait;
use serde_json::Value;
use tokio::sync::mpsc;
use super::formatting::{format_outgoing_text, FormatTarget};
use super::traits::*;
pub struct WhatsAppChannel {
access_token: String,
phone_number_id: String,
verify_token: String,
}
impl WhatsAppChannel {
pub fn new(
access_token: impl Into<String>,
phone_number_id: impl Into<String>,
verify_token: impl Into<String>,
) -> Self {
Self {
access_token: access_token.into(),
phone_number_id: phone_number_id.into(),
verify_token: verify_token.into(),
}
}
/// Load from env vars
pub fn from_env() -> anyhow::Result<Self> {
Ok(Self {
access_token: std::env::var("WHATSAPP_ACCESS_TOKEN")
.map_err(|_| anyhow::anyhow!("WHATSAPP_ACCESS_TOKEN not set"))?,
phone_number_id: std::env::var("WHATSAPP_PHONE_NUMBER_ID")
.map_err(|_| anyhow::anyhow!("WHATSAPP_PHONE_NUMBER_ID not set"))?,
verify_token: std::env::var("WHATSAPP_VERIFY_TOKEN")
.unwrap_or_else(|_| "aclaw-verify".to_string()),
})
}
}
#[async_trait]
impl Channel for WhatsAppChannel {
fn name(&self) -> &str {
"whatsapp"
}
async fn start(&mut self) -> anyhow::Result<mpsc::Receiver<IncomingMessage>> {
let (tx, rx) = mpsc::channel(32);
// WhatsApp Cloud API uses webhooks
// For now, start a simple HTTP server to receive webhooks
let verify_token = self.verify_token.clone();
let _access_token = self.access_token.clone();
tokio::spawn(async move {
use axum::{
extract::Query,
routing::{get, post},
Json, Router,
};
let tx_clone = tx.clone();
let verify = verify_token.clone();
let app = Router::new()
.route(
"/webhook",
get(
move |Query(params): Query<std::collections::HashMap<String, String>>| {
let v = verify.clone();
async move {
// Webhook verification
if params.get("hub.verify_token").map(|t| t.as_str()) == Some(&v) {
params.get("hub.challenge").cloned().unwrap_or_default()
} else {
"Forbidden".to_string()
}
}
},
),
)
.route(
"/webhook",
post(move |Json(body): Json<Value>| {
let tx = tx_clone.clone();
async move {
// Parse incoming WhatsApp message
if let Some(entries) = body["entry"].as_array() {
for entry in entries {
if let Some(changes) = entry["changes"].as_array() {
for change in changes {
if let Some(messages) =
change["value"]["messages"].as_array()
{
for msg in messages {
let text = msg["text"]["body"]
.as_str()
.unwrap_or("")
.to_string();
if text.is_empty() {
continue;
}
let incoming = IncomingMessage {
id: msg["id"]
.as_str()
.unwrap_or("")
.to_string(),
sender_id: msg["from"]
.as_str()
.unwrap_or("")
.to_string(),
sender_name: None,
chat_id: msg["from"]
.as_str()
.unwrap_or("")
.to_string(),
text,
is_group: false,
reply_to: None,
timestamp: chrono::Utc::now(),
};
let _ = tx.send(incoming).await;
}
}
}
}
}
}
"OK"
}
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
});
Ok(rx)
}
async fn send(&self, message: OutgoingMessage) -> anyhow::Result<Option<String>> {
let client = reqwest::Client::new();
let formatted = format_outgoing_text(FormatTarget::WhatsApp, &message.text);
let body = serde_json::json!({
"messaging_product": "whatsapp",
"to": &message.chat_id,
"type": "text",
"text": {
"body": formatted
}
});
let resp = client
.post(format!(
"https://graph.facebook.com/v18.0/{}/messages",
self.phone_number_id
))
.header("Authorization", format!("Bearer {}", self.access_token))
.header("Content-Type", "application/json")
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
let text = resp.text().await.unwrap_or_default();
anyhow::bail!("WhatsApp send failed: {}", text);
}
Ok(None)
}
async fn stop(&mut self) -> anyhow::Result<()> {
Ok(())
}
}