Spaces:
Paused
Paused
File size: 2,493 Bytes
f6cb78b |
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 |
import time
import json
from pathlib import Path
from typing import Literal, Optional
# Rutas
LOG_FILE = Path("logs/registro_uso.json")
USER_STATS_FILE = Path("logs/usuarios.json")
# Crear carpeta si no existe
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
# Tipo de entrada admitida
TipoEntrada = Literal["Texto", "Imagen", "PDF", "DOCX", "TXT", "Otro"]
def registrar_uso(
user_id: int,
username: Optional[str],
tipo_entrada: TipoEntrada,
duracion_segundos: float,
exito: bool,
fuente: Optional[str] = "telegram_bot",
) -> None:
"""
Registra un evento de uso y actualiza el historial acumulado por usuario.
"""
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
log_entry = {
"timestamp": timestamp,
"user_id": user_id,
"username": username or "N/A",
"tipo_entrada": tipo_entrada,
"duracion_segundos": round(duracion_segundos, 2),
"exito": exito,
"fuente": fuente,
}
# Guardar log individual
try:
registros = []
if LOG_FILE.exists():
with open(LOG_FILE, "r", encoding="utf-8") as f:
registros = json.load(f)
registros.append(log_entry)
with open(LOG_FILE, "w", encoding="utf-8") as f:
json.dump(registros, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"[ERROR] No se pudo guardar el registro individual: {e}")
# Actualizar conteo acumulado
try:
resumen = {}
if USER_STATS_FILE.exists():
with open(USER_STATS_FILE, "r", encoding="utf-8") as f:
resumen = json.load(f)
uid = str(user_id)
if uid not in resumen:
resumen[uid] = {
"username": username or "N/A",
"total_usos": 0,
"exitosos": 0,
"fallidos": 0,
"ultima_vez": timestamp
}
resumen[uid]["username"] = username or "N/A"
resumen[uid]["total_usos"] += 1
resumen[uid]["ultima_vez"] = timestamp
if exito:
resumen[uid]["exitosos"] += 1
else:
resumen[uid]["fallidos"] += 1
with open(USER_STATS_FILE, "w", encoding="utf-8") as f:
json.dump(resumen, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"[ERROR] No se pudo actualizar el resumen de usuarios: {e}")
|