|
| 1 | +""" |
| 2 | +Cliente HTTP para comunicar com o bot-report-api. |
| 3 | +""" |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import json |
| 7 | +import urllib.request |
| 8 | +import urllib.error |
| 9 | +from typing import Any, Optional |
| 10 | + |
| 11 | + |
| 12 | +class ApiError(Exception): |
| 13 | + """Erro de comunicação com o bot-report-api.""" |
| 14 | + def __init__(self, status: int, mensagem: str) -> None: |
| 15 | + self.status = status |
| 16 | + super().__init__(f"API retornou {status}: {mensagem}") |
| 17 | + |
| 18 | + |
| 19 | +class BotReportClient: |
| 20 | + """ |
| 21 | + Cliente leve para o bot-report-api (sem dependência de requests). |
| 22 | +
|
| 23 | + Usa apenas a stdlib do Python para comunicação HTTP. |
| 24 | +
|
| 25 | + Exemplo:: |
| 26 | +
|
| 27 | + client = BotReportClient("http://localhost:8000") |
| 28 | + bot = client.obter_ou_criar_bot("Meu Bot", tipo="web") |
| 29 | + exec_id = client.iniciar_execucao(bot["id"]) |
| 30 | + client.finalizar_execucao(exec_id, status="sucesso", duracao=12.5) |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, base_url: str, timeout: int = 10) -> None: |
| 34 | + self.base_url = base_url.rstrip("/") |
| 35 | + self.timeout = timeout |
| 36 | + |
| 37 | + # ------------------------------------------------------------------ |
| 38 | + # Bots |
| 39 | + # ------------------------------------------------------------------ |
| 40 | + |
| 41 | + def listar_bots(self) -> list[dict]: |
| 42 | + return self._get("/bots/") |
| 43 | + |
| 44 | + def criar_bot(self, nome: str, tipo: str = "web", descricao: str = "") -> dict: |
| 45 | + return self._post("/bots/", {"nome": nome, "tipo": tipo, "descricao": descricao}) |
| 46 | + |
| 47 | + def obter_ou_criar_bot(self, nome: str, tipo: str = "web") -> dict: |
| 48 | + """Retorna o bot existente com o nome dado, ou cria um novo.""" |
| 49 | + bots = self.listar_bots() |
| 50 | + for bot in bots: |
| 51 | + if bot["nome"] == nome: |
| 52 | + return bot |
| 53 | + return self.criar_bot(nome, tipo=tipo) |
| 54 | + |
| 55 | + # ------------------------------------------------------------------ |
| 56 | + # Execuções |
| 57 | + # ------------------------------------------------------------------ |
| 58 | + |
| 59 | + def iniciar_execucao(self, bot_id: int) -> int: |
| 60 | + """Registra início de execução e retorna o ID da execução.""" |
| 61 | + exec_ = self._post("/execucoes/", {"bot_id": bot_id, "status": "em_andamento"}) |
| 62 | + return exec_["id"] |
| 63 | + |
| 64 | + def finalizar_execucao( |
| 65 | + self, |
| 66 | + exec_id: int, |
| 67 | + status: str, |
| 68 | + duracao_segundos: Optional[float] = None, |
| 69 | + mensagem: Optional[str] = None, |
| 70 | + ) -> dict: |
| 71 | + """Atualiza o status de uma execução (sucesso/falha/cancelado).""" |
| 72 | + payload: dict[str, Any] = {"status": status} |
| 73 | + if duracao_segundos is not None: |
| 74 | + payload["duracao_segundos"] = duracao_segundos |
| 75 | + if mensagem: |
| 76 | + payload["mensagem"] = mensagem |
| 77 | + return self._patch(f"/execucoes/{exec_id}", payload) |
| 78 | + |
| 79 | + def health(self) -> bool: |
| 80 | + """Retorna True se a API estiver respondendo.""" |
| 81 | + try: |
| 82 | + resp = self._get("/health") |
| 83 | + return resp.get("status") == "ok" |
| 84 | + except Exception: |
| 85 | + return False |
| 86 | + |
| 87 | + # ------------------------------------------------------------------ |
| 88 | + # HTTP interno |
| 89 | + # ------------------------------------------------------------------ |
| 90 | + |
| 91 | + def _get(self, path: str) -> Any: |
| 92 | + url = f"{self.base_url}{path}" |
| 93 | + req = urllib.request.Request(url, headers={"Accept": "application/json"}) |
| 94 | + try: |
| 95 | + with urllib.request.urlopen(req, timeout=self.timeout) as resp: |
| 96 | + return json.loads(resp.read()) |
| 97 | + except urllib.error.HTTPError as e: |
| 98 | + raise ApiError(e.code, e.read().decode()) |
| 99 | + |
| 100 | + def _post(self, path: str, dados: dict) -> Any: |
| 101 | + return self._request("POST", path, dados) |
| 102 | + |
| 103 | + def _patch(self, path: str, dados: dict) -> Any: |
| 104 | + return self._request("PATCH", path, dados) |
| 105 | + |
| 106 | + def _request(self, metodo: str, path: str, dados: dict) -> Any: |
| 107 | + url = f"{self.base_url}{path}" |
| 108 | + corpo = json.dumps(dados).encode() |
| 109 | + req = urllib.request.Request( |
| 110 | + url, data=corpo, method=metodo, |
| 111 | + headers={"Content-Type": "application/json", "Accept": "application/json"}, |
| 112 | + ) |
| 113 | + try: |
| 114 | + with urllib.request.urlopen(req, timeout=self.timeout) as resp: |
| 115 | + return json.loads(resp.read()) |
| 116 | + except urllib.error.HTTPError as e: |
| 117 | + raise ApiError(e.code, e.read().decode()) |
0 commit comments