Upload 5 files
Browse files
main.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
import os, json
|
| 2 |
from fastapi import FastAPI, Request, HTTPException, Query
|
| 3 |
from fastapi.responses import PlainTextResponse, JSONResponse
|
|
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "") # set in HF Secrets
|
|
|
|
|
|
|
| 8 |
|
| 9 |
@app.get("/webhook") # verification
|
| 10 |
def verify(
|
|
@@ -19,8 +22,37 @@ def verify(
|
|
| 19 |
@app.post("/webhook") # incoming messages
|
| 20 |
async def receive_update(req: Request):
|
| 21 |
data = await req.json()
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
@app.get("/ping") # health check
|
| 26 |
def ping():
|
|
|
|
| 1 |
import os, json
|
| 2 |
from fastapi import FastAPI, Request, HTTPException, Query
|
| 3 |
from fastapi.responses import PlainTextResponse, JSONResponse
|
| 4 |
+
import httpx
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
| 8 |
VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "") # set in HF Secrets
|
| 9 |
+
PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
|
| 10 |
+
WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
|
| 11 |
|
| 12 |
@app.get("/webhook") # verification
|
| 13 |
def verify(
|
|
|
|
| 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}",
|
| 44 |
+
"Content-Type": "application/json"
|
| 45 |
+
}
|
| 46 |
+
payload = {
|
| 47 |
+
"messaging_product": "whatsapp",
|
| 48 |
+
"to": wa_id,
|
| 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 |
|
| 57 |
@app.get("/ping") # health check
|
| 58 |
def ping():
|