devZenaight commited on
Commit
c08bda7
·
verified ·
1 Parent(s): 4e18bd8

Upload 5 files

Browse files
Files changed (1) hide show
  1. main.py +31 -23
main.py CHANGED
@@ -1,12 +1,15 @@
1
  from fastapi import FastAPI, Request, Query, HTTPException
2
  from fastapi.responses import JSONResponse, PlainTextResponse
3
- from typing import Optional
4
  import os
5
  import httpx
6
  import base64
7
 
8
  app = FastAPI()
9
- VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "")
 
 
 
 
10
 
11
  @app.get("/")
12
  def root():
@@ -25,38 +28,44 @@ async def test_post():
25
  return {"detail": "POST method working"}
26
 
27
  @app.get("/webhook")
28
- async def verify(hub_mode: str = Query(..., alias="hub.mode"),
29
- hub_token: str = Query(..., alias="hub.verify_token"),
30
- hub_challenge: str = Query(..., alias="hub.challenge")):
31
- if hub_mode == "subscribe" and hub_token == os.getenv("VERIFY_TOKEN"):
 
 
 
32
  return PlainTextResponse(hub_challenge)
33
- raise HTTPException(status_code=403)
34
 
35
  @app.post("/webhook")
36
  async def receive_webhook(request: Request):
37
  data = await request.json()
38
  try:
39
- msg = data["entry"][0]["changes"][0]["value"]["messages"][0]
40
- wa_id = msg["from"]
41
- msg_type = msg["type"]
42
 
43
  if msg_type == "image":
44
- media_id = msg["image"]["id"]
45
- image_bytes = await download_whatsapp_media(media_id)
46
  if not image_bytes:
47
  return {"status": "error", "message": "Failed to process image"}
48
  b64_str = base64.b64encode(image_bytes).decode('utf-8')
49
- reply = f"Base64: {b64_str[:10]}"
50
  send_whatsapp_message(wa_id, reply)
51
  return {"status": "success", "base64_first_10": b64_str[:10]}
52
- else:
53
- send_whatsapp_message(wa_id, "Please send an image.")
54
- return {"status": "replied", "message": "Please send an image"}
 
 
55
  except Exception as e:
56
  print("Webhook error:", e)
57
  return JSONResponse(content={"error": str(e)}, status_code=400)
58
 
59
- async def download_whatsapp_media(media_id):
 
60
  try:
61
  with open("test.jpg", "rb") as f:
62
  return f.read()
@@ -64,10 +73,10 @@ async def download_whatsapp_media(media_id):
64
  print("test.jpg not found")
65
  return None
66
 
67
- def send_whatsapp_message(wa_id, text):
68
- url = f"https://graph.facebook.com/v19.0/{os.getenv('PHONE_NUMBER_ID')}/messages"
69
  headers = {
70
- "Authorization": f"Bearer {os.getenv('WHATSAPP_API_TOKEN')}",
71
  "Content-Type": "application/json"
72
  }
73
  payload = {
@@ -80,7 +89,6 @@ def send_whatsapp_message(wa_id, text):
80
 
81
  @app.post("/send")
82
  async def check_token():
83
- token = os.getenv("WHATSAPP_TOKEN", "")
84
- if token:
85
  return {"token_loaded": True}
86
- return JSONResponse(content={"error": "Token not found in environment"}, status_code=400)
 
1
  from fastapi import FastAPI, Request, Query, HTTPException
2
  from fastapi.responses import JSONResponse, PlainTextResponse
 
3
  import os
4
  import httpx
5
  import base64
6
 
7
  app = FastAPI()
8
+
9
+ # Load these once from env
10
+ VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "")
11
+ WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
12
+ PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
13
 
14
  @app.get("/")
15
  def root():
 
28
  return {"detail": "POST method working"}
29
 
30
  @app.get("/webhook")
31
+ async def verify(
32
+ hub_mode: str = Query(..., alias="hub.mode"),
33
+ hub_token: str = Query(..., alias="hub.verify_token"),
34
+ hub_challenge: str = Query(..., alias="hub.challenge")
35
+ ):
36
+ # Only succeed if Meta's token matches ours
37
+ if hub_mode == "subscribe" and hub_token == VERIFY_TOKEN:
38
  return PlainTextResponse(hub_challenge)
39
+ raise HTTPException(status_code=403, detail="Verification token mismatch")
40
 
41
  @app.post("/webhook")
42
  async def receive_webhook(request: Request):
43
  data = await request.json()
44
  try:
45
+ msg = data["entry"][0]["changes"][0]["value"]["messages"][0]
46
+ wa_id = msg["from"]
47
+ msg_type= msg["type"]
48
 
49
  if msg_type == "image":
50
+ media_id = msg["image"]["id"]
51
+ image_bytes= await download_whatsapp_media(media_id)
52
  if not image_bytes:
53
  return {"status": "error", "message": "Failed to process image"}
54
  b64_str = base64.b64encode(image_bytes).decode('utf-8')
55
+ reply = f"Base64: {b64_str[:10]}"
56
  send_whatsapp_message(wa_id, reply)
57
  return {"status": "success", "base64_first_10": b64_str[:10]}
58
+
59
+ # fallback for non-image
60
+ send_whatsapp_message(wa_id, "Please send an image.")
61
+ return {"status": "replied", "message": "Please send an image"}
62
+
63
  except Exception as e:
64
  print("Webhook error:", e)
65
  return JSONResponse(content={"error": str(e)}, status_code=400)
66
 
67
+ async def download_whatsapp_media(media_id: str) -> Optional[bytes]:
68
+ # stub: replace with real media download later
69
  try:
70
  with open("test.jpg", "rb") as f:
71
  return f.read()
 
73
  print("test.jpg not found")
74
  return None
75
 
76
+ def send_whatsapp_message(wa_id: str, text: str) -> None:
77
+ url = f"https://graph.facebook.com/v19.0/{PHONE_NUMBER_ID}/messages"
78
  headers = {
79
+ "Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
80
  "Content-Type": "application/json"
81
  }
82
  payload = {
 
89
 
90
  @app.post("/send")
91
  async def check_token():
92
+ if WHATSAPP_API_TOKEN:
 
93
  return {"token_loaded": True}
94
+ return JSONResponse(content={"error": "WHATSAPP_API_TOKEN not set"}, status_code=400)