Spaces:
Paused
Paused
File size: 15,773 Bytes
042f4ed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Telegram webhook handler — runs inside the main backend (no separate gateway needed).
Receives Telegram messages, creates tasks, sends agent responses back.
Eliminates network calls between gateway and backend.
"""
import hashlib
import hmac as hmac_mod
import logging
import time
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from sqlalchemy import select, func
from sqlalchemy.exc import IntegrityError
from src.config import settings
from src.core.encryption import decrypt_value
from src.database import async_session
from src.models.channel import ChannelConnection, ChannelMessage, ChannelContactBlock
logger = logging.getLogger(__name__)
router = APIRouter(tags=["telegram-webhook"])
# In-memory rate limiter + dedup (same as gateway)
_rate_counters: dict[str, list[float]] = {}
_dedup_seen: dict[str, float] = {}
def _is_rate_limited(key: str, max_req: int = 10, window: int = 60) -> bool:
now = time.time()
hits = [t for t in _rate_counters.get(key, []) if t > now - window]
hits.append(now)
_rate_counters[key] = hits
return len(hits) > max_req
def _is_duplicate(conn_id: str, msg_id: str, ttl: int = 300) -> bool:
key = f"{conn_id}:{msg_id}"
now = time.time()
if key in _dedup_seen and now - _dedup_seen[key] < ttl:
return True
_dedup_seen[key] = now
# Cleanup
if len(_dedup_seen) > 10000:
_dedup_seen.clear()
return False
def _pseudonymize(user_id: str, conn_id: str) -> str:
key = f"{settings.gateway_service_key}:{conn_id}".encode()
return hmac_mod.new(key, user_id.encode(), hashlib.sha256).hexdigest()[:16]
def _verify_secret(conn_id: str, headers: dict) -> bool:
if not settings.gateway_service_key:
return True # no key configured
expected = hashlib.sha256(
f"{settings.gateway_service_key}:{conn_id}".encode()
).hexdigest()[:32]
actual = headers.get("x-telegram-bot-api-secret-token", "")
if not actual:
return False
return hmac_mod.compare_digest(actual, expected)
async def _telegram_api(token: str, method: str, payload: dict) -> dict | None:
"""Call Telegram Bot API using IP address directly (bypasses DNS resolution).
HF Spaces Docker containers cannot resolve external hostnames.
We hardcode Telegram's API server IP and use the Host header.
"""
import json as j
import asyncio as aio
import http.client
import ssl
# Telegram Bot API server IPs (api.telegram.org)
TELEGRAM_IPS = ["149.154.167.220", "149.154.167.198"]
data = j.dumps(payload).encode()
path = f"/bot{token}/{method}"
async def _do_request(ip: str) -> dict | None:
def _sync():
ctx = ssl.create_default_context()
# IMPORTANT: disable hostname check since we're connecting to IP
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection(ip, timeout=20, context=ctx)
conn.request("POST", path, body=data, headers={
"Content-Type": "application/json",
"Host": "api.telegram.org",
})
resp = conn.getresponse()
raw = resp.read()
conn.close()
return j.loads(raw)
return await aio.to_thread(_sync)
for ip in TELEGRAM_IPS:
try:
result = await _do_request(ip)
if result:
return result
except Exception as e:
logger.warning("Telegram API %s via %s failed: %s", method, ip, e)
continue
logger.error("All Telegram API IPs failed for %s", method)
return None
async def _send_telegram(token: str, chat_id: str, text: str) -> bool:
"""Send a message via Telegram Bot API."""
chunks = [text[i:i + 4000] for i in range(0, len(text), 4000)]
for chunk in chunks:
result = await _telegram_api(token, "sendMessage", {"chat_id": chat_id, "text": chunk, "parse_mode": "Markdown"})
if not result or not result.get("ok"):
# Retry without Markdown
result = await _telegram_api(token, "sendMessage", {"chat_id": chat_id, "text": chunk})
return True
async def _send_typing(token: str, chat_id: str):
await _telegram_api(token, "sendChatAction", {"chat_id": chat_id, "action": "typing"})
async def _get_first_skill_id(db, agent_id) -> str:
"""Get the first skill ID for an agent (fallback when channel has no specific skill)."""
from src.models.skill import AgentSkill
result = await db.execute(
select(AgentSkill.id).where(AgentSkill.agent_id == agent_id).limit(1)
)
skill = result.scalar_one_or_none()
return str(skill) if skill else ""
@router.post("/webhook/telegram/{connection_id}")
async def telegram_webhook(connection_id: str, request: Request):
"""Receive Telegram webhook — ack immediately, process in background."""
import json as json_mod
body_bytes = await request.body()
try:
body = json_mod.loads(body_bytes)
except Exception:
return JSONResponse(status_code=400, content={"detail": "Invalid JSON"})
# Verify webhook secret
headers = {k.lower(): v for k, v in request.headers.items()}
if not _verify_secret(connection_id, headers):
return JSONResponse(status_code=401, content={"detail": "Unauthorized", "debug": "secret_mismatch"})
# Parse message
message = body.get("message") or body.get("edited_message")
if not message or not message.get("text"):
return {"ok": True, "debug": "no_text_message", "keys": list(body.keys())}
platform_user_id = str(message["from"]["id"])
platform_msg_id = str(message["message_id"])
chat_id = str(message["chat"]["id"])
text = message["text"]
# Dedup
if _is_duplicate(connection_id, platform_msg_id):
return {"ok": True}
# Rate limit
if _is_rate_limited(f"{connection_id}:{platform_user_id}"):
return {"ok": True}
# Process synchronously for debugging
try:
result = await _process_telegram_message(
connection_id, platform_user_id, platform_msg_id, chat_id, text
)
return {"ok": True, "debug": result or "returned_none", "parsed": {"user": platform_user_id, "msg_id": platform_msg_id, "text": text[:50], "conn_id": connection_id}}
except Exception as e:
import traceback
tb = traceback.format_exc()
logger.exception("Webhook processing failed: %s", e)
return {"ok": True, "debug_error": f"{type(e).__name__}: {e}", "traceback": tb[-500:]}
async def _process_telegram_message(
connection_id: str, platform_user_id: str, platform_msg_id: str, chat_id: str, text: str
):
"""Process Telegram message: look up connection, charge credits, create task, send response."""
debug_info = {"stage": "start", "connection_id": connection_id, "text": text[:30]}
try:
debug_info["stage"] = "opening_db"
async with async_session() as db:
debug_info["stage"] = "db_connected"
# Get connection (cast string to UUID)
from uuid import UUID as _UUID
try:
conn_uuid = _UUID(connection_id)
except ValueError:
debug_info["stage"] = "invalid_uuid"
return debug_info
result = await db.execute(
select(ChannelConnection).where(ChannelConnection.id == conn_uuid)
)
conn = result.scalar_one_or_none()
if not conn or conn.status != "active":
debug_info["stage"] = "connection_not_found"
return debug_info
debug_info["stage"] = "connection_found"
debug_info["conn_status"] = conn.status
# Decrypt bot token
bot_token = decrypt_value(conn.bot_token) if conn.bot_token else ""
if not bot_token:
debug_info["stage"] = "no_bot_token"
return debug_info
debug_info["stage"] = "token_decrypted"
# Check if user is blocked
user_hash = _pseudonymize(platform_user_id, connection_id)
blocked = await db.execute(
select(ChannelContactBlock).where(
ChannelContactBlock.connection_id == conn.id,
ChannelContactBlock.platform_user_id_hash == user_hash,
)
)
if blocked.scalar_one_or_none():
debug_info["stage"] = "user_blocked"
return debug_info
# Send typing indicator
await _send_typing(bot_token, chat_id)
# Check daily credit limit
if conn.daily_credit_limit:
from datetime import datetime, timezone
today = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
usage_result = await db.execute(
select(func.coalesce(func.sum(ChannelMessage.credits_charged), 0))
.where(ChannelMessage.connection_id == conn.id)
.where(ChannelMessage.created_at >= today)
)
today_usage = float(usage_result.scalar_one())
if today_usage >= conn.daily_credit_limit:
await _send_telegram(bot_token, chat_id, "Daily message limit reached. Service will resume tomorrow.")
debug_info["stage"] = "daily_limit_hit"
return debug_info
# Check credit balance
from src.models.user import User
owner = await db.get(User, conn.owner_id)
if not owner or not owner.account:
debug_info["stage"] = "no_owner_or_account"
debug_info["owner_found"] = owner is not None
debug_info["has_account"] = bool(owner.account) if owner else False
await _send_telegram(bot_token, chat_id, "Service temporarily unavailable.")
return debug_info
balance = float(owner.account.balance)
debug_info["stage"] = "balance_checked"
debug_info["balance"] = balance
if balance < 1:
await _send_telegram(bot_token, chat_id, "Service temporarily unavailable.")
debug_info["stage"] = "insufficient_balance"
return debug_info
# Log inbound message (text = NULL for privacy)
inbound_msg = ChannelMessage(
connection_id=conn.id,
platform_user_id_hash=user_hash,
platform_message_id=platform_msg_id,
platform_chat_id=chat_id,
direction="inbound",
message_text=None, # GDPR: don't store inbound text
media_type="text",
)
db.add(inbound_msg)
try:
await db.flush()
except IntegrityError:
await db.rollback()
debug_info["stage"] = "duplicate_message"
return debug_info
# Create task for the agent
from src.services.task_broker import TaskBrokerService
from src.schemas.task import TaskCreate, TaskMessage, MessagePart
broker = TaskBrokerService(db)
try:
task_data = TaskCreate(
provider_agent_id=conn.agent_id,
skill_id=str(conn.skill_id) if conn.skill_id else await _get_first_skill_id(db, conn.agent_id),
messages=[TaskMessage(role="user", parts=[MessagePart(type="text", content=text)])],
confirmed=True,
)
task = await broker.create_task(data=task_data, user_id=conn.owner_id)
await db.flush()
logger.info("Task %s created for Telegram message on connection %s", task.id, connection_id)
except Exception as e:
logger.error("Task creation failed: %s", e)
await _send_telegram(bot_token, chat_id, "Sorry, I couldn't process your request. Please try again.")
debug_info["stage"] = "task_creation_failed"
debug_info["error"] = f"{type(e).__name__}: {e}"
return debug_info
# Wait for task completion (poll with timeout)
# The task broker dispatches to the agent asynchronously.
# We poll the task status for up to 120 seconds.
import asyncio as aio
from src.models.task import Task
task_id = task.id
response_text = None
start = time.time()
while time.time() - start < 120:
await aio.sleep(3)
async with async_session() as poll_db:
t = await poll_db.get(Task, task_id)
if not t:
break
status = t.status.value if hasattr(t.status, "value") else t.status
if status == "completed":
# Get response from artifacts
if t.artifacts:
for artifact in t.artifacts:
parts = artifact.get("parts", []) if isinstance(artifact, dict) else []
for part in parts:
if isinstance(part, dict) and part.get("type") == "text" and part.get("content"):
response_text = part["content"]
break
if response_text:
break
if not response_text:
response_text = "Task completed successfully."
break
elif status in ("failed", "canceled"):
response_text = "Sorry, I couldn't complete your request."
break
if not response_text:
response_text = "Request is taking longer than expected. Please try again."
# Send response to Telegram
success = await _send_telegram(bot_token, chat_id, response_text)
# Log outbound message (encrypted)
from src.core.message_crypto import encrypt_message
encrypted_text = None
if response_text:
try:
encrypted_text = encrypt_message(response_text[:2000])
except Exception:
encrypted_text = response_text[:2000]
outbound_msg = ChannelMessage(
connection_id=conn.id,
platform_user_id_hash="agent",
platform_message_id=f"reply-{platform_msg_id}",
platform_chat_id=chat_id,
direction="outbound",
message_text=encrypted_text,
task_id=task_id,
credits_charged=1, # 1 credit per message
)
db.add(outbound_msg)
# Deduct 1 credit from owner's balance
from decimal import Decimal
if owner.account:
owner.account.balance -= Decimal("1")
outbound_msg.credits_charged = 1
await db.commit()
logger.info("Telegram response sent for connection %s: %s", connection_id, "success" if success else "failed")
except Exception as e:
logger.exception("Error processing Telegram message for %s: %s", connection_id, e)
debug_info["error"] = f"{type(e).__name__}: {e}"
return debug_info
|