File size: 4,343 Bytes
a577a4e
cf88048
 
2cb5b51
 
33c03b7
e01c50e
33c03b7
e01c50e
2cb5b51
e01c50e
2cb5b51
cf88048
 
a577a4e
cf88048
a577a4e
2cb5b51
 
136b6f2
 
e01c50e
 
 
 
 
1546637
e01c50e
 
136b6f2
1546637
2cb5b51
 
cf88048
e01c50e
cf88048
e01c50e
 
 
 
1546637
e01c50e
 
 
 
 
 
 
 
 
 
 
cf88048
e01c50e
 
 
 
 
 
cf88048
e01c50e
cf88048
 
e01c50e
 
 
cf88048
 
1546637
cf88048
e01c50e
cf88048
e01c50e
 
 
cf88048
 
e01c50e
 
 
cf88048
 
 
e01c50e
 
 
 
f8ccb73
1546637
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16a25d6
e01c50e
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
import os, random, httpx, uvicorn
from fastapi import FastAPI, Request, Response
from fastapi.responses import HTMLResponse

app = FastAPI()

# 🛡️ Pool de 15 Chaves - Carregamento Seguro
KEYS = [os.getenv(f"OR_KEY_{i}") for i in range(1, 16)]
KEYS = [k.strip() for k in KEYS if k and k.strip()]

# 🧠 MAPEAMENTO DE ELITE (Roteamento por Projeto)
MODEL_MAP = {
    "gpt-4o": "qwen/qwen3-coder:free",
    "vitalis": "google/gemini-2.0-pro-exp-02-05:free", 
    "nexos": "qwen/qwen3-coder:free",
    "nutrilens": "google/gemini-2.0-flash-lite-preview-02-05:free", 
    "default": "qwen/qwen3-coder:free"
}

@app.get("/", response_class=HTMLResponse)
async def root():
    status_color = "#00ff00" if KEYS else "#ff0000"
    return f"""
    <body style="background: #0e1117; color: white; font-family: sans-serif; text-align: center; padding-top: 50px;">
        <h1 style="color: {status_color};">🛡️ Escudo Fortune Ativo</h1>
        <p><b>{len(KEYS)}</b> chaves operacionais no sistema.</p>
        <p style="color: #888;">Status: Roteador AI e Ponte Telegram Operacionais.</p>
    </body>
    """

# 1️⃣ ROTA DO CÉREBRO (Modelos de IA)
@app.post("/v1/chat/completions")
async def proxy(request: Request):
    if not KEYS:
        return Response(content='{"error": "Nenhuma chave configurada nos Secrets!"}', status_code=500)

    try:
        body = await request.json()
        msg_content = str(body.get("messages", "")).lower()
        
        # 🛰️ Roteador Inteligente de Projetos
        target = MODEL_MAP["gpt-4o"]
        if "vitalis" in msg_content: 
            target = MODEL_MAP["vitalis"]
        elif "nexos" in msg_content: 
            target = MODEL_MAP["nexos"]
        elif "nutrilens" in msg_content: 
            target = MODEL_MAP["nutrilens"]
        
        body["model"] = target
        
        selected_key = random.choice(KEYS).strip()

        headers = {
            "Authorization": f"Bearer {selected_key}",
            "X-Title": "Aria_Sovereign_System",
            "HTTP-Referer": "https://fortune-dev-moz.io",
            "Content-Type": "application/json"
        }

        async with httpx.AsyncClient() as client:
            resp = await client.post(
                "https://openrouter.ai/api/v1/chat/completions",
                json=body, 
                headers=headers, 
                timeout=60.0
            )
            
            # 🚨 Modo de Emergência
            if resp.status_code != 200:
                print(f"⚠️ Erro {resp.status_code} na chave atual. Tentando emergência...")
                body["model"] = "openrouter/free"
                new_key = random.choice(KEYS).strip()
                headers["Authorization"] = f"Bearer {new_key}"
                
                resp = await client.post(
                    "https://openrouter.ai/api/v1/chat/completions",
                    json=body, 
                    headers=headers, 
                    timeout=60.0
                )
                
            return Response(content=resp.content, status_code=resp.status_code)

    except Exception as e:
        print(f"🔥 Erro Crítico: {str(e)}")
        return Response(content=f'{{"error": "{str(e)}"}}', status_code=500)

# 2️⃣ ROTA DA BOCA/OUVIDOS (Ponte de Rede para o Telegram)
@app.api_route("/bot{token}/{method_name}", methods=["GET", "POST"])
async def telegram_proxy(request: Request, token: str, method_name: str):
    target_url = f"https://api.telegram.org/bot{token}/{method_name}"
    try:
        async with httpx.AsyncClient() as client:
            if request.method == "POST":
                body = await request.body()
                headers = {"Content-Type": request.headers.get("content-type", "application/json")}
                resp = await client.post(target_url, content=body, headers=headers, timeout=60.0)
            else:
                resp = await client.get(target_url, params=request.query_params, timeout=60.0)
            return Response(content=resp.content, status_code=resp.status_code)
    except Exception as e:
        print(f"🔥 Erro na Ponte Telegram: {str(e)}")
        return Response(content=f'{{"ok": false, "error_code": 500, "description": "Erro no Escudo: {str(e)}"}}', status_code=500)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)