Upload 5 files
Browse files
main.py
CHANGED
|
@@ -19,25 +19,22 @@ def verify(
|
|
| 19 |
return PlainTextResponse(hub_challenge)
|
| 20 |
raise HTTPException(status_code=403, detail="Invalid token")
|
| 21 |
|
| 22 |
-
@app.post("/webhook")
|
| 23 |
async def receive_update(req: Request):
|
| 24 |
data = await req.json()
|
| 25 |
-
# log the raw update
|
| 26 |
-
print("WA update:", json.dumps(data))
|
| 27 |
-
|
| 28 |
-
# drill into the first WhatsApp message
|
| 29 |
change = data["entry"][0]["changes"][0]["value"]
|
| 30 |
wa_id = change["contacts"][0]["wa_id"]
|
| 31 |
msg = change["messages"][0]
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
if msg["type"] =
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
# send the reply back via the WhatsApp Cloud API
|
| 41 |
url = f"https://graph.facebook.com/v23.0/{PHONE_NUMBER_ID}/messages"
|
| 42 |
headers = {
|
| 43 |
"Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
|
|
@@ -49,8 +46,12 @@ async def receive_update(req: Request):
|
|
| 49 |
"type": "text",
|
| 50 |
"text": {"body": reply}
|
| 51 |
}
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
return JSONResponse({"status": "replied"})
|
| 56 |
|
|
|
|
| 19 |
return PlainTextResponse(hub_challenge)
|
| 20 |
raise HTTPException(status_code=403, detail="Invalid token")
|
| 21 |
|
| 22 |
+
@app.post("/webhook")
|
| 23 |
async def receive_update(req: Request):
|
| 24 |
data = await req.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
change = data["entry"][0]["changes"][0]["value"]
|
| 26 |
wa_id = change["contacts"][0]["wa_id"]
|
| 27 |
msg = change["messages"][0]
|
| 28 |
|
| 29 |
+
# 1) Ignore non-text messages
|
| 30 |
+
if msg["type"] != "text":
|
| 31 |
+
print(f"Ignoring message type: {msg['type']}")
|
| 32 |
+
return JSONResponse({"status": "ignored", "type": msg["type"]})
|
| 33 |
+
|
| 34 |
+
# 2) Handle text as before
|
| 35 |
+
incoming = msg["text"]["body"]
|
| 36 |
+
reply = f"You said: {incoming}"
|
| 37 |
|
|
|
|
| 38 |
url = f"https://graph.facebook.com/v23.0/{PHONE_NUMBER_ID}/messages"
|
| 39 |
headers = {
|
| 40 |
"Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
|
|
|
|
| 46 |
"type": "text",
|
| 47 |
"text": {"body": reply}
|
| 48 |
}
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
resp = httpx.post(url, headers=headers, json=payload)
|
| 52 |
+
resp.raise_for_status()
|
| 53 |
+
except httpx.HTTPStatusError as e:
|
| 54 |
+
print("Failed to send reply:", e)
|
| 55 |
|
| 56 |
return JSONResponse({"status": "replied"})
|
| 57 |
|