-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathapp.py
81 lines (59 loc) · 2.47 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import logging
from agents import VERIFY_TOKEN, get_whatsapp_agent
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse
# Configure logging
logger = logging.getLogger(__name__)
# Initialize agent
agent = get_whatsapp_agent()
# Create FastAPI app
app = FastAPI()
@app.get("/webhook")
async def verify_webhook(request: Request):
"""Handle WhatsApp webhook verification"""
mode = request.query_params.get("hub.mode")
token = request.query_params.get("hub.verify_token")
challenge = request.query_params.get("hub.challenge")
if mode == "subscribe" and token == VERIFY_TOKEN:
if not challenge:
raise HTTPException(status_code=400, detail="No challenge received")
return PlainTextResponse(content=challenge)
raise HTTPException(status_code=403, detail="Invalid verify token or mode")
@app.post("/webhook")
async def handle_message(request: Request):
"""Handle incoming WhatsApp messages"""
try:
body = await request.json()
# Validate webhook data
if body.get("object") != "whatsapp_business_account":
logger.warning(
f"Received non-WhatsApp webhook object: {body.get('object')}"
)
return {"status": "ignored"}
# Process messages
for entry in body.get("entry", []):
for change in entry.get("changes", []):
messages = change.get("value", {}).get("messages", [])
if not messages:
continue
message = messages[0]
if message.get("type") != "text":
continue
# Extract message details
phone_number = message["from"]
message_text = message["text"]["body"]
logger.info(f"Processing message from {phone_number}: {message_text}")
# Generate and send response
response = agent.run(message_text)
agent.tools[0].send_text_message_sync(
recipient=phone_number, text=response.content
)
logger.info(f"Response sent to {phone_number}")
return {"status": "ok"}
except Exception as e:
logger.error(f"Error processing webhook: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
logger.info("Starting WhatsApp Bot Server")
uvicorn.run(app, host="0.0.0.0", port=8000)