devZenaight commited on
Commit
63c6763
·
verified ·
1 Parent(s): 4eaa4e3

Upload 5 files

Browse files
Files changed (3) hide show
  1. Dockerfile +6 -11
  2. main.py +19 -93
  3. requirements.txt +1 -2
Dockerfile CHANGED
@@ -1,12 +1,7 @@
1
- FROM python:3.9
2
-
3
- RUN useradd -m -u 1000 user
4
- USER user
5
- ENV PATH="/home/user/.local/bin:$PATH"
6
-
7
- WORKDIR /app
8
- COPY --chown=user . .
9
-
10
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
-
12
  CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
+ FROM python:3.11-slim
2
+ WORKDIR /code
3
+ COPY requirements.txt .
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+ COPY . .
6
+ EXPOSE 7860
 
 
 
 
 
7
  CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
main.py CHANGED
@@ -1,101 +1,27 @@
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
- PHONE_NUMBER_ID = os.getenv('PHONE_NUMBER_ID')
11
- WHATSAPP_API_TOKEN = os.getenv('WHATSAPP_API_TOKEN')
12
 
13
- if not all([VERIFY_TOKEN, WHATSAPP_API_TOKEN, PHONE_NUMBER_ID]):
14
- raise ValueError("Missing required environment variables")
15
 
16
- @app.get("/")
17
- def root():
18
- return {"message": "Hello from WhatsApp ChatBot"}
19
-
20
- @app.get("/ping")
21
- def ping():
22
- return {"pong": True}
23
-
24
- @app.get("/test")
25
- async def test_get():
26
- return {"detail": "GET method working"}
27
-
28
- @app.post("/test")
29
- async def test_post():
30
- return {"detail": "POST method working"}
31
-
32
- @app.get("/webhook")
33
  def verify(
34
- hub_mode: Optional[str] = Query(None, alias="hub.mode"),
35
- hub_challenge: Optional[str] = Query(None, alias="hub.challenge"),
36
- hub_verify_token: Optional[str] = Query(None, alias="hub.verify_token"),
37
  ):
38
- # 1) Initial probe
39
- if hub_mode is None and hub_challenge is None and hub_verify_token is None:
40
- return PlainTextResponse(status_code=200, content="")
41
-
42
- # 2) Real handshake: echo back challenge (temporarily ignore token)
43
- if hub_mode == "subscribe":
44
- return PlainTextResponse(content=hub_challenge or "", media_type="text/plain")
45
 
46
- # 3) Everything else → forbidden
47
- if hub_verify_token != VERIFY_TOKEN:
48
- raise HTTPException(status_code=403, detail="Invalid verify token")
 
 
49
 
50
- @app.post("/webhook")
51
- async def receive_webhook(request: Request):
52
- data = await request.json()
53
- try:
54
- msg = data["entry"][0]["changes"][0]["value"]["messages"][0]
55
- wa_id = msg["from"]
56
- msg_type = msg["type"]
57
-
58
- if msg_type == "image":
59
- media_id = msg["image"]["id"]
60
- image_bytes = await download_whatsapp_media(media_id)
61
- if not image_bytes:
62
- return {"status": "error", "message": "Failed to process image"}
63
- b64_str = base64.b64encode(image_bytes).decode('utf-8')
64
- reply = f"Base64: {b64_str[:10]}"
65
- send_whatsapp_message(wa_id, reply)
66
- return {"status": "success", "base64_first_10": b64_str[:10]}
67
- else:
68
- send_whatsapp_message(wa_id, "Please send an image.")
69
- return {"status": "replied", "message": "Please send an image"}
70
- except Exception as e:
71
- print("Webhook error:", e)
72
- return JSONResponse(content={"error": str(e)}, status_code=400)
73
-
74
- async def download_whatsapp_media(media_id):
75
- try:
76
- with open("test.jpg", "rb") as f:
77
- return f.read()
78
- except FileNotFoundError:
79
- print("test.jpg not found")
80
- return None
81
-
82
- def send_whatsapp_message(wa_id, text):
83
- url = f"https://graph.facebook.com/v19.0/{PHONE_NUMBER_ID}/messages"
84
- headers = {
85
- "Authorization": f"Bearer {WHATSAPP_API_TOKEN}",
86
- "Content-Type": "application/json"
87
- }
88
- payload = {
89
- "messaging_product": "whatsapp",
90
- "to": wa_id,
91
- "type": "text",
92
- "text": {"body": text}
93
- }
94
- httpx.post(url, headers=headers, json=payload)
95
-
96
- @app.post("/send")
97
- async def check_token():
98
- token = WHATSAPP_API_TOKEN
99
- if token:
100
- return {"token_loaded": True}
101
- return JSONResponse(content={"error": "Token not found in environment"}, status_code=400)
 
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(
11
+ hub_mode: str = Query(None, alias="hub.mode"),
12
+ hub_token: str = Query(None, alias="hub.verify_token"),
13
+ hub_challenge: str = Query(None, alias="hub.challenge")
14
  ):
15
+ if hub_mode == "subscribe" and hub_token == VERIFY_TOKEN:
16
+ return PlainTextResponse(hub_challenge)
17
+ raise HTTPException(status_code=403, detail="Invalid token")
 
 
 
 
18
 
19
+ @app.post("/webhook") # incoming messages
20
+ async def receive_update(req: Request):
21
+ data = await req.json()
22
+ print("WA update:", json.dumps(data)[:300])
23
+ return JSONResponse({"status": "received"})
24
 
25
+ @app.get("/ping") # health check
26
+ def ping():
27
+ return {"pong": True}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,3 +1,2 @@
1
  fastapi
2
- uvicorn
3
- httpx
 
1
  fastapi
2
+ uvicorn[standard]