chandrashekhar2002dubey commited on
Commit
6902fd6
·
1 Parent(s): 550e965

Added meta integration

Browse files
Files changed (1) hide show
  1. app.py +83 -1
app.py CHANGED
@@ -2,11 +2,14 @@ import json
2
  import os
3
  import logging
4
  import asyncio
 
 
 
5
  import lead_client
6
  from datetime import datetime
7
  from typing import Dict, Any, List
8
 
9
- from fastapi import FastAPI, HTTPException
10
  from pydantic import BaseModel
11
 
12
  from google import genai
@@ -261,6 +264,85 @@ def capture_lead(user: lead_client.User):
261
  "mobile": user.mobile, "name": user.name, "go_to_chat": True}
262
  return {"status": "error", "message": "Failed to save user", "go_to_chat": False}
263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
 
265
  if __name__ == "__main__":
266
  import uvicorn
 
2
  import os
3
  import logging
4
  import asyncio
5
+ import re
6
+
7
+ import httpx
8
  import lead_client
9
  from datetime import datetime
10
  from typing import Dict, Any, List
11
 
12
+ from fastapi import FastAPI, HTTPException, Request, Response
13
  from pydantic import BaseModel
14
 
15
  from google import genai
 
264
  "mobile": user.mobile, "name": user.name, "go_to_chat": True}
265
  return {"status": "error", "message": "Failed to save user", "go_to_chat": False}
266
 
267
+ # Configuration from your Meta Dashboard
268
+ VERIFY_TOKEN = "BuilderBot_2026_Secure"
269
+ META_ACCESS_TOKEN = "EAAMdfo77nSQBRJgiqBqgeEZBDqN1LLvGAuOSqJqpP8vc1Q3cCZCm4RSLcm3maURew0dFGcZCMSge0LEnZCVbJg1ZC0xU7DGqnncMClUOPxS8P6WALttiZAGBRO7UQsALZBjSzZBvAu9WHDTkuepFkOkDYWwBurNixbE7UrZA3MuaNzfG73qyZALktBu2M0KSlw1DqZBPKR8YPu1UmyZAHkZB20IeZC49ZBoyyorpxhRTZBR3RtvZB"
270
+ PHONE_NUMBER_ID = "1046536671883013"
271
+
272
+ @app.get("/webhook")
273
+ async def verify_meta_webhook(request: Request):
274
+ """Handles the initial verification handshake from Meta."""
275
+ params = request.query_params
276
+
277
+ # Meta sends these specific parameters
278
+ mode = params.get("hub.mode")
279
+ token = params.get("hub.verify_token")
280
+ challenge = params.get("hub.challenge")
281
+
282
+ # Check if this is a subscribe attempt and the token matches
283
+ if mode == "subscribe" and token == VERIFY_TOKEN:
284
+ logger.info("WEBHOOK_VERIFIED")
285
+ # Important: Return the challenge as plain text
286
+ return Response(content=str(challenge), media_type="text/plain")
287
+
288
+ logger.warning("WEBHOOK_VERIFICATION_FAILED")
289
+ return Response(content="Verification failed", status_code=403)
290
+
291
+ @app.post("/webhook")
292
+ async def handle_meta_message(request: Request):
293
+ """Handles incoming messages from WhatsApp/Instagram."""
294
+ data = await request.json()
295
+
296
+ try:
297
+ # 1. Extract message and user info (WhatsApp format example)
298
+ entry = data.get("entry", [{}])[0]
299
+ changes = entry.get("changes", [{}])[0]
300
+ value = changes.get("value", {})
301
+ message_obj = value.get("messages", [{}])[0]
302
+
303
+ org_id = "mathapathi" # Default fallback
304
+ match = re.search(r"\[REF:(\w+)\]", user_text)
305
+ if match:
306
+ org_id = match.group(1)
307
+ # Clean the tag out of the message so the AI doesn't see it
308
+ user_text = user_text.replace(match.group(0), "").strip()
309
+ if not message_obj:
310
+ return {"status": "no_message"}
311
+
312
+ user_mobile = message_obj.get("from") # The user's phone number
313
+ user_text = message_obj.get("text", {}).get("body")
314
+ user_name = value.get("contacts", [{}])[0].get("profile", {}).get("name", "New User")
315
+
316
+ # 2. Step 1: Automated Lead Registration
317
+ # We check if user exists; if not, we register them to a default org (e.g., 'mathapathi')
318
+ if not lead_client.check_user_exists(user_mobile):
319
+ logger.info(f"Registering new lead for org: {org_id}")
320
+ lead_client.save_user(user_name, user_mobile, org_id)
321
+
322
+ # 3. Step 2: Trigger the Chat Logic
323
+ ai_response_text = run_chat_loop(user_text, user_mobile)
324
+
325
+ # 4. Step 3: Send response back to WhatsApp
326
+ await send_whatsapp_message(user_mobile, ai_response_text)
327
+
328
+ except Exception as e:
329
+ logger.error(f"Webhook Error: {e}")
330
+
331
+ return {"status": "success"}
332
+
333
+ async def send_whatsapp_message(to_number: str, text: str):
334
+ """Helper to push the AI response back to the user's phone."""
335
+ url = f"https://graph.facebook.com/v25.0/{PHONE_NUMBER_ID}/messages"
336
+ headers = {"Authorization": f"Bearer {META_ACCESS_TOKEN}", "Content-Type": "application/json"}
337
+ payload = {
338
+ "messaging_product": "whatsapp",
339
+ "to": to_number,
340
+ "type": "text",
341
+ "text": {"body": text}
342
+ }
343
+ async with httpx.AsyncClient() as client:
344
+ await client.post(url, json=payload, headers=headers)
345
+
346
 
347
  if __name__ == "__main__":
348
  import uvicorn