File size: 3,225 Bytes
0e7b0a3
 
 
 
05f1c74
7e96c21
357cd59
 
05f1c74
027af30
53e9bc3
0e7b0a3
 
 
d37fcfc
0e7b0a3
 
 
 
 
 
 
 
 
 
 
 
 
85c96f5
0e7b0a3
 
d37fcfc
0e7b0a3
 
d37fcfc
0e7b0a3
 
 
 
d37fcfc
 
4e30a4f
 
d37fcfc
0e7b0a3
9892e56
add6179
9892e56
7d7f669
 
 
 
 
161c07b
 
 
0e7b0a3
 
 
 
153a089
 
0e7b0a3
153a089
51437db
 
8790e63
5316f49
 
d4588fa
 
df572ba
29b7292
df572ba
d4588fa
5316f49
1522146
f969e71
5316f49
 
 
 
 
0e7b0a3
 
 
 
 
 
 
 
9aa81c0
 
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
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import os
import json
import httpx
import subprocess
#import asyncio #alternativa a 
#from waitress import serve #alternativa a 
#import socket #para funcionalidad ipv6
import aiohttp
#import telebot #https://github.com/eternnoir/pyTelegramBotAPI

app = FastAPI()

# Configurar CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Cargar los códigos y configuración de Telegram desde las variables de entorno
@app.on_event("startup")
async def startup_event():
    global codigos, TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
    codigos_json = os.environ.get("codigos")
    print("codigos recogidos pero no chequeados")
    if codigos_json:
        codigos = json.loads(codigos_json)
        print("Códigos cargados correctamente")
    else:
        codigos = {}
        print("No se encontraron códigos en las variables de entorno")
    
    TELEGRAM_BOT_TOKEN = os.environ.get("T_bot")
    TELEGRAM_CHAT_ID = os.environ.get("nroChat")

    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        print("Faltan configuraciones de Telegram")
    else:
        print("Claves de telegram cargados correctamente")

async def send_telegram_message(message):
    #envio mensaje por medio de un script externo
    subprocess.run(["python", "/code/envia_mensaje.py", message])

    #url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    #params = {
    #    "chat_id": TELEGRAM_CHAT_ID,
    #    "text": message
    #}

    # async with httpx.AsyncClient() as client:
    #     await client.post(url, params=params)

@app.get("/verificar/{codigo}")
async def verificar_codigo(codigo: str):
    if codigo in codigos:
        if codigos[codigo] > 0:

            # Enviar mensaje a Telegram
            mensaje = f"Código utilizado: {codigo}\nConsultas restantes: {codigos[codigo]}"
            print(f"\nmensaje:")
            print(mensaje, end="\n\n")
            #await send_telegram_message(mensaje)
            #subprocess.run(["python", "envia_mensaje.py", mensaje])

            #chequeo a ver si está el scirpt
            print("averrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr")
            print(os.getcwd())
            print(os.listdir())
            print("averrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr")

            # Ejecuta el script Bash con el mensaje como argumento
            result = subprocess.run(["ls"], capture_output=True, text=True)
            result = subprocess.run(["./envia_mensaje.sh", mensaje], capture_output=True, text=True)
            # Imprime la salida del script Bash
            print("STDOUT:", result.stdout)
            print("STDERR:", result.stderr)
            if result.returncode != 0:
                print(f"Ocurrió un Error: {result.returncode}")
            
            return {"mensaje": "código encontrado", "consultas_restantes": codigos[codigo]}
        else:
            return {"mensaje": "código caducado"}
    else:
        return {"mensaje": "código no encontrado"}

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