Spaces:
Running
Running
Download backend/app/api/meta_webhooks.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/meta_webhooks.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/meta_webhooks.py
-
curl -L -o meta_webhooks.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/meta_webhooks.py
10.1 kB
| """ | |
| Meta Official Webhook Handler (WhatsApp & Instagram). | |
| Uses unified MessageProcessor for message handling. | |
| Handles verification (GET) and event notifications (POST). | |
| """ | |
| from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends, Query | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from uuid import UUID | |
| import logging | |
| from typing import Optional | |
| from app.core.database import get_async_session, async_session_maker | |
| from app.models.tenant import Tenant | |
| from app.services.message_processor import IncomingMessage, get_message_processor | |
| from app.services.meta_whatsapp import get_whatsapp_cloud_service | |
| from app.services.llm_client import get_llm_client | |
| from app.core.config import settings | |
| from app.core.limiter import limiter | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter(prefix="/webhook/meta", tags=["Meta Webhooks"]) | |
| # ========================================================================= | |
| # VERIFICATION (GET) | |
| # ========================================================================= | |
| async def verify_webhook( | |
| tenant_id: UUID, | |
| mode: str = Query(alias="hub.mode"), | |
| token: str = Query(alias="hub.verify_token"), | |
| challenge: str = Query(alias="hub.challenge"), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """Handle Meta Webhook Verification Challenge.""" | |
| logger.info(f"π Webhook verification attempt: tenant={tenant_id}, mode={mode}, token={token[:10]}...") | |
| tenant = await session.get(Tenant, tenant_id) | |
| if not tenant: | |
| logger.error(f"β Tenant {tenant_id} not found") | |
| raise HTTPException(status_code=404, detail="Tenant not found") | |
| # Get verify token from config or use default | |
| wa_verify = None | |
| if tenant.meta_wa_config: | |
| wa_verify = tenant.meta_wa_config.get("verify_token") | |
| # Fallback to default token for initial setup | |
| default_token = "microfunnel_webhook_2024" | |
| if mode == "subscribe" and (token == wa_verify or token == default_token): | |
| logger.info(f"β Webhook Verified for Tenant {tenant_id}") | |
| return int(challenge) | |
| logger.error(f"β Verification failed: expected={wa_verify or default_token}, got={token}") | |
| raise HTTPException(status_code=403, detail="Verification failed") | |
| # ========================================================================= | |
| # EVENT NOTIFICATION (POST) | |
| # ========================================================================= | |
| async def handle_meta_webhook( | |
| tenant_id: UUID, | |
| request: Request, | |
| background_tasks: BackgroundTasks, | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """Handle incoming events from Meta (WhatsApp & Instagram).""" | |
| try: | |
| data = await request.json() | |
| logger.info(f"π© Meta Webhook for Tenant {tenant_id}: {list(data.keys())}") | |
| except Exception: | |
| raise HTTPException(status_code=400, detail="Invalid JSON") | |
| tenant = await session.get(Tenant, tenant_id) | |
| if not tenant: | |
| return {"status": "ignored", "reason": "tenant_not_found"} | |
| # Process in background | |
| background_tasks.add_task( | |
| process_meta_event, | |
| tenant_id=tenant.id, | |
| payload=data | |
| ) | |
| return {"status": "ok"} | |
| # ========================================================================= | |
| # EVENT PROCESSING | |
| # ========================================================================= | |
| async def process_meta_event(tenant_id: UUID, payload: dict): | |
| """Parse and route Meta event by platform.""" | |
| object_type = payload.get("object") | |
| if object_type == "whatsapp_business": | |
| await process_whatsapp_event(tenant_id, payload) | |
| elif object_type == "instagram": | |
| # TODO: Implement Instagram | |
| logger.info("Instagram event received (not implemented)") | |
| else: | |
| logger.warning(f"Unknown Meta object type: {object_type}") | |
| async def process_whatsapp_event(tenant_id: UUID, payload: dict): | |
| """Process WhatsApp Business API event.""" | |
| try: | |
| entry = payload.get("entry", [])[0] | |
| changes = entry.get("changes", [])[0] | |
| value = changes.get("value", {}) | |
| if "messages" not in value: | |
| return # Status update or other event | |
| message = value["messages"][0] | |
| contact = value.get("contacts", [])[0] if "contacts" in value else {} | |
| sender_id = message.get("from") | |
| sender_name = contact.get("profile", {}).get("name", f"User {sender_id}") | |
| msg_type = message.get("type") | |
| text = "" | |
| is_voice = False | |
| media_id = None | |
| media_mime = None | |
| if msg_type == "text": | |
| text = message["text"]["body"] | |
| elif msg_type == "audio": | |
| media_id = message["audio"]["id"] | |
| media_mime = message["audio"].get("mime_type") | |
| is_voice = True # Will transcribe | |
| text = "[Voice Message]" | |
| elif msg_type == "image": | |
| media_id = message["image"]["id"] | |
| media_mime = message["image"].get("mime_type") | |
| text = message["image"].get("caption", "[Image]") | |
| elif msg_type == "document": | |
| media_id = message["document"]["id"] | |
| media_mime = message["document"].get("mime_type") | |
| text = message["document"].get("caption", "[Document]") | |
| else: | |
| text = f"[{msg_type} not supported]" | |
| # Use unified processor | |
| await process_whatsapp_message( | |
| tenant_id=tenant_id, | |
| sender_id=sender_id, | |
| sender_name=sender_name, | |
| text=text, | |
| is_voice=is_voice, | |
| media_id=media_id | |
| ) | |
| except (IndexError, KeyError) as e: | |
| logger.error(f"Error parsing WhatsApp payload: {e}") | |
| async def process_whatsapp_message( | |
| tenant_id: UUID, | |
| sender_id: str, | |
| sender_name: str, | |
| text: str, | |
| is_voice: bool = False, | |
| media_id: Optional[str] = None | |
| ): | |
| """Process WhatsApp message using unified MessageProcessor.""" | |
| from app.core.supabase import supabase_client | |
| import time | |
| import re | |
| async with async_session_maker() as session: | |
| try: | |
| tenant = await session.get(Tenant, tenant_id) | |
| if not tenant: | |
| logger.error(f"Tenant {tenant_id} not found") | |
| return | |
| # Message Processing Vars | |
| media_url = None | |
| media_type = None | |
| # Handle Media Download | |
| if media_id: | |
| try: | |
| wa_service = get_whatsapp_cloud_service() | |
| content, mime = await wa_service.download_media(tenant, media_id) | |
| if is_voice: | |
| try: | |
| # Transcribe Voice | |
| llm = get_llm_client() | |
| transcript = await llm.transcribe_audio(content, mime_type=mime) | |
| text = f"[Voice] {transcript}" | |
| except Exception as e: | |
| logger.error(f"Transcription failed: {e}") | |
| text += " (Failed to transcribe)" | |
| # Upload to Supabase | |
| if supabase_client: | |
| bucket = "chat-attachments" | |
| ts = int(time.time()) | |
| # safe name? We don't have filename from WA easily, use generic | |
| ext = mime.split('/')[-1] | |
| filename = f"wa_{media_id}.{ext}" | |
| path = f"{tenant.id}/incoming/{ts}_{filename}" | |
| supabase_client.storage.from_(bucket).upload( | |
| path=path, file=content, file_options={"content-type": mime} | |
| ) | |
| media_url = supabase_client.storage.from_(bucket).get_public_url(path) | |
| media_type = mime | |
| logger.info(f"π WhatsApp Media uploaded: {media_url}") | |
| except Exception as e: | |
| logger.error(f"WhatsApp Media processing failed: {e}") | |
| # Build incoming message | |
| incoming = IncomingMessage( | |
| channel="whatsapp", | |
| sender_id=sender_id, | |
| sender_name=sender_name, | |
| text=text, | |
| is_voice=is_voice, | |
| media_url=media_url, | |
| media_type=media_type | |
| ) | |
| # Process with unified MessageProcessor | |
| processor = get_message_processor() | |
| result = await processor.process(session, tenant, incoming) | |
| # Send response via WhatsApp Cloud API | |
| wa_service = get_whatsapp_cloud_service() | |
| if result["is_voice_reply"] and settings.OPENAI_API_KEY: | |
| # Send voice reply | |
| try: | |
| llm = get_llm_client() | |
| audio_bytes = await llm.generate_speech(result["response_text"]) | |
| media_id = await wa_service.upload_media(tenant, audio_bytes) | |
| await wa_service.send_audio_message(tenant, sender_id, media_id) | |
| logger.info(f"π£οΈ Voice reply sent to {sender_id}") | |
| except Exception as e: | |
| logger.error(f"Voice send failed, falling back to text: {e}") | |
| await wa_service.send_text_message(tenant, sender_id, result["response_text"]) | |
| else: | |
| # Send text reply | |
| await wa_service.send_text_message( | |
| tenant=tenant, | |
| to_phone=sender_id, | |
| text=result["response_text"] | |
| ) | |
| logger.info(f"β WhatsApp reply sent to {sender_id}") | |
| except Exception as e: | |
| logger.error(f"Error processing WhatsApp message: {e}", exc_info=True) | |