import os import requests import gradio as gr import gspread from google.oauth2.service_account import Credentials from datetime import datetime # Autenticación con Google Sheets usando el archivo credentials.json scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] creds = Credentials.from_service_account_file("credentials.json", scopes=scope) client = gspread.authorize(creds) # Abre el Google Sheet (reemplaza 'NOMBRE_DE_TU_SHEET' por el nombre de tu hoja) spreadsheet = client.open("Sim Cards Invertaxi") sheet = spreadsheet.sheet1 # Asume que trabajas en la primera hoja # Obtener el token de la variable de entorno api_token = os.getenv('API_TOKEN') def get_sim_status(iccid): url = f"https://iot.truphone.com/api/v2.2/sims/{iccid}/status" headers = {"Authorization": f"Token {api_token}"} response = requests.get(url, headers=headers) if response.status_code == 200: print("Solicitud exitosa:", response.json()) return response.json() else: print(f"Error al realizar la solicitud: {response.status_code}") return None def send_sms(iccid, text): url = "https://iot.truphone.com/api/v2.0/sims/send_sms" headers = { "Authorization": f"Token {api_token}", "Content-Type": "application/json" } body = {"iccid": [iccid], "text": text} response = requests.post(url, json=body, headers=headers) if response.status_code == 200: print("Mensaje enviado exitosamente") return "ok" else: print(f"Error al enviar el mensaje: {response.status_code}") return "error" def save_to_google_sheets(iccid, placa, imei, operario): """Guarda los datos en Google Sheets.""" fecha_actual = datetime.now().strftime('%Y-%m-%d') try: sheet.append_row([iccid, placa, imei, operario, fecha_actual]) print("Datos guardados exitosamente en Google Sheets.") except Exception as e: print(f"Error al guardar en Google Sheets: {e}") def program_gps(iccid_list, placa, imei, operario, tipo_gps): """Programa los GPS con comandos específicos según el tipo de dispositivo.""" messages = { 'Coban': [ 'begin123456', 'apn123456 iot.truphone.com', 'fix090s***n123456', 'dns123456 track.falconcol.com 5001', 'gprs123456', 'reset123456' ], 'Concox': [ 'Apn,iot.truphone.com#', 'TIMER,90,1200#', "SERVER,1,track.falconcol.com,5023,0#", 'RESET#' ] } iccids = iccid_list.split(',') text = f"Programación iniciada por {operario} para GPS tipo {tipo_gps}.\n\n" gps_messages = messages[tipo_gps] for sim in iccids: sim = sim.strip() status_response = get_sim_status(sim) sim_card_service = status_response.get('status', {}).get('sim_card_service', "error") if status_response else "error" aswr_ok = sum([1 for message in gps_messages if send_sms(sim, message) == "ok"]) if aswr_ok == len(gps_messages): status_text = f"{sim} (Placa: {placa}, IMEI: {imei}) - ok.\n" if sim_card_service == 'SUSPENDED': status_text += "Bloqueada por consumo, solicitar reactivación.\n" text += status_text save_to_google_sheets(sim, placa, imei, operario) else: text += f"{sim} (Placa: {placa}, IMEI: {imei}) - fail\n" return text # Crea una interfaz de Gradio con los nuevos campos iface = gr.Interface( fn=program_gps, inputs=[ gr.Textbox(label="Introduce los ICCIDs separados por comas"), gr.Textbox(label="Placa del vehículo"), gr.Textbox(label="IMEI del dispositivo"), gr.Radio(choices=["Santiago", "Daniel"], label="Operario"), gr.Radio(choices=["Coban", "Concox"], label="Tipo de GPS") ], outputs="text", title="Programador de GPS", description="Introduce los ICCIDs, la placa, el IMEI y selecciona un operario para programar los GPS." ) # Lanza la interfaz iface.launch()