Upload 5 files
Browse files
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 |
-
#
|
| 47 |
-
|
| 48 |
f"https://graph.facebook.com/v23.0/{media_id}",
|
| 49 |
headers={"Authorization": f"Bearer {WHATSAPP_API_TOKEN}"}
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
if msg["type"]
|
| 59 |
-
|
| 60 |
-
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 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():
|