File size: 5,519 Bytes
4519f1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import os
import logging
import asyncio
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

# ============================================
# CẤU HÌNH
# ============================================
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("telegram-bot")

# Đặt biến này trong HF Space Settings -> Repository secrets
# Tên secret: TELEGRAM_BOT_TOKEN
TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
TELEGRAM_API = f"https://api.telegram.org/bot{TOKEN}"

app = FastAPI()

# Dùng để chống xử lý trùng update_id (dedup) khi Telegram gửi lại do timeout
_last_update_id = None


# ============================================
# HÀM GỬI TIN NHẮN (bất đồng bộ, KHÔNG block)
# ============================================
async def send_message(chat_id: int, text: str):
    async with httpx.AsyncClient(timeout=10.0) as client:
        try:
            resp = await client.post(
                f"{TELEGRAM_API}/sendMessage",
                json={"chat_id": chat_id, "text": text}
            )
            logger.info(f"Đã gửi tin nhắn tới {chat_id}: status={resp.status_code}")
            return resp.json()
        except Exception as e:
            logger.error(f"Lỗi khi gửi tin nhắn: {e}")
            return None


# ============================================
# XỬ LÝ LOGIC TIN NHẮN (chạy nền, không chặn response)
# ============================================
async def process_message_background(update: dict):
    """
    Hàm này chạy NỀN sau khi đã trả 200 cho Telegram.
    Đây là nơi bạn xử lý logic thật: lưu SQLite, gọi Gemini, ChromaDB...
    QUAN TRỌNG: mọi call ở đây phải là async hoặc chạy trong executor,
    KHÔNG được gọi hàm sync blocking trực tiếp (đây là bug bạn từng gặp trước đó).
    """
    try:
        message = update.get("message")
        if not message:
            logger.info("Update không chứa 'message' (edited_message, callback_query...), bỏ qua.")
            return

        text = message.get("text", "")
        chat_id = message["chat"]["id"]
        from_user = message.get("from", {})

        logger.info(f"Xử lý tin nhắn: '{text}' từ chat_id={chat_id}, user={from_user.get('first_name')}")

        # ---------------------------------------------
        # TODO: Thay đoạn dưới đây bằng logic thật của bạn
        # Ví dụ: lưu vào SQLite, tìm kiếm ChromaDB, gọi Gemini API...
        # ---------------------------------------------
        reply_text = f"Đã nhận: {text}"

        await send_message(chat_id, reply_text)

    except Exception as e:
        logger.error(f"Lỗi khi xử lý message nền: {e}")


# ============================================
# ENDPOINT WEBHOOK - TELEGRAM GỌI VÀO ĐÂY
# ============================================
@app.post("/webhook")
async def telegram_webhook(request: Request):
    global _last_update_id

    try:
        update = await request.json()
    except Exception as e:
        logger.error(f"Lỗi parse JSON: {e}")
        # Vẫn trả 200 để Telegram không retry
        return JSONResponse(content={"ok": True}, status_code=200)

    update_id = update.get("update_id")
    logger.info(f"Nhận update_id={update_id}: {update}")

    # Dedup đơn giản - chống xử lý trùng nếu Telegram gửi lại
    if update_id is not None and update_id == _last_update_id:
        logger.info(f"Update trùng lặp (update_id={update_id}), bỏ qua.")
        return JSONResponse(content={"ok": True}, status_code=200)
    _last_update_id = update_id

    # QUAN TRỌNG: đưa việc xử lý ra chạy NỀN (background task),
    # để trả response 200 cho Telegram NGAY LẬP TỨC, không đợi xử lý xong.
    # Đây chính là điểm khắc phục bug loop bạn từng gặp (blocking sync trong async handler).
    asyncio.create_task(process_message_background(update))

    return JSONResponse(content={"ok": True}, status_code=200)


# ============================================
# ENDPOINT KIỂM TRA SỨC KHỎE (health check)
# ============================================
@app.get("/")
async def root():
    return {"status": "Bot đang chạy", "webhook_path": "/webhook"}


@app.get("/health")
async def health():
    return {"status": "ok"}


# ============================================
# ENDPOINT TIỆN ÍCH: TỰ ĐỘNG SET WEBHOOK
# Gọi endpoint này 1 lần sau khi deploy để đăng ký webhook với Telegram
# Ví dụ: GET https://<space-url>/set_webhook?url=https://<space-url>/webhook
# ============================================
@app.get("/set_webhook")
async def set_webhook(url: str):
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(
            f"{TELEGRAM_API}/setWebhook",
            params={"url": url, "drop_pending_updates": "true"}
        )
        result = resp.json()
        logger.info(f"Set webhook result: {result}")
        return result


@app.get("/webhook_info")
async def webhook_info():
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(f"{TELEGRAM_API}/getWebhookInfo")
        return resp.json()


@app.get("/delete_webhook")
async def delete_webhook_endpoint():
    async with httpx.AsyncClient(timeout=10.0) as client:
        resp = await client.get(f"{TELEGRAM_API}/deleteWebhook")
        return resp.json()