phanquocdat123's picture
Create main.py
4519f1e verified
Raw History Blame Contribute Delete
5.52 kB
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()