import logging from typing import List, Optional from app.services.telegram_service import send_message as tg_send logger = logging.getLogger(__name__) async def send_handoff_alert( chatbot_id: str, chatbot_name: str, conversation_history: List[dict], trigger_message: str, conversation_id: str, low_confidence: bool, supabase, ) -> bool: """ Notify the chatbot owner via their connected Telegram bot. Owner must have sent /owner to their bot to register their chat_id. Returns True if notification was sent. """ try: conn = ( supabase.table("channel_connections") .select("bot_token, owner_chat_id") .eq("chatbot_id", chatbot_id) .eq("channel", "telegram") .eq("is_active", True) .execute() ) if not conn.data: logger.info(f"No Telegram connection for chatbot {chatbot_id}") return False bot_token: Optional[str] = conn.data[0].get("bot_token") owner_chat_id = conn.data[0].get("owner_chat_id") if not bot_token or not owner_chat_id: logger.info( f"Owner has not registered for notifications on chatbot {chatbot_id}. " "They should send /owner to their Telegram bot." ) return False from app.config import settings recent = conversation_history[-4:] history_lines = "\n".join( f"{'👤' if m['role'] == 'user' else '🤖'} {m['content'][:120]}" for m in recent ) reason = "❓ Bot couldn't answer confidently" if low_confidence else "🙋 User requested a human" inbox_url = f"{settings.app_url}/inbox" text = ( f"🔔 *Handoff — {chatbot_name}*\n" f"Reason: {reason}\n\n" f"Last messages:\n{history_lines}\n\n" f"▶ [Open in inbox]({inbox_url})" ) sent = await tg_send(bot_token, owner_chat_id, text) if sent: logger.info(f"Handoff alert sent to owner for chatbot {chatbot_id}") return sent except Exception as e: logger.error(f"Failed to send handoff alert for chatbot {chatbot_id}: {e}") return False