Spaces:
Running
Running
axeronis commited on
Commit ·
e07475a
1
Parent(s): c5b11a5
feat: Add WhatsApp Cloud API integration - no QR codes needed!
Browse files- backend/app/api/channels.py +98 -8
- backend/app/core/config.py +0 -15
- backend/app/services/whatsapp_cloud.py +218 -0
- baileys-whatsapp-service +1 -0
- evolution-api-deploy +1 -0
backend/app/api/channels.py
CHANGED
|
@@ -12,7 +12,7 @@ from app.core.config import settings
|
|
| 12 |
from app.core.logging import get_logger
|
| 13 |
from app.models import User
|
| 14 |
from app.api.deps import get_current_user
|
| 15 |
-
from app.services.
|
| 16 |
from app.services.linkedin_service import linkedin_service
|
| 17 |
|
| 18 |
logger = get_logger(__name__)
|
|
@@ -383,18 +383,108 @@ async def get_whatsapp_qr_status(
|
|
| 383 |
raise HTTPException(status_code=500, detail=f"Status check error: {str(e)}")
|
| 384 |
|
| 385 |
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
current_user: User = Depends(get_current_user),
|
| 389 |
session = Depends(get_session)
|
| 390 |
):
|
| 391 |
"""
|
| 392 |
-
|
| 393 |
"""
|
| 394 |
try:
|
| 395 |
-
tenant_id =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
| 399 |
return {
|
| 400 |
"ok": True,
|
|
@@ -403,5 +493,5 @@ async def disconnect_whatsapp_qr(
|
|
| 403 |
}
|
| 404 |
|
| 405 |
except Exception as e:
|
| 406 |
-
logger.error(f"Failed to disconnect WhatsApp
|
| 407 |
-
raise HTTPException(status_code=500, detail=
|
|
|
|
| 12 |
from app.core.logging import get_logger
|
| 13 |
from app.models import User
|
| 14 |
from app.api.deps import get_current_user
|
| 15 |
+
from app.services.whatsapp_cloud import whatsapp_cloud_service
|
| 16 |
from app.services.linkedin_service import linkedin_service
|
| 17 |
|
| 18 |
logger = get_logger(__name__)
|
|
|
|
| 383 |
raise HTTPException(status_code=500, detail=f"Status check error: {str(e)}")
|
| 384 |
|
| 385 |
|
| 386 |
+
# ==================== WHATSAPP CLOUD API ENDPOINTS ====================
|
| 387 |
+
|
| 388 |
+
class WhatsAppConnectRequest(BaseModel):
|
| 389 |
+
"""WhatsApp Cloud API connection request."""
|
| 390 |
+
access_token: str
|
| 391 |
+
phone_number_id: str
|
| 392 |
+
business_account_id: str
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@router.post("/whatsapp/connect")
|
| 396 |
+
async def connect_whatsapp(
|
| 397 |
+
request: WhatsAppConnectRequest,
|
| 398 |
current_user: User = Depends(get_current_user),
|
| 399 |
session = Depends(get_session)
|
| 400 |
):
|
| 401 |
"""
|
| 402 |
+
Connect WhatsApp Cloud API - no QR codes needed!
|
| 403 |
"""
|
| 404 |
try:
|
| 405 |
+
tenant_id = current_user.tenant_id
|
| 406 |
+
|
| 407 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 408 |
+
if not tenant:
|
| 409 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 410 |
+
|
| 411 |
+
# Store credentials (in production, encrypt these!)
|
| 412 |
+
config = {
|
| 413 |
+
"access_token": request.access_token.strip(),
|
| 414 |
+
"phone_number_id": request.phone_number_id.strip(),
|
| 415 |
+
"business_account_id": request.business_account_id.strip()
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
tenant.whatsapp_config = config
|
| 419 |
+
tenant.whatsapp_connected = True
|
| 420 |
+
|
| 421 |
+
await session.commit()
|
| 422 |
+
|
| 423 |
+
return {
|
| 424 |
+
"ok": True,
|
| 425 |
+
"status": "connected",
|
| 426 |
+
"message": "WhatsApp Cloud API connected successfully!",
|
| 427 |
+
"phone_number_id": request.phone_number_id
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
except Exception as e:
|
| 431 |
+
logger.error(f"Failed to connect WhatsApp: {e}")
|
| 432 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
@router.get("/whatsapp/status")
|
| 436 |
+
async def get_whatsapp_status(
|
| 437 |
+
current_user: User = Depends(get_current_user),
|
| 438 |
+
session = Depends(get_session)
|
| 439 |
+
):
|
| 440 |
+
"""
|
| 441 |
+
Get WhatsApp connection status.
|
| 442 |
+
"""
|
| 443 |
+
try:
|
| 444 |
+
tenant_id = current_user.tenant_id
|
| 445 |
+
|
| 446 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 447 |
+
if not tenant:
|
| 448 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 449 |
+
|
| 450 |
+
if not tenant.whatsapp_connected or not tenant.whatsapp_config:
|
| 451 |
+
return {
|
| 452 |
+
"connected": False,
|
| 453 |
+
"status": "disconnected"
|
| 454 |
+
}
|
| 455 |
|
| 456 |
+
config = tenant.whatsapp_config
|
| 457 |
+
|
| 458 |
+
return {
|
| 459 |
+
"connected": True,
|
| 460 |
+
"status": "active",
|
| 461 |
+
"phone_number_id": config.get("phone_number_id", "Unknown")
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
except Exception as e:
|
| 465 |
+
logger.error(f"Failed to check WhatsApp status: {e}")
|
| 466 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
@router.post("/whatsapp/disconnect")
|
| 470 |
+
async def disconnect_whatsapp(
|
| 471 |
+
current_user: User = Depends(get_current_user),
|
| 472 |
+
session = Depends(get_session)
|
| 473 |
+
):
|
| 474 |
+
"""
|
| 475 |
+
Disconnect WhatsApp Cloud API.
|
| 476 |
+
"""
|
| 477 |
+
try:
|
| 478 |
+
tenant_id = current_user.tenant_id
|
| 479 |
+
|
| 480 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 481 |
+
if not tenant:
|
| 482 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 483 |
+
|
| 484 |
+
tenant.whatsapp_connected = False
|
| 485 |
+
tenant.whatsapp_config = None
|
| 486 |
+
|
| 487 |
+
await session.commit()
|
| 488 |
|
| 489 |
return {
|
| 490 |
"ok": True,
|
|
|
|
| 493 |
}
|
| 494 |
|
| 495 |
except Exception as e:
|
| 496 |
+
logger.error(f"Failed to disconnect WhatsApp: {e}")
|
| 497 |
+
raise HTTPException(status_code=500, detail=str(e))
|
backend/app/core/config.py
CHANGED
|
@@ -45,21 +45,6 @@ class Settings(BaseSettings):
|
|
| 45 |
|
| 46 |
# Telegram
|
| 47 |
TELEGRAM_BOT_TOKEN: Optional[str] = None
|
| 48 |
-
TELEGRAM_WEBHOOK_URL: Optional[str] = None
|
| 49 |
-
|
| 50 |
-
# Meta OAuth (Instagram & WhatsApp)
|
| 51 |
-
META_APP_ID: Optional[str] = None
|
| 52 |
-
META_APP_SECRET: Optional[str] = None
|
| 53 |
-
|
| 54 |
-
# Evolution API (WhatsApp Web QR)
|
| 55 |
-
EVOLUTION_API_URL: str = "http://localhost:8080"
|
| 56 |
-
EVOLUTION_API_KEY: str = "evolution-api-key"
|
| 57 |
-
|
| 58 |
-
# Vector embeddings
|
| 59 |
-
EMBEDDING_MODEL: str = "all-MiniLM-L6-v2"
|
| 60 |
-
EMBEDDING_DIMENSION: int = 384
|
| 61 |
-
|
| 62 |
-
# AI Settings
|
| 63 |
MAX_CONTEXT_MESSAGES: int = 50 # Increased from 20 to capture full conversation context
|
| 64 |
TEMPERATURE: float = 0.7
|
| 65 |
MAX_TOKENS: int = 1024
|
|
|
|
| 45 |
|
| 46 |
# Telegram
|
| 47 |
TELEGRAM_BOT_TOKEN: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
MAX_CONTEXT_MESSAGES: int = 50 # Increased from 20 to capture full conversation context
|
| 49 |
TEMPERATURE: float = 0.7
|
| 50 |
MAX_TOKENS: int = 1024
|
backend/app/services/whatsapp_cloud.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
WhatsApp Cloud API Service
|
| 3 |
+
Official WhatsApp Business API from Meta
|
| 4 |
+
"""
|
| 5 |
+
import httpx
|
| 6 |
+
from typing import Dict, Optional
|
| 7 |
+
from app.core.config import settings
|
| 8 |
+
from app.core.logging import get_logger
|
| 9 |
+
|
| 10 |
+
logger = get_logger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class WhatsAppCloudService:
|
| 14 |
+
"""WhatsApp Cloud API integration"""
|
| 15 |
+
|
| 16 |
+
def __init__(self):
|
| 17 |
+
self.access_token = getattr(settings, 'WHATSAPP_ACCESS_TOKEN', None)
|
| 18 |
+
self.phone_number_id = getattr(settings, 'WHATSAPP_PHONE_NUMBER_ID', None)
|
| 19 |
+
self.business_account_id = getattr(settings, 'WHATSAPP_BUSINESS_ACCOUNT_ID', None)
|
| 20 |
+
self.api_version = "v18.0"
|
| 21 |
+
self.base_url = f"https://graph.facebook.com/{self.api_version}"
|
| 22 |
+
|
| 23 |
+
def is_configured(self) -> bool:
|
| 24 |
+
"""Check if WhatsApp Cloud API is configured"""
|
| 25 |
+
return bool(self.access_token and self.phone_number_id)
|
| 26 |
+
|
| 27 |
+
async def send_message(self, to: str, message: str) -> Dict:
|
| 28 |
+
"""
|
| 29 |
+
Send text message via WhatsApp Cloud API
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
to: Recipient phone number (with country code, no +)
|
| 33 |
+
message: Text message to send
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
API response dict
|
| 37 |
+
"""
|
| 38 |
+
if not self.is_configured():
|
| 39 |
+
raise Exception("WhatsApp Cloud API not configured")
|
| 40 |
+
|
| 41 |
+
url = f"{self.base_url}/{self.phone_number_id}/messages"
|
| 42 |
+
|
| 43 |
+
headers = {
|
| 44 |
+
"Authorization": f"Bearer {self.access_token}",
|
| 45 |
+
"Content-Type": "application/json"
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
payload = {
|
| 49 |
+
"messaging_product": "whatsapp",
|
| 50 |
+
"recipient_type": "individual",
|
| 51 |
+
"to": to,
|
| 52 |
+
"type": "text",
|
| 53 |
+
"text": {
|
| 54 |
+
"preview_url": False,
|
| 55 |
+
"body": message
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 61 |
+
response = await client.post(url, json=payload, headers=headers)
|
| 62 |
+
|
| 63 |
+
if response.status_code == 200:
|
| 64 |
+
data = response.json()
|
| 65 |
+
logger.info(f"Message sent to {to}: {data}")
|
| 66 |
+
return {
|
| 67 |
+
"success": True,
|
| 68 |
+
"message_id": data.get("messages", [{}])[0].get("id"),
|
| 69 |
+
"data": data
|
| 70 |
+
}
|
| 71 |
+
else:
|
| 72 |
+
error_data = response.json()
|
| 73 |
+
logger.error(f"Failed to send message: {error_data}")
|
| 74 |
+
return {
|
| 75 |
+
"success": False,
|
| 76 |
+
"error": error_data.get("error", {}).get("message", "Unknown error")
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"WhatsApp send error: {str(e)}")
|
| 81 |
+
return {
|
| 82 |
+
"success": False,
|
| 83 |
+
"error": str(e)
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
async def send_template(self, to: str, template_name: str, language_code: str = "en_US") -> Dict:
|
| 87 |
+
"""
|
| 88 |
+
Send template message (for initial contact)
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
to: Recipient phone number
|
| 92 |
+
template_name: Template name (e.g., "hello_world")
|
| 93 |
+
language_code: Language code (default: en_US)
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
API response dict
|
| 97 |
+
"""
|
| 98 |
+
if not self.is_configured():
|
| 99 |
+
raise Exception("WhatsApp Cloud API not configured")
|
| 100 |
+
|
| 101 |
+
url = f"{self.base_url}/{self.phone_number_id}/messages"
|
| 102 |
+
|
| 103 |
+
headers = {
|
| 104 |
+
"Authorization": f"Bearer {self.access_token}",
|
| 105 |
+
"Content-Type": "application/json"
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
payload = {
|
| 109 |
+
"messaging_product": "whatsapp",
|
| 110 |
+
"to": to,
|
| 111 |
+
"type": "template",
|
| 112 |
+
"template": {
|
| 113 |
+
"name": template_name,
|
| 114 |
+
"language": {
|
| 115 |
+
"code": language_code
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 122 |
+
response = await client.post(url, json=payload, headers=headers)
|
| 123 |
+
|
| 124 |
+
if response.status_code == 200:
|
| 125 |
+
data = response.json()
|
| 126 |
+
logger.info(f"Template sent to {to}: {data}")
|
| 127 |
+
return {
|
| 128 |
+
"success": True,
|
| 129 |
+
"message_id": data.get("messages", [{}])[0].get("id"),
|
| 130 |
+
"data": data
|
| 131 |
+
}
|
| 132 |
+
else:
|
| 133 |
+
error_data = response.json()
|
| 134 |
+
logger.error(f"Failed to send template: {error_data}")
|
| 135 |
+
return {
|
| 136 |
+
"success": False,
|
| 137 |
+
"error": error_data.get("error", {}).get("message", "Unknown error")
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
logger.error(f"WhatsApp template error: {str(e)}")
|
| 142 |
+
return {
|
| 143 |
+
"success": False,
|
| 144 |
+
"error": str(e)
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
def verify_webhook(self, mode: str, token: str, challenge: str) -> Optional[str]:
|
| 148 |
+
"""
|
| 149 |
+
Verify webhook subscription
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
mode: Verification mode
|
| 153 |
+
token: Verification token
|
| 154 |
+
challenge: Challenge string
|
| 155 |
+
|
| 156 |
+
Returns:
|
| 157 |
+
Challenge if verified, None otherwise
|
| 158 |
+
"""
|
| 159 |
+
verify_token = getattr(settings, 'WHATSAPP_WEBHOOK_VERIFY_TOKEN', 'default_verify_token')
|
| 160 |
+
|
| 161 |
+
if mode == "subscribe" and token == verify_token:
|
| 162 |
+
logger.info("Webhook verified successfully")
|
| 163 |
+
return challenge
|
| 164 |
+
else:
|
| 165 |
+
logger.warning("Webhook verification failed")
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
def process_webhook(self, data: Dict) -> Optional[Dict]:
|
| 169 |
+
"""
|
| 170 |
+
Process incoming webhook from WhatsApp
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
data: Webhook payload
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
Processed message data or None
|
| 177 |
+
"""
|
| 178 |
+
try:
|
| 179 |
+
# Extract message from webhook
|
| 180 |
+
entry = data.get("entry", [{}])[0]
|
| 181 |
+
changes = entry.get("changes", [{}])[0]
|
| 182 |
+
value = changes.get("value", {})
|
| 183 |
+
|
| 184 |
+
messages = value.get("messages", [])
|
| 185 |
+
if not messages:
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
message = messages[0]
|
| 189 |
+
|
| 190 |
+
# Extract message details
|
| 191 |
+
from_number = message.get("from")
|
| 192 |
+
message_id = message.get("id")
|
| 193 |
+
timestamp = message.get("timestamp")
|
| 194 |
+
|
| 195 |
+
# Get message content
|
| 196 |
+
message_type = message.get("type")
|
| 197 |
+
text = None
|
| 198 |
+
|
| 199 |
+
if message_type == "text":
|
| 200 |
+
text = message.get("text", {}).get("body")
|
| 201 |
+
|
| 202 |
+
logger.info(f"Received message from {from_number}: {text}")
|
| 203 |
+
|
| 204 |
+
return {
|
| 205 |
+
"from": from_number,
|
| 206 |
+
"message_id": message_id,
|
| 207 |
+
"timestamp": timestamp,
|
| 208 |
+
"type": message_type,
|
| 209 |
+
"text": text
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
except Exception as e:
|
| 213 |
+
logger.error(f"Webhook processing error: {str(e)}")
|
| 214 |
+
return None
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# Global instance
|
| 218 |
+
whatsapp_cloud_service = WhatsAppCloudService()
|
baileys-whatsapp-service
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit c98c90b10e8d662f4218702448ab582796868d9d
|
evolution-api-deploy
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit 4376169bf05ce187585f6b73598b807ce221dc33
|