cotienbot / src /webhook.py
Anothervin1's picture
Create webhook.py
6126421 verified
from pydantic import BaseModel
from typing import Dict, Optional, Any
from fastapi import APIRouter
from src.logger import logger
router = APIRouter()
class WebhookUpdate(BaseModel):
update_id: int
message: Optional[Dict[str, Any]] = None
callback_query: Optional[Dict[str, Any]] = None
inline_query: Optional[Dict[str, Any]] = None
@router.post("/v1/webhook")
async def webhook(update: WebhookUpdate):
try:
logger.info(f"[Webhook] Received update_id={update['update_id']}")
if update.callback_query or update.inline_query:
logger.debug(f"[Webhook] Ignoring callback_query or inline_query")
return {"status": "ok"}
if not update.message:
logger.error(f"[Webhook] No message in update")
return {"status": "error"}
chat_id = update.message.get("chat", {}).get("id")
user_id = update.message.get("from", {}).get("id")
text = update.message.get("text", "").strip()
if not all([chat_id, user_id, text]):
logger.error(f"[Webhook] Invalid payload: {str(update.message)}")
return {"status": "error"}
from src.api import app
logger.debug(f"[Webhook] Processing: chat_id={chat_id}, user_id={user_id}, text={text[:50]}...")
app.state.bot_message = update
await app.state.bot.handle_message(chat_id, user_id, text)
return {"status": "ok"}
except Exception as e:
logger.error(f"[Webhook] Error: {str(e)}", exc_info=True)
return {"status": "error", "error": str(e)}