- generador/: ficha.py (validación cliente.yml), registro.py (registry.json + puertos), plantillas.py (.env/compose/README/scripts), nucleo.py (estampar/validar_paquete/desplegar), evolution.py (API client), CLI python -m generador (estampar|validar|whatsapp|desplegar|listar|eliminar) - src/api/webhook_evolution.py: adaptador webhook nativo Evolution → WebhookMessage (réplicas sin n8n); registrado en main.py - fichas/ejemplo-demo.yml: ficha demo con credenciales falsas - Solo-generar es default; --desplegar explícito. El generador solo LEE el molde (git archive de HEAD) y ESCRIBE en replicas/ (gitignored) - 31 tests nuevos (Evolution mockeado con httpx.MockTransport): 158 verdes
96 lines
3.6 KiB
Python
96 lines
3.6 KiB
Python
"""Cliente de la API de Evolution para aprovisionar instancias de réplicas.
|
|
|
|
El Evolution destino sale del .env de CADA réplica (EVOLUTION_API_URL):
|
|
central del VPS propio para réplicas locales, o el Evolution del cliente
|
|
para paquetes portables. Este módulo no asume cuál.
|
|
|
|
`transport` es inyectable (httpx.MockTransport) para tests sin red.
|
|
"""
|
|
|
|
import logging
|
|
|
|
import httpx
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ErrorEvolution(Exception):
|
|
pass
|
|
|
|
|
|
class ClienteEvolution:
|
|
def __init__(self, api_url: str, api_key: str, transport=None):
|
|
self._http = httpx.Client(
|
|
base_url=api_url.rstrip("/"),
|
|
headers={"apikey": api_key, "Content-Type": "application/json"},
|
|
timeout=20,
|
|
transport=transport,
|
|
)
|
|
|
|
def _llamar(self, metodo: str, ruta: str, json_body: dict | None = None) -> dict | list:
|
|
try:
|
|
r = self._http.request(metodo, ruta, json=json_body)
|
|
except httpx.HTTPError as e:
|
|
raise ErrorEvolution(f"No se pudo conectar a Evolution ({ruta}): {e}") from e
|
|
if r.status_code >= 400:
|
|
raise ErrorEvolution(
|
|
f"Evolution respondió {r.status_code} en {ruta}: {r.text[:300]}"
|
|
)
|
|
try:
|
|
return r.json() if r.content else {}
|
|
except ValueError:
|
|
return {}
|
|
|
|
# ── operaciones ─────────────────────────────────────────────────
|
|
def instancia_existe(self, nombre: str) -> bool:
|
|
try:
|
|
datos = self._llamar("GET", f"/instance/fetchInstances?instanceName={nombre}")
|
|
except ErrorEvolution:
|
|
return False
|
|
lista = datos if isinstance(datos, list) else datos.get("instances", [])
|
|
return any(
|
|
(i.get("name") or (i.get("instance") or {}).get("instanceName")) == nombre
|
|
for i in lista
|
|
)
|
|
|
|
def crear_instancia(self, nombre: str) -> dict:
|
|
return self._llamar("POST", "/instance/create", {
|
|
"instanceName": nombre,
|
|
"integration": "WHATSAPP-BAILEYS",
|
|
"qrcode": True,
|
|
})
|
|
|
|
def configurar_webhook(self, nombre: str, url_webhook: str) -> dict:
|
|
return self._llamar("POST", f"/webhook/set/{nombre}", {
|
|
"webhook": {
|
|
"enabled": True,
|
|
"url": url_webhook,
|
|
"webhookByEvents": False,
|
|
"webhookBase64": True,
|
|
"events": ["MESSAGES_UPSERT"],
|
|
}
|
|
})
|
|
|
|
def obtener_qr(self, nombre: str) -> dict:
|
|
"""Devuelve el dict de /instance/connect (base64 del QR y/o pairingCode)."""
|
|
return self._llamar("GET", f"/instance/connect/{nombre}")
|
|
|
|
def estado_conexion(self, nombre: str) -> str:
|
|
datos = self._llamar("GET", f"/instance/connectionState/{nombre}")
|
|
return ((datos or {}).get("instance") or {}).get("state", "desconocido")
|
|
|
|
def eliminar_instancia(self, nombre: str) -> None:
|
|
self._llamar("DELETE", f"/instance/delete/{nombre}")
|
|
|
|
|
|
def aprovisionar(cliente: ClienteEvolution, slug: str, base_url: str) -> str:
|
|
"""Crea la instancia si falta y configura su webhook → la réplica.
|
|
Devuelve el estado de conexión actual ('open' si ya está vinculada)."""
|
|
if not cliente.instancia_existe(slug):
|
|
logger.info("Creando instancia Evolution '%s'", slug)
|
|
cliente.crear_instancia(slug)
|
|
webhook = base_url.rstrip("/") + "/webhook/evolution"
|
|
logger.info("Configurando webhook de '%s' → %s", slug, webhook)
|
|
cliente.configurar_webhook(slug, webhook)
|
|
return cliente.estado_conexion(slug)
|