Files
botAffilate/serverPython/main.py
T

58 lines
2.0 KiB
Python

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from automation import ShopeeBot
from typing import Optional
import logging
import os
import sys
# Cấu hình logging: ghi log ra cả màn hình (console) và file (shopee_bot.log)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("shopee_bot.log", encoding="utf-8"),
logging.StreamHandler(sys.stdout)
]
)
app = FastAPI(title="n8n Shopee Bridge API")
class CommissionRequest(BaseModel):
link: str
# Cho phép truyền IP linh hoạt từ n8n.
device_ip: Optional[str] = Field(default=None, description="IP:Port của điện thoại, ví dụ 192.168.1.100:5555 (WiFi) hoặc 10.8.0.5:5555 (VPN)")
@app.post("/get_commission")
async def get_commission_endpoint(req: CommissionRequest):
if not req.link:
raise HTTPException(status_code=400, detail="Thiếu link sản phẩm")
try:
# Lấy IP theo độ ưu tiên:
# 1. Truyền từ Request Body của n8n
# 2. Truyền từ biến môi trường DEVICE_IP của Armbian/Windows
# 3. Để rỗng "" (Thư viện u2 sẽ tự tìm thiết bị ADB đang cắm/connect)
target_ip = req.device_ip or os.environ.get("DEVICE_IP") or ""
bot = ShopeeBot(device_ip=target_ip)
result = bot.get_commission_rate(req.link)
# Nếu đã có status thì gộp thẳng các thuộc tính của result vào JSON trả về
if isinstance(result, dict) and "status" in result:
return result
return {
"status": "success",
"commission": result
}
except Exception as e:
logging.error(f"Lỗi API: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
# Chạy server API ở cổng 8000
uvicorn.run(app, host="0.0.0.0", port=8000)