Repository navigation
Expand file tree
/
Copy pathwebhook.py
More file actions
78 lines (65 loc) · 2.63 KB
/
Copy pathwebhook.py
File metadata and controls
78 lines (65 loc) · 2.63 KB
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
import os
import httpx
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.staticfiles import StaticFiles
from math_agent import handle_query
load_dotenv()
# WhatsApp Cloud API credentials
token = os.getenv("WA_TOKEN")
phone_number_id = os.getenv("PHONE_NUMBER_ID")
verify_token = os.getenv("WA_VERIFY_TOKEN")
public_url = "https://internal-teaching-kiwi.ngrok-free.app"
app = FastAPI()
app.mount("/static", StaticFiles(directory="./static"), name="static")
async def send_whatsapp_message(payload: dict):
url = f"https://graph.facebook.com/v22.0/{phone_number_id}/messages"
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
async with httpx.AsyncClient() as client:
resp = await client.post(url, headers=headers, json=payload)
resp.raise_for_status()
return resp.json()
@app.get("/")
async def root():
return {"message": "OK"}
# Verification endpoint
@app.get("/webhook")
async def verify_webhook(request: Request):
mode = request.query_params.get("hub.mode")
challenge = request.query_params.get("hub.challenge")
token_sent = request.query_params.get("hub.verify_token")
if mode == "subscribe" and token_sent == verify_token:
return Response(content=challenge, media_type="text/plain")
raise HTTPException(status_code=403, detail="Verification failed")
# Incoming message handler
@app.post("/webhook")
async def whatsapp_webhook(req: Request):
data = await req.json()
for entry in data.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
messages = value.get("messages")
if not messages:
continue
msg = messages[0]
from_phone = msg.get("from")
if msg.get("type") == "text":
body = msg["text"]["body"]
reply = handle_query(body)
payload = {
"messaging_product": "whatsapp",
"to": from_phone,
"type": "text",
"text": {"preview_url": False, "body": reply},
}
await send_whatsapp_message(payload)
elif msg.get("type") == "audio":
audio_link = f"{public_url}/static/Arabic.mp3"
payload = {
"messaging_product": "whatsapp",
"to": from_phone,
"type": "audio",
"audio": {"link": audio_link},
}
await send_whatsapp_message(payload)
return Response(status_code=200)