mirror of
http://88.130.71.182:3000/BlitTech/contexta_be.git
synced 2026-06-12 23:23:21 +00:00
updates Mar6
This commit is contained in:
62
app/services/n8n_service.py
Normal file
62
app/services/n8n_service.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import httpx
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def send_notification(
|
||||
event_type: str,
|
||||
data: Dict[str, Any],
|
||||
webhook_url: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Generic n8n notification sender.
|
||||
Returns True if sent, False if not configured or failed.
|
||||
"""
|
||||
if not webhook_url:
|
||||
return False
|
||||
|
||||
payload = {
|
||||
"event": event_type,
|
||||
"timestamp": datetime.utcnow().isoformat(),
|
||||
**data,
|
||||
}
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
response = await client.post(webhook_url, json=payload)
|
||||
response.raise_for_status()
|
||||
logger.info(f"n8n notification sent: {event_type}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send n8n notification ({event_type}): {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def send_handoff_notification(
|
||||
chatbot_name: str,
|
||||
owner_email: str,
|
||||
conversation_history: List[dict],
|
||||
trigger_message: str,
|
||||
chatbot_id: str,
|
||||
conversation_id: str,
|
||||
webhook_url: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
Send a human handoff notification to the configured n8n webhook.
|
||||
Returns True if sent, False if not configured or failed.
|
||||
"""
|
||||
return await send_notification(
|
||||
event_type="handoff",
|
||||
data={
|
||||
"chatbot_name": chatbot_name,
|
||||
"owner_email": owner_email,
|
||||
"trigger_message": trigger_message,
|
||||
"conversation_history": conversation_history[-10:],
|
||||
"chatbot_id": chatbot_id,
|
||||
"conversation_id": conversation_id,
|
||||
},
|
||||
webhook_url=webhook_url,
|
||||
)
|
||||
57
app/services/telegram_service.py
Normal file
57
app/services/telegram_service.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import httpx
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_BASE = "https://api.telegram.org/bot{token}"
|
||||
|
||||
|
||||
async def get_bot_info(bot_token: str) -> Optional[dict]:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.get(f"https://api.telegram.org/bot{bot_token}/getMe")
|
||||
data = r.json()
|
||||
if data.get("ok"):
|
||||
return data["result"]
|
||||
except Exception as e:
|
||||
logger.error(f"Telegram getMe error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
async def set_webhook(bot_token: str, webhook_url: str) -> bool:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(
|
||||
f"https://api.telegram.org/bot{bot_token}/setWebhook",
|
||||
json={"url": webhook_url, "allowed_updates": ["message"]},
|
||||
)
|
||||
return r.json().get("ok", False)
|
||||
except Exception as e:
|
||||
logger.error(f"Telegram setWebhook error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def delete_webhook(bot_token: str) -> bool:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(
|
||||
f"https://api.telegram.org/bot{bot_token}/deleteWebhook"
|
||||
)
|
||||
return r.json().get("ok", False)
|
||||
except Exception as e:
|
||||
logger.error(f"Telegram deleteWebhook error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def send_message(bot_token: str, chat_id, text: str) -> bool:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(
|
||||
f"https://api.telegram.org/bot{bot_token}/sendMessage",
|
||||
json={"chat_id": chat_id, "text": text},
|
||||
)
|
||||
return r.json().get("ok", False)
|
||||
except Exception as e:
|
||||
logger.error(f"Telegram sendMessage error: {e}")
|
||||
return False
|
||||
65
app/services/web_scraper.py
Normal file
65
app/services/web_scraper.py
Normal file
@@ -0,0 +1,65 @@
|
||||
import httpx
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_TEXT_BYTES = 100 * 1024 # 100KB
|
||||
|
||||
|
||||
async def scrape_url(url: str) -> dict:
|
||||
"""
|
||||
Fetch a URL and extract clean text content.
|
||||
Returns: {title, text, url} or {error, url}
|
||||
"""
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (compatible; ContextaBot/1.0; +https://contexta.ai)",
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
|
||||
response = await client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
|
||||
content_type = response.headers.get("content-type", "")
|
||||
if "text/html" not in content_type and "text/plain" not in content_type:
|
||||
return {"error": f"Unsupported content type: {content_type}", "url": url}
|
||||
|
||||
html = response.text
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
# Extract title
|
||||
title_tag = soup.find("title")
|
||||
title = title_tag.get_text(strip=True) if title_tag else ""
|
||||
|
||||
# Remove unwanted tags
|
||||
for tag in soup.find_all(["nav", "header", "footer", "script", "style", "noscript", "aside", "advertisement"]):
|
||||
tag.decompose()
|
||||
|
||||
# Extract main content (prefer article/main/body)
|
||||
main = soup.find("main") or soup.find("article") or soup.find("body") or soup
|
||||
text = main.get_text(separator="\n", strip=True)
|
||||
|
||||
# Clean up whitespace
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
text = "\n".join(lines)
|
||||
|
||||
# Limit size
|
||||
if len(text.encode("utf-8")) > MAX_TEXT_BYTES:
|
||||
text = text[:MAX_TEXT_BYTES].rsplit("\n", 1)[0]
|
||||
|
||||
if not text:
|
||||
return {"error": "No text content found on page", "url": url}
|
||||
|
||||
logger.info(f"Scraped {url}: {len(text)} chars, title='{title}'")
|
||||
return {"title": title, "text": text, "url": url}
|
||||
|
||||
except httpx.TimeoutException:
|
||||
return {"error": "Request timed out", "url": url}
|
||||
except httpx.HTTPStatusError as e:
|
||||
return {"error": f"HTTP {e.response.status_code}", "url": url}
|
||||
except Exception as e:
|
||||
logger.error(f"Scrape error for {url}: {e}")
|
||||
return {"error": str(e)[:200], "url": url}
|
||||
36
app/services/whatsapp_service.py
Normal file
36
app/services/whatsapp_service.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import httpx
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_META_API = "https://graph.facebook.com/v19.0"
|
||||
|
||||
|
||||
async def send_message(phone_number_id: str, to: str, text: str, access_token: str) -> bool:
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(
|
||||
f"{_META_API}/{phone_number_id}/messages",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
json={
|
||||
"messaging_product": "whatsapp",
|
||||
"to": to,
|
||||
"type": "text",
|
||||
"text": {"body": text},
|
||||
},
|
||||
)
|
||||
return r.status_code == 200
|
||||
except Exception as e:
|
||||
logger.error(f"WhatsApp send error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def verify_signature(payload: bytes, signature: str, app_secret: str) -> bool:
|
||||
expected = "sha256=" + hmac.new(
|
||||
app_secret.encode("utf-8"),
|
||||
payload,
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
return hmac.compare_digest(expected, signature)
|
||||
140
app/services/widget.py
Normal file
140
app/services/widget.py
Normal file
@@ -0,0 +1,140 @@
|
||||
def generate_widget_js(app_url: str) -> str:
|
||||
"""Generate the embeddable widget JavaScript with app_url baked in."""
|
||||
return f"""
|
||||
(function() {{
|
||||
var APP_URL = "{app_url}";
|
||||
|
||||
// Find script tag to get chatbot ID
|
||||
var scripts = document.querySelectorAll('script[data-chatbot]');
|
||||
var chatbotId = null;
|
||||
if (scripts.length > 0) {{
|
||||
chatbotId = scripts[scripts.length - 1].getAttribute('data-chatbot');
|
||||
}}
|
||||
if (!chatbotId) {{
|
||||
console.warn('[Contexta] No data-chatbot attribute found on script tag');
|
||||
return;
|
||||
}}
|
||||
|
||||
// Styles
|
||||
var style = document.createElement('style');
|
||||
style.textContent = `
|
||||
.contexta-btn {{
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 50%;
|
||||
background: #6366f1;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 999998;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
}}
|
||||
.contexta-btn:hover {{
|
||||
transform: scale(1.08);
|
||||
box-shadow: 0 6px 20px rgba(0,0,0,0.25);
|
||||
}}
|
||||
.contexta-btn svg {{
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
fill: white;
|
||||
}}
|
||||
.contexta-container {{
|
||||
position: fixed;
|
||||
bottom: 92px;
|
||||
right: 24px;
|
||||
width: 380px;
|
||||
height: 580px;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.15);
|
||||
z-index: 999999;
|
||||
overflow: hidden;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
border: 1px solid #e5e7eb;
|
||||
}}
|
||||
.contexta-container.open {{
|
||||
display: flex;
|
||||
}}
|
||||
.contexta-iframe {{
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
flex: 1;
|
||||
}}
|
||||
.contexta-close {{
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
background: rgba(0,0,0,0.3);
|
||||
border: none;
|
||||
color: white;
|
||||
border-radius: 50%;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1;
|
||||
}}
|
||||
@media (max-width: 480px) {{
|
||||
.contexta-container {{
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
border-radius: 0;
|
||||
}}
|
||||
}}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
// Button
|
||||
var btn = document.createElement('button');
|
||||
btn.className = 'contexta-btn';
|
||||
btn.setAttribute('aria-label', 'Open chat');
|
||||
btn.innerHTML = '<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>';
|
||||
document.body.appendChild(btn);
|
||||
|
||||
// Container with iframe
|
||||
var container = document.createElement('div');
|
||||
container.className = 'contexta-container';
|
||||
|
||||
var closeBtn = document.createElement('button');
|
||||
closeBtn.className = 'contexta-close';
|
||||
closeBtn.innerHTML = '×';
|
||||
closeBtn.setAttribute('aria-label', 'Close chat');
|
||||
container.appendChild(closeBtn);
|
||||
|
||||
var iframe = document.createElement('iframe');
|
||||
iframe.className = 'contexta-iframe';
|
||||
iframe.src = APP_URL + '/chat/' + chatbotId;
|
||||
iframe.setAttribute('allow', 'microphone');
|
||||
container.appendChild(iframe);
|
||||
|
||||
document.body.appendChild(container);
|
||||
|
||||
// Toggle logic
|
||||
var isOpen = false;
|
||||
function toggle() {{
|
||||
isOpen = !isOpen;
|
||||
if (isOpen) {{
|
||||
container.classList.add('open');
|
||||
btn.innerHTML = '<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>';
|
||||
}} else {{
|
||||
container.classList.remove('open');
|
||||
btn.innerHTML = '<svg viewBox="0 0 24 24"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/></svg>';
|
||||
}}
|
||||
}}
|
||||
|
||||
btn.addEventListener('click', toggle);
|
||||
closeBtn.addEventListener('click', toggle);
|
||||
}})();
|
||||
"""
|
||||
Reference in New Issue
Block a user