CoolFace
Apppublic

codeBOKER/customer_service

sourceHugging Faceupdated 3mo agoView on Hugging Face
1likes
telegram_handlers.py95 linesDownload Raw Back to root
1import httpx2import json3import html4import re5import asyncio6from config import TELEGRAM_URL, TELEGRAM_TOKEN7from ai_service import get_ai_response8from database import db_manager9from schemas import WebhookData10 11TELEGRAM_IP = "149.154.167.220"12MAX_TELEGRAM_MESSAGE_LENGTH = 409613 14def _sanitize_telegram_text(text: str) -> str:15    if text is None:16        return ""17    normalized = str(text).replace("\r\n", "\n").replace("\r", "\n")18    cleaned = "".join(19        ch20        for ch in normalized21        if (ch in ("\n", "\t") or ord(ch) >= 32) and not (0xD800 <= ord(ch) <= 0xDFFF)22    )23    return cleaned.strip()24 25def _format_telegram_message(text: str) -> str:26    if not text:27        return text28    escaped = html.escape(text, quote=False)29    formatted = re.sub(r'\*\*(.*?)\*\*', r'<b>\1</b>', escaped)30    return formatted31 32async def telegram_webhook(data: WebhookData):33    try:34        if not data.message or not data.message.text:35            return {"status": "ok"}36 37        telegram_id = data.message.chat.id38        user_text = data.message.text39        username = data.message.chat.username40        first_name = data.message.chat.first_name41 42        if db_manager:43            await db_manager.create_or_update_user(telegram_id, username, first_name, data.message.chat.last_name)44 45        if TELEGRAM_TOKEN:46            async with httpx.AsyncClient(timeout=40.0, verify=False) as client:47                action_payload = {48                    "chat_id": telegram_id,49                    "action": "typing",50                }51                action_url = f"https://{TELEGRAM_IP}/bot{TELEGRAM_TOKEN}/sendChatAction"52                headers = {53                    "Host": "api.telegram.org",54                    "Content-Type": "application/json; charset=utf-8",55                }56                try:57                    await client.post(action_url, json=action_payload, headers=headers)58                except Exception:59                    pass60 61                ai_answer = await get_ai_response(user_text, telegram_id)62                final_response = ai_answer or "Sorry, I couldn't generate a response."63 64                prepared_text = _sanitize_telegram_text(final_response)65                formatted_text = _format_telegram_message(prepared_text)66                final_text = formatted_text[:MAX_TELEGRAM_MESSAGE_LENGTH]67                68                payload = {69                    "chat_id": telegram_id,70                    "text": final_text if final_text.strip() else ".",71                    "parse_mode": "HTML",72                }73 74                forced_ip_url = f"https://{TELEGRAM_IP}/bot{TELEGRAM_TOKEN}/sendMessage"75                headers = {76                    "Host": "api.telegram.org",77                    "Content-Type": "application/json; charset=utf-8",78                }79 80                response = await client.post(forced_ip_url, json=payload, headers=headers)81 82                if response.status_code == 200:83                    print("--- Success: Telegram message delivered ---")84                    if db_manager:85                        await asyncio.gather(86                            db_manager.save_message(telegram_id, user_text, "user"),87                            db_manager.save_message(telegram_id, final_response, "assistant")88                        )89                else:90                    print(f"--- Telegram Rejected: {response.status_code} - {response.text} ---")91        92        return {"status": "ok"}93    except Exception as e:94        print(f"Error in webhook: {str(e)}")95        return {"status": "error", "message": str(e)}