Spaces:
Running

microfunnel-api / backend /app /api /telegram_webhook.py
axeronis's picture
Fix: /start now sends welcome message (not ID) in tenant bot
4b3688e
Raw History Blame Contribute Delete
21.4 kB
"""
Telegram Webhook Handler.
Uses unified MessageProcessor for message handling.
"""
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from uuid import UUID
from datetime import datetime
import logging
import httpx
from app.core.database import get_async_session, async_session_maker
from app.models.tenant import Tenant
from app.services.message_processor import IncomingMessage, get_message_processor
from app.core.logging import get_logger
from app.core.config import settings
from app.core.limiter import limiter
logger = get_logger(__name__)
router = APIRouter(prefix="/webhook/telegram-notify", tags=["Telegram Notification Bot"])
@router.post("/global")
@limiter.limit("20/minute")
async def handle_global_telegram_webhook(
request: Request,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_async_session)
):
"""Handle incoming updates for the Global Notification Bot."""
try:
raw_body = await request.body()
import json
data = json.loads(raw_body)
except Exception:
return {"status": "ignored"}
logger.info(f"🚨 GLOBAL BOT WEBHOOK: body_preview={raw_body[:200]}")
# 1. Handle Group Addition
if "my_chat_member" in data:
my_chat_member = data["my_chat_member"]
chat = my_chat_member.get("chat", {})
new_status = my_chat_member.get("new_chat_member", {}).get("status")
chat_id = str(chat.get("id"))
if new_status in ["member", "administrator"]:
token = settings.TELEGRAM_NOTIFICATION_TOKEN
if token:
from app.services.telegram_service import telegram_service
msg = f"✅ <b>Бота добавили в группу!</b>\n\n🆔 Group ID: <code>{chat_id}</code>\n\nВставьте этот ID в поле 'Групповой чат' в настройках уведомлений."
background_tasks.add_task(telegram_service.send_message, token=token, chat_id=chat_id, text=msg)
return {"status": "ok"}
# 2. Handle /start for Personal ID
if "message" in data:
msg_data = data["message"]
text = msg_data.get("text", "")
chat_id = str(msg_data.get("chat", {}).get("id"))
if text and text.strip().lower().startswith("/start"):
token = settings.TELEGRAM_NOTIFICATION_TOKEN
if token:
from app.services.telegram_service import telegram_service
reply = f"✅ <b>Бот готов к работе!</b>\n\n🆔 Ваш Personal ID: <code>{chat_id}</code>\n\nВставьте этот ID в поле 'Личный чат' в настройках уведомлений."
background_tasks.add_task(telegram_service.send_message, token=token, chat_id=chat_id, text=reply)
return {"status": "ok"}
@router.post("/{tenant_id}")
@limiter.limit("5/minute")
async def handle_telegram_webhook(
tenant_id: UUID,
request: Request,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_async_session)
):
"""Handle incoming Telegram updates."""
# ABSOLUTE FIRST LOG - Before anything else
raw_body = await request.body()
logger.info(f"🚨 RAW TELEGRAM REQUEST: tenant={tenant_id}, bytes={len(raw_body)}, body_preview={raw_body[:200]}")
try:
import json
data = json.loads(raw_body)
except Exception as e:
logger.error(f"❌ JSON parse failed: {e}")
raise HTTPException(status_code=400, detail="Invalid JSON")
# Check for My Chat Member (Bot added/removed from group)
if "my_chat_member" in data:
my_chat_member = data["my_chat_member"]
chat = my_chat_member.get("chat", {})
new_status = my_chat_member.get("new_chat_member", {}).get("status")
chat_id = str(chat.get("id"))
chat_title = chat.get("title", "Group")
logger.info(f"📢 Bot status changed in chat {chat_id} ({chat_title}): {new_status}")
if new_status in ["member", "administrator"]:
try:
# Send Welcome & ID so user can copy it
tenant = await session.get(Tenant, tenant_id)
if tenant:
token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
if token:
from app.services.telegram_service import telegram_service
msg = f"✅ <b>Бот подключен к группе!</b>\n\n🆔 ID группы: <code>{chat_id}</code>\n\nСкопируйте этот ID в настройки уведомлений MicroFunnel."
background_tasks.add_task(
telegram_service.send_message,
token=token,
chat_id=chat_id,
text=msg
)
logger.info(f"✅ Sent Group ID {chat_id} to chat")
except Exception as e:
logger.error(f"Failed to handle group add: {e}")
return {"status": "processed_group_update"}
# Check if it's a message
if "message" not in data:
# Debug log for ignored updates
logger.info(f"📩 Telegram Update (Ignored): {list(data.keys())}")
return {"status": "ignored"}
message_data = data["message"]
logger.info(f"📩 Telegram Webhook: {list(data.keys())} | Msg Keys: {list(message_data.keys())}")
chat_id = str(message_data.get("chat", {}).get("id"))
text = message_data.get("text", "") or message_data.get("caption", "")
# Check for Voice OR Audio
voice = message_data.get("voice") or message_data.get("audio") or {}
voice_file_id = voice.get("file_id")
# Check for Photo (array)
photo_list = message_data.get("photo", [])
photo_file_id = photo_list[-1]["file_id"] if photo_list else None
# Check for Document
doc = message_data.get("document", {})
doc_file_id = doc.get("file_id")
user_data = message_data.get("from", {})
username = user_data.get("username", "")
first_name = user_data.get("first_name", "")
if not text and not voice_file_id and not photo_file_id and not doc_file_id:
logger.warning(f"⚠️ Ignored message with no content. Keys: {list(message_data.keys())}")
return {"status": "ignored_no_content"}
# Process in background
background_tasks.add_task(
process_telegram_message,
tenant_id=tenant_id,
chat_id=chat_id,
text=text,
voice_file_id=voice_file_id,
photo_file_id=photo_file_id,
doc_file_id=doc_file_id,
username=username,
first_name=first_name
)
return {"status": "ok"}
@router.get("/{tenant_id}")
async def verify_webhook_status(tenant_id: UUID):
"""
Simple GET endpoint to verify that the webhook URL is reachable.
Useful for debugging "no logs" issues.
"""
logger.info(f"✅ Webhook endpoint reachable for Tenant {tenant_id}")
return {
"status": "active",
"message": "Telegram Webhook Endpoint is online.",
"tenant_id": str(tenant_id)
}
@router.post("/{tenant_id}/register")
async def register_telegram_webhook(
tenant_id: UUID,
session: AsyncSession = Depends(get_async_session)
):
"""
Re-register Telegram webhook with correct allowed_updates.
This MUST be called after initial setup to enable voice/photo/document messages!
"""
tenant = await session.get(Tenant, tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
bot_token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
if not bot_token:
raise HTTPException(status_code=400, detail="No Telegram bot token configured")
# Construct webhook URL from settings
webhook_base = (settings.TELEGRAM_WEBHOOK_URL or "https://axeronis-microfunnel-api.hf.space").rstrip("/")
webhook_url = f"{webhook_base}/api/v1/webhook/telegram-notify/{tenant_id}"
# Register webhook with ALL message types
async with httpx.AsyncClient() as client:
# First, delete existing webhook
await client.get(f"https://api.telegram.org/bot{bot_token}/deleteWebhook")
# Then set new webhook with allowed_updates
response = await client.post(
f"https://api.telegram.org/bot{bot_token}/setWebhook",
json={
"url": webhook_url,
"allowed_updates": ["message", "edited_message", "channel_post"]
}
)
result = response.json()
# Also get current webhook info
info_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getWebhookInfo")
info = info_res.json()
logger.info(f"📡 Webhook registered: {result}")
return {
"status": "registered",
"webhook_url": webhook_url,
"telegram_response": result,
"webhook_info": info.get("result", {})
}
async def process_telegram_message(
tenant_id: UUID,
chat_id: str,
text: str,
voice_file_id: str | None,
photo_file_id: str | None,
doc_file_id: str | None,
username: str,
first_name: str
):
"""Background task: Process Telegram message using unified MessageProcessor."""
from app.services.telegram_service import telegram_service
from app.core.supabase import supabase_client
import time
import re
logger.info(f"🔧 Processing TG message: text={text[:30] if text else 'N/A'}..., voice={voice_file_id}, photo={photo_file_id}, doc={doc_file_id}")
async with async_session_maker() as session:
try:
# 1. Get Tenant & Bot Token
tenant = await session.get(Tenant, tenant_id)
if not tenant:
logger.error(f"Tenant {tenant_id} not found")
return
bot_token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
if not bot_token:
logger.error(f"No Telegram token for tenant {tenant_id}")
return
logger.info(f"✅ Tenant found, bot_token={'present' if bot_token else 'MISSING'}")
# NOTE: /start is handled in the AI processing flow (webhook.py)
# which sends the welcome message. We don't intercept it here.
# The ID message is only sent by the global notification bot (/tg-global).
# 2. Process Media (Voice, Photo, Doc)
is_voice = False
media_url = None
media_type = None
# Helper to download file
async def download_file(file_id: str) -> tuple[bytes, str, str]:
async with httpx.AsyncClient() as client:
file_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}")
if not file_res.json().get("ok"): return None, None, None
path = file_res.json()["result"]["file_path"]
url = f"https://api.telegram.org/file/bot{bot_token}/{path}"
data_res = await client.get(url)
data_res.raise_for_status()
# Guess MIME/Name
ext = path.split('.')[-1].lower() if '.' in path else "bin"
mime_map = {
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"webp": "image/webp",
"oga": "audio/ogg",
"ogg": "audio/ogg",
"mp3": "audio/mpeg",
"pdf": "application/pdf",
"txt": "text/plain"
}
mime = mime_map.get(ext, "application/octet-stream")
return data_res.content, path.split('/')[-1], mime
# Handle Voice
if voice_file_id:
logger.info(f"🎤 Voice file detected: {voice_file_id}")
try:
text = await transcribe_telegram_voice(bot_token, voice_file_id)
is_voice = True
logger.info(f"✅ Voice transcribed: {text[:50]}...")
except Exception as e:
logger.error(f"❌ Voice processing failed: {e}", exc_info=True)
# Handle Photo / Document
target_file_id = photo_file_id or doc_file_id
if target_file_id:
logger.info(f"📎 Media file detected: {target_file_id}")
try:
content, name, mime = await download_file(target_file_id)
if content and supabase_client:
bucket = "chat-attachments"
ts = int(time.time())
safe_name = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', name)
# Store in incoming path
path = f"{tenant.id}/incoming/{ts}_{safe_name}"
supabase_client.storage.from_(bucket).upload(
path=path, file=content, file_options={"content-type": mime}
)
media_url = supabase_client.storage.from_(bucket).get_public_url(path)
media_type = mime
logger.info(f"📎 Media uploaded: {media_url}")
except Exception as e:
logger.error(f"Media upload failed: {e}")
# 3. Build incoming message
sender_name = f"{first_name} {username}".strip() or f"TG User {chat_id}"
incoming = IncomingMessage(
channel="telegram",
sender_id=chat_id,
sender_name=sender_name,
text=text,
is_voice=is_voice,
media_url=media_url,
media_type=media_type
)
# 4. Process with unified MessageProcessor
processor = get_message_processor()
result = await processor.process(session, tenant, incoming)
# 5. Send response via Telegram
await telegram_service.send_message(
token=bot_token,
chat_id=chat_id,
text=result["response_text"]
)
logger.info(f"✅ Telegram reply sent to {chat_id}")
except Exception as e:
logger.error(f"Error processing Telegram message: {e}", exc_info=True)
async def transcribe_telegram_voice(bot_token: str, file_id: str) -> str:
"""Download and transcribe Telegram voice message."""
try:
logger.info("🎤 Processing Telegram voice message...")
async with httpx.AsyncClient() as client:
# Get file path
file_res = await client.get(
f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
)
file_data = file_res.json()
if not file_data.get("ok"):
logger.error(f"Failed to get file path: {file_data}")
return "[Voice Message] (Ошибка загрузки)"
file_path = file_data["result"]["file_path"]
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
# Download file
audio_res = await client.get(download_url)
audio_res.raise_for_status()
audio_bytes = audio_res.content
# Transcribe with Gemini
from app.services.llm_client import get_llm_client
llm = get_llm_client()
transcription = await llm.transcribe_audio(audio_bytes, mime_type="audio/ogg")
logger.info(f"✅ Transcription: {transcription[:50]}...")
return f"[Voice] {transcription}"
except Exception as e:
logger.error(f"❌ Voice transcription failed: {e}")
return "[Voice Message] (Не удалось распознать)"
async def analyze_telegram_image(bot_token: str, file_id: str) -> str:
"""Download and analyze Telegram image using Gemini Vision."""
try:
logger.info("📷 Processing Telegram image...")
async with httpx.AsyncClient() as client:
# Get file path
file_res = await client.get(
f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
)
file_data = file_res.json()
if not file_data.get("ok"):
logger.error(f"Failed to get file path: {file_data}")
return "[Фото] (Ошибка загрузки)"
file_path = file_data["result"]["file_path"]
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
# Download file
img_res = await client.get(download_url)
img_res.raise_for_status()
img_bytes = img_res.content
# Determine mime type from file extension
ext = file_path.split(".")[-1].lower()
mime_map = {"jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png", "webp": "image/webp", "gif": "image/gif"}
mime_type = mime_map.get(ext, "image/jpeg")
# Analyze with Gemini Vision
from app.services.llm_client import get_llm_client
llm = get_llm_client()
analysis = await llm.analyze_image(img_bytes, mime_type=mime_type)
logger.info(f"✅ Image analysis: {analysis[:50]}...")
return f"[Фото: {analysis}]"
except Exception as e:
logger.error(f"❌ Image analysis failed: {e}")
return "[Фото] (Не удалось проанализировать)"
async def analyze_telegram_document(bot_token: str, file_id: str, mime_type: str, file_name: str) -> str:
"""Download and analyze Telegram document."""
try:
logger.info(f"📄 Processing Telegram document: {file_name} ({mime_type})")
async with httpx.AsyncClient() as client:
# Get file path
file_res = await client.get(
f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
)
file_data = file_res.json()
if not file_data.get("ok"):
logger.error(f"Failed to get file path: {file_data}")
return f"[Документ: {file_name}] (Ошибка загрузки)"
file_path = file_data["result"]["file_path"]
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
# Download file
doc_res = await client.get(download_url)
doc_res.raise_for_status()
doc_bytes = doc_res.content
# Handle based on file type
if mime_type and mime_type.startswith("image/"):
# It's an image sent as document
from app.services.llm_client import get_llm_client
llm = get_llm_client()
analysis = await llm.analyze_image(doc_bytes, mime_type=mime_type)
logger.info(f"✅ Document (image) analysis: {analysis[:50]}...")
return f"[Документ-изображение: {analysis}]"
elif mime_type == "application/pdf":
# PDF - try to extract text or analyze as image
from app.services.llm_client import get_llm_client
llm = get_llm_client()
# Gemini can analyze PDFs directly
analysis = await llm.analyze_document(doc_bytes, mime_type="application/pdf", file_name=file_name)
logger.info(f"✅ PDF analysis: {analysis[:50]}...")
return f"[PDF-документ '{file_name}': {analysis}]"
elif mime_type and mime_type.startswith("text/"):
# Text file - read directly
try:
text_content = doc_bytes.decode("utf-8")[:2000] # Limit to 2000 chars
logger.info(f"✅ Text file read: {len(text_content)} chars")
return f"[Текстовый файл '{file_name}':\n{text_content}]"
except:
return f"[Документ: {file_name}] (Не удалось прочитать текст)"
else:
# Unknown format
return f"[Документ: {file_name}] (Формат {mime_type or 'неизвестен'} не поддерживается для анализа)"
except Exception as e:
logger.error(f"❌ Document analysis failed: {e}")
return f"[Документ: {file_name}] (Ошибка анализа)"