devZenaight commited on
Commit
876265d
·
verified ·
1 Parent(s): c08bda7

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +27 -29
main.py CHANGED
@@ -1,15 +1,13 @@
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():
@@ -29,43 +27,40 @@ async def test_post():
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,10 +68,11 @@ async def download_whatsapp_media(media_id: str) -> Optional[bytes]:
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,6 +85,8 @@ def send_whatsapp_message(wa_id: str, text: str) -> None:
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)
 
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
+ # Load verify token once from env
10
+ VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "")
 
 
 
11
 
12
  @app.get("/")
13
  def root():
 
27
 
28
  @app.get("/webhook")
29
  async def verify(
30
+ hub_mode: str = Query(..., alias="hub.mode"),
31
+ hub_token: str = Query(..., alias="hub.verify_token"),
32
+ hub_challenge: str= Query(..., alias="hub.challenge")
33
+ ) :
34
+ # Only succeed if Meta's verify_token matches ours
35
  if hub_mode == "subscribe" and hub_token == VERIFY_TOKEN:
36
  return PlainTextResponse(hub_challenge)
37
+ raise HTTPException(status_code=403)
38
 
39
  @app.post("/webhook")
40
  async def receive_webhook(request: Request):
41
  data = await request.json()
42
  try:
43
+ msg = data["entry"][0]["changes"][0]["value"]["messages"][0]
44
+ wa_id = msg["from"]
45
+ msg_type = msg["type"]
46
 
47
  if msg_type == "image":
48
+ media_id = msg["image"]["id"]
49
+ image_bytes = await download_whatsapp_media(media_id)
50
  if not image_bytes:
51
  return {"status": "error", "message": "Failed to process image"}
52
  b64_str = base64.b64encode(image_bytes).decode('utf-8')
53
+ reply = f"Base64: {b64_str[:10]}"
54
  send_whatsapp_message(wa_id, reply)
55
  return {"status": "success", "base64_first_10": b64_str[:10]}
56
+ else:
57
+ send_whatsapp_message(wa_id, "Please send an image.")
58
+ return {"status": "replied", "message": "Please send an image"}
 
 
59
  except Exception as e:
60
  print("Webhook error:", e)
61
  return JSONResponse(content={"error": str(e)}, status_code=400)
62
 
63
+ async def download_whatsapp_media(media_id):
 
64
  try:
65
  with open("test.jpg", "rb") as f:
66
  return f.read()
 
68
  print("test.jpg not found")
69
  return None
70
 
71
+ def send_whatsapp_message(wa_id, text):
72
+ url = f"https://graph.facebook.com/v19.0/{os.getenv('PHONE_NUMBER_ID')}/messages"
73
  headers = {
74
+ # Use the single token name everywhere
75
+ "Authorization": f"Bearer {os.getenv('WHATSAPP_API_TOKEN', '')}",
76
  "Content-Type": "application/json"
77
  }
78
  payload = {
 
85
 
86
  @app.post("/send")
87
  async def check_token():
88
+ # Check the same token name that send_whatsapp_message() uses
89
+ token = os.getenv("WHATSAPP_API_TOKEN", "")
90
+ if token:
91
  return {"token_loaded": True}
92
+ return JSONResponse(content={"error": "Token not found in environment"}, status_code=400)