devZenaight commited on
Commit
ed4f1f5
·
verified ·
1 Parent(s): b0242f1

Upload 5 files

Browse files
Files changed (1) hide show
  1. main.py +66 -59
main.py CHANGED
@@ -1,60 +1,67 @@
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(
14
- hub_mode: str = Query(None, alias="hub.mode"),
15
- hub_token: str = Query(None, alias="hub.verify_token"),
16
- hub_challenge: str = Query(None, alias="hub.challenge")
17
- ):
18
- if hub_mode == "subscribe" and hub_token == VERIFY_TOKEN:
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}",
41
- "Content-Type": "application/json"
42
- }
43
- payload = {
44
- "messaging_product": "whatsapp",
45
- "to": wa_id,
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
-
58
- @app.get("/ping") # health check
59
- def ping():
 
 
 
 
 
 
 
60
  return {"pong": True}
 
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(
14
+ hub_mode: str = Query(None, alias="hub.mode"),
15
+ hub_token: str = Query(None, alias="hub.verify_token"),
16
+ hub_challenge: str = Query(None, alias="hub.challenge")
17
+ ):
18
+ if hub_mode == "subscribe" and hub_token == VERIFY_TOKEN:
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}",
41
+ "Content-Type": "application/json"
42
+ }
43
+ payload = {
44
+ "messaging_product": "whatsapp",
45
+ "to": wa_id,
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
+
58
+ @app.post("/send")
59
+ async def check_token():
60
+ token = os.getenv("WHATSAPP_API_TOKEN", "")
61
+ if token:
62
+ return {"token_loaded": True}
63
+ raise HTTPException(status_code=400, detail="Token not found")
64
+
65
+ @app.get("/ping") # health check
66
+ def ping():
67
  return {"pong": True}