File size: 1,497 Bytes
3a006a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Telegram Webhook API — Executive Command Gateway."""

from fastapi import APIRouter, Depends, Request, Header, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.services.telegram_ceo_service import TelegramCEOService
from app.config.settings import settings
from typing import Optional
import httpx
from loguru import logger

router = APIRouter(tags=["Executive Control"])

@router.post("/webhook/telegram")
@router.post("/v1/webhook/telegram")
async def telegram_webhook(

    request: Request, 

    db: AsyncSession = Depends(get_db),

    x_webhook_token: Optional[str] = Header(None)

):
    """Receives commands/updates directly from Telegram or API clients."""
    data = await request.json()
    
    # Check if this is a standard Telegram payload
    is_telegram_payload = ("message" in data or "callback_query" in data or "edited_message" in data)
    
    # Security Check: Only enforce for non-Telegram clients
    if not is_telegram_payload:
        expected_secret = settings.webhook_secret or settings.security_webhook_token
        if expected_secret and x_webhook_token != expected_secret:
            logger.warning("[Telegram Webhook] Unauthorized access attempt.")
            return {"status": "unauthorized"}

    ceo_service = TelegramCEOService(db)
    
    # Process webhook natively via the service
    result = await ceo_service.handle_webhook(data)
    return result