TonyMoralist's picture
Upload 55 files
5c1ff2b verified
Raw History Blame Contribute Delete
4.2 kB
import httpx
from typing import Optional, Dict, Any
import json
from app.config import settings
class WebhookService:
"""Service for sending webhooks to external services (CRM, etc.)"""
async def send_webhook(
self,
url: str,
payload: Dict[str, Any],
headers: Optional[Dict[str, str]] = None,
timeout: int = 10
) -> bool:
"""Send webhook to external URL"""
default_headers = {
"Content-Type": "application/json",
"User-Agent": "ChatBotAI/1.0"
}
if headers:
default_headers.update(headers)
try:
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.post(
url,
json=payload,
headers=default_headers
)
return response.status_code in [200, 201, 202, 204]
except Exception as e:
print(f"Error sending webhook: {e}")
return False
async def send_lead_to_crm(
self,
webhook_url: str,
bot_name: str,
lead_name: Optional[str],
lead_phone: Optional[str],
lead_email: Optional[str],
source: str = "chatbot",
custom_data: Optional[Dict[str, Any]] = None
) -> bool:
"""Send lead data to CRM via webhook"""
payload = {
"event": "new_lead",
"timestamp": settings.Datetime.utcnow().isoformat(),
"bot": {
"name": bot_name
},
"lead": {
"name": lead_name,
"phone": lead_phone,
"email": lead_email,
"source": source
}
}
if custom_data:
payload["custom_data"] = custom_data
return await self.send_webhook(webhook_url, payload)
async def send_to_amocrm(
self,
webhook_url: str,
lead_name: str,
lead_phone: Optional[str],
lead_email: Optional[str],
pipeline_id: int = 1,
status_id: int = 142
) -> bool:
"""Send lead to amoCRM"""
payload = {
"leads": [
{
"name": f"Лид от чатбота: {lead_name}",
"price": 0,
"pipeline_id": pipeline_id,
"status_id": status_id,
"custom_fields_values": [
{
"field_name": "Телефон",
"values": [{"value": lead_phone}]
} if lead_phone else None,
{
"field_name": "Email",
"values": [{"value": lead_email}]
} if lead_email else None,
{
"field_name": "Источник",
"values": [{"value": "ChatBot AI"}]
}
]
}
]
}
# Remove None values
payload["leads"][0]["custom_fields_values"] = [
f for f in payload["leads"][0]["custom_fields_values"] if f
]
return await self.send_webhook(webhook_url, payload)
async def send_to_bitrix24(
self,
webhook_url: str,
lead_name: str,
lead_phone: Optional[str],
lead_email: Optional[str]
) -> bool:
"""Send lead to Bitrix24"""
payload = {
"FIELDS": {
"TITLE": f"Лид от чатбота: {lead_name}",
"NAME": lead_name,
"PHONE": [{"PHONE": lead_phone}] if lead_phone else [],
"EMAIL": [{"EMAIL": lead_email}] if lead_email else [],
"SOURCE_ID": "CHATBOT",
"SOURCE_DESCRIPTION": "AI ChatBot"
}
}
return await self.send_webhook(webhook_url, payload)
# Global webhook service instance
webhook_service = WebhookService()