devZenaight commited on
Commit
6c3bf56
·
verified ·
1 Parent(s): 366f5b2

Upload 5 files

Browse files
Files changed (1) hide show
  1. main.py +22 -17
main.py CHANGED
@@ -34,35 +34,40 @@ def send_whatsapp_message(wa_id, reply):
34
  }
35
  httpx.post(url, headers=headers, json=payload)
36
 
37
- @app.post("/webhook")
38
  async def receive_update(req: Request):
39
  data = await req.json()
40
  change = data["entry"][0]["changes"][0]["value"]
41
  wa_id = change["contacts"][0]["wa_id"]
42
  msg = change["messages"][0]
43
 
 
44
  if msg["type"] == "image":
45
  media_id = msg["image"]["id"]
46
- # fetch media URL
47
- media_url = httpx.get(
48
  f"https://graph.facebook.com/v23.0/{media_id}",
49
  headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}
50
- ).json()["url"]
51
- media_bytes = httpx.get(media_url, headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}).content
52
- b64 = base64.b64encode(media_bytes).decode("utf-8")[:10]
53
- reply = f"Base64: {b64}"
54
- send_whatsapp_message(wa_id, reply)
55
- return JSONResponse({"status":"image_preview_sent","preview":b64})
 
 
 
 
 
 
56
 
57
- # fall through to text handler
58
- if msg["type"] != "text":
59
- print(f"Ignoring message type: {msg['type']}")
60
- return JSONResponse({"status": "ignored", "type": msg["type"]})
 
61
 
62
- incoming = msg["text"]["body"]
63
- reply = f"You said: {incoming}"
64
- send_whatsapp_message(wa_id, reply)
65
- return JSONResponse({"status": "replied"})
66
 
67
  @app.post("/send")
68
  async def check_token():
 
34
  }
35
  httpx.post(url, headers=headers, json=payload)
36
 
 
37
  async def receive_update(req: Request):
38
  data = await req.json()
39
  change = data["entry"][0]["changes"][0]["value"]
40
  wa_id = change["contacts"][0]["wa_id"]
41
  msg = change["messages"][0]
42
 
43
+ # IMAGE: convert to Base64 preview
44
  if msg["type"] == "image":
45
  media_id = msg["image"]["id"]
46
+ # 1) get media URL
47
+ media_resp = httpx.get(
48
  f"https://graph.facebook.com/v23.0/{media_id}",
49
  headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}
50
+ )
51
+ media_resp.raise_for_status()
52
+ media_url = media_resp.json()["url"]
53
+ # 2) download bytes
54
+ media_bytes = httpx.get(
55
+ media_url,
56
+ headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}
57
+ ).content
58
+ # 3) encode & preview
59
+ preview = base64.b64encode(media_bytes).decode("utf-8")[:10]
60
+ send_whatsapp_message(wa_id, f"Base64: {preview}")
61
+ return JSONResponse({"status": "image_preview_sent", "preview": preview})
62
 
63
+ # TEXT: simple echo
64
+ if msg["type"] == "text":
65
+ incoming = msg["text"]["body"]
66
+ send_whatsapp_message(wa_id, f"You said: {incoming}")
67
+ return JSONResponse({"status": "replied"})
68
 
69
+ # ANY OTHER TYPE: ignore silently
70
+ return JSONResponse({"status": "ignored", "type": msg["type"]})
 
 
71
 
72
  @app.post("/send")
73
  async def check_token():