Spaces:
Running

microfunnel-api / backend /app /services /message_processor.py
axeronis
feat(security): implement rate limiting and kill switch for anti-spam protection
895402e
Raw History Blame Contribute Delete
11.5 kB
"""
Message Processor Service
Unified message processing logic for all webhook handlers.
Handles: Lead/Conversation lookup, message storage, AI response, sending.
Used by:
- telegram_webhook.py
- meta_webhooks.py
- webhook.py (email)
"""
from typing import List, Optional, Dict, Any
from uuid import UUID
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
import logging
from datetime import datetime, timedelta
from app.models.tenant import Tenant
from app.models.lead import Lead, Message, Conversation, MessageStatus
from app.services.ai_core import get_ai_core
from app.core.config import settings
logger = logging.getLogger(__name__)
# =============================================================================
# Data Classes for Clean Interface
# =============================================================================
class IncomingMessage:
"""Represents an incoming message from any channel."""
def __init__(
self,
channel: str, # "telegram", "whatsapp", "instagram", "email"
sender_id: str, # Unique ID (phone, telegram_id, email)
sender_name: str,
text: str,
is_voice: bool = False,
media_url: Optional[str] = None,
media_type: Optional[str] = None,
raw_payload: Optional[Dict[str, Any]] = None
):
self.channel = channel
self.sender_id = sender_id
self.sender_name = sender_name
self.text = text
self.is_voice = is_voice
self.media_url = media_url
self.media_type = media_type
self.raw_payload = raw_payload or {}
# =============================================================================
# Lead/Conversation Management
# =============================================================================
async def get_or_create_lead(
session: AsyncSession,
tenant_id: UUID,
channel: str,
sender_id: str,
sender_name: str
) -> Lead:
"""
Find existing lead or create new one.
Matches by channel-specific ID (telegram_id, whatsapp_id, email).
"""
# Build query based on channel
if channel == "telegram":
stmt = select(Lead).where(
Lead.tenant_id == tenant_id,
Lead.telegram_id == sender_id
)
elif channel in ("whatsapp", "instagram"):
stmt = select(Lead).where(
Lead.tenant_id == tenant_id,
Lead.whatsapp_id == sender_id
)
else: # email
stmt = select(Lead).where(
Lead.tenant_id == tenant_id,
Lead.email == sender_id
)
result = await session.execute(stmt)
lead = result.scalar_one_or_none()
if not lead:
# Create new lead with channel-specific ID
lead_data = {
"tenant_id": tenant_id,
"name": sender_name,
"status": "NEW",
"processing_status": "idle"
}
if channel == "telegram":
lead_data["telegram_id"] = sender_id
elif channel in ("whatsapp", "instagram"):
lead_data["whatsapp_id"] = sender_id
else:
lead_data["email"] = sender_id
lead = Lead(**lead_data)
session.add(lead)
await session.flush()
logger.info(f"✨ Created new lead {lead.id} for {channel}:{sender_id}")
return lead
async def get_or_create_conversation(
session: AsyncSession,
tenant_id: UUID,
lead_id: UUID,
channel: str
) -> Conversation:
"""Find active conversation or create new one."""
stmt = select(Conversation).where(
Conversation.tenant_id == tenant_id,
Conversation.lead_id == lead_id,
Conversation.channel == channel,
Conversation.is_active == True
)
result = await session.execute(stmt)
conversation = result.scalar_one_or_none()
if not conversation:
conversation = Conversation(
tenant_id=tenant_id,
lead_id=lead_id,
channel=channel,
is_active=True
)
session.add(conversation)
await session.flush()
logger.info(f"✨ Created new conversation {conversation.id}")
return conversation
async def get_conversation_history(
session: AsyncSession,
conversation_id: UUID
) -> List[Message]:
"""Get all messages in conversation ordered by time."""
stmt = select(Message).where(
Message.conversation_id == conversation_id
).order_by(Message.created_at)
result = await session.execute(stmt)
return list(result.scalars().all())
# =============================================================================
# Message Processing
# =============================================================================
async def save_user_message(
session: AsyncSession,
tenant_id: UUID,
conversation_id: UUID,
text: str,
media_url: Optional[str] = None,
media_type: Optional[str] = None
) -> Message:
"""Save incoming user message to database."""
message = Message(
tenant_id=tenant_id,
conversation_id=conversation_id,
sender_type="user",
content=text,
media_url=media_url,
media_type=media_type
)
session.add(message)
await session.flush()
return message
async def save_ai_message(
session: AsyncSession,
tenant_id: UUID,
conversation_id: UUID,
text: str,
tokens: Dict[str, int] = None
) -> Message:
"""Save AI response message to database."""
tokens = tokens or {}
message = Message(
tenant_id=tenant_id,
conversation_id=conversation_id,
sender_type="ai",
content=text,
prompt_tokens=tokens.get("prompt_tokens"),
completion_tokens=tokens.get("completion_tokens"),
model_used=settings.GEMINI_MODEL,
status=MessageStatus.PENDING
)
session.add(message)
await session.flush()
return message
async def generate_ai_response(
session: AsyncSession,
tenant: Tenant,
lead: Lead,
user_message: str,
conversation_history: List[Message],
media_url: Optional[str] = None,
media_type: Optional[str] = None
) -> Dict[str, Any]:
"""Generate AI sales response using AICore."""
ai_core = get_ai_core()
response = await ai_core.generate_sales_response(
session=session,
tenant=tenant,
lead=lead,
user_message=user_message,
conversation_history=conversation_history,
media_url=media_url,
media_type=media_type
)
return response
# =============================================================================
# Main Processing Function
# =============================================================================
async def process_incoming_message(
session: AsyncSession,
tenant: Tenant,
message: IncomingMessage
) -> Dict[str, Any]:
"""
Unified message processing pipeline.
Steps:
1. Find/Create Lead
2. Find/Create Conversation
3. Save User Message
4. Generate AI Response
5. Save AI Message
6. Return response for sending
Returns:
Dict with keys: lead, conversation, user_message, ai_message, response_text
"""
# 1. Find/Create Lead
lead = await get_or_create_lead(
session=session,
tenant_id=tenant.id,
channel=message.channel,
sender_id=message.sender_id,
sender_name=message.sender_name
)
lead.last_message_at = datetime.utcnow()
lead.processing_status = "generating"
session.add(lead)
# 2. Find/Create Conversation
conversation = await get_or_create_conversation(
session=session,
tenant_id=tenant.id,
lead_id=lead.id,
channel=message.channel
)
# 3. Save User Message
user_msg = await save_user_message(
session=session,
tenant_id=tenant.id,
conversation_id=conversation.id,
text=message.text,
media_url=message.media_url,
media_type=message.media_type
)
await session.commit()
# 4. ANTI-SPAM: Kill Switch (Max 50 messages per hour)
one_hour_ago = datetime.utcnow() - timedelta(hours=1)
count_stmt = select(func.count(Message.id)).where(
Message.conversation_id == conversation.id,
Message.sender_type == "user",
Message.created_at >= one_hour_ago
)
msg_count_res = await session.execute(count_stmt)
msg_count = msg_count_res.scalar_one()
if msg_count > 50:
logger.warning(
f"🚨 KILL SWITCH ACTIVATED: Lead {lead.id} sent {msg_count} messages in 1 hour. Disabling AI."
)
conversation.human_takeover = True
lead.needs_attention = True
lead.processing_status = "idle"
session.add(conversation)
session.add(lead)
await session.commit()
# Notify Manager
from app.services.notification import notification_service
await notification_service.notify_kill_switch(
tenant=tenant,
lead=lead,
msg_count=msg_count
)
return {
"lead": lead,
"conversation": conversation,
"user_message": user_msg,
"ai_message": None,
"response_text": "(ИИ временно отключен из-за подозрительной активности. Ожидайте ответа менеджера.)",
"is_voice_reply": False
}
# 5. Get History & Generate AI Response
history = await get_conversation_history(session, conversation.id)
response = await generate_ai_response(
session=session,
tenant=tenant,
lead=lead,
user_message=message.text,
conversation_history=history,
media_url=message.media_url,
media_type=message.media_type
)
# 6. Save AI Message
ai_msg = await save_ai_message(
session=session,
tenant_id=tenant.id,
conversation_id=conversation.id,
text=response["text"],
tokens={
"prompt_tokens": response.get("prompt_tokens"),
"completion_tokens": response.get("completion_tokens")
}
)
lead.processing_status = "idle"
session.add(lead)
await session.commit()
return {
"lead": lead,
"conversation": conversation,
"user_message": user_msg,
"ai_message": ai_msg,
"response_text": response["text"],
"is_voice_reply": message.is_voice
}
# =============================================================================
# Singleton
# =============================================================================
class MessageProcessor:
"""Facade for message processing service."""
async def process(
self,
session: AsyncSession,
tenant: Tenant,
message: IncomingMessage
) -> Dict[str, Any]:
return await process_incoming_message(session, tenant, message)
_processor_instance: Optional[MessageProcessor] = None
def get_message_processor() -> MessageProcessor:
"""Get message processor instance."""
global _processor_instance
if _processor_instance is None:
_processor_instance = MessageProcessor()
return _processor_instance