devZenaight commited on
Commit
39068f2
·
verified ·
1 Parent(s): ba97fe3

Upload 5 files

Browse files
Files changed (1) hide show
  1. main.py +15 -14
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") # incoming messages
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
- # prepare reply
34
- if msg["type"] == "text":
35
- incoming = msg["text"]["body"]
36
- reply = f"You said: {incoming}"
37
- else:
38
- reply = "Please send me a text message."
 
 
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
- resp = httpx.post(url, headers=headers, json=payload)
53
- resp.raise_for_status()
 
 
 
 
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