"""Cliente da Central de Números WhatsApp (IAMAI) — copie este arquivo para o seu projeto. Só usa a biblioteca padrão do Python (3.9+). Nenhum projeto precisa falar direto com Salvy, HookCloud ou Meta: tudo passa pela Central, autenticado pela chave do projeto (X-Internal-Api-Key). Baixar/atualizar: curl -fsSL https://central-whatsapp.iamai.ia.br/sdk/python -o central_whatsapp_client.py Documentação: https://central-whatsapp.iamai.ia.br/llms.txt Uso rápido ---------- from central_whatsapp_client import CentralWhatsApp, CentralErro central = CentralWhatsApp( "https://central-whatsapp.iamai.ia.br", chave=os.environ["CENTRAL_API_KEY"], telefone="+5511987650000", # número padrão que envia (ou numero_id=...) ) print(central.quem_sou_eu()) # {"projeto": "saas_feedback", ...} central.enviar_texto("5511988887777", "Olá! Seu pedido saiu para entrega.") central.enviar_template("5511988887777", "pesquisa_satisfacao", variaveis=["Ana", "Pizzaria Bella"]) central.enviar_botoes("5511988887777", "Gostou?", ["Sim", "Não"]) try: central.enviar_texto("5511900000000", "oi") except CentralErro as erro: if erro.codigo_meta == 131047: # fora da janela de 24 h central.enviar_template("5511900000000", "reabrir_conversa") Webhook (receber da Central) ---------------------------- corpo = request.body() # corpo BRUTO if not verificar_assinatura(SEGREDO, corpo, headers["X-Central-Timestamp"], headers["X-Central-Signature"]): return 401 for evento in interpretar_webhook(corpo): if evento["tipo"] == "mensagem": # cliente escreveu ... elif evento["tipo"] == "evento_admin" and evento["status"] in ("desconectado", "pausado", "cancelado"): ... # parar envios daquele número Erros: toda falha vira CentralErro(status_http, detalhe, codigo_meta). """ from __future__ import annotations import hashlib import hmac import json import time import urllib.error import urllib.parse import urllib.request from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple __all__ = ["CentralWhatsApp", "CentralErro", "verificar_assinatura", "interpretar_webhook"] __version__ = "1.0.0" # Transporte: (método, url, headers, corpo_bytes, timeout) -> (status, headers, corpo_bytes) Transporte = Callable[[str, str, Dict[str, str], Optional[bytes], float], Tuple[int, Dict[str, str], bytes]] class CentralErro(Exception): """Erro devolvido pela Central. `codigo_meta` vem preenchido quando a Meta recusou (ex.: 131047).""" def __init__(self, status_http: int, detalhe: str, codigo_meta: Optional[int] = None, dados: Any = None) -> None: super().__init__(f"[{status_http}] {detalhe}") self.status_http = status_http self.detalhe = detalhe self.codigo_meta = codigo_meta self.dados = dados @property def fora_da_janela(self) -> bool: """True quando a Meta recusou por estar fora da janela de 24 h (use um template).""" return self.codigo_meta == 131047 def _transporte_urllib( metodo: str, url: str, headers: Dict[str, str], corpo: Optional[bytes], timeout: float ) -> Tuple[int, Dict[str, str], bytes]: requisicao = urllib.request.Request(url, data=corpo, method=metodo, headers=headers) try: with urllib.request.urlopen(requisicao, timeout=timeout) as resposta: # noqa: S310 (URL da Central) return resposta.status, dict(resposta.headers.items()), resposta.read() except urllib.error.HTTPError as erro: return erro.code, dict(erro.headers.items()) if erro.headers else {}, erro.read() or b"" except urllib.error.URLError as erro: raise CentralErro(0, f"Não consegui falar com a Central: {erro.reason}") from erro class CentralWhatsApp: """Cliente da Central. `telefone`/`numero_id` definem o número padrão que envia (opcional).""" def __init__( self, url_base: str, chave: str, *, telefone: Optional[str] = None, numero_id: Optional[str] = None, timeout: float = 30.0, transporte: Optional[Transporte] = None, ) -> None: if not chave: raise ValueError("Informe a chave do projeto (X-Internal-Api-Key).") self.url_base = url_base.rstrip("/") self.chave = chave self.telefone = telefone self.numero_id = numero_id self.timeout = timeout self._transporte = transporte or _transporte_urllib # ------------------------------------------------------------------ infraestrutura def _requisitar( self, metodo: str, caminho: str, *, json_corpo: Any = None, params: Optional[Dict[str, Any]] = None, bruto: bool = False, ) -> Any: url = self.url_base + caminho if params: limpos = {k: ("true" if v is True else "false" if v is False else v) for k, v in params.items() if v is not None} if limpos: url += "?" + urllib.parse.urlencode(limpos) headers = {"X-Internal-Api-Key": self.chave, "Accept": "application/json", "User-Agent": f"central-whatsapp-py/{__version__}"} corpo = None if json_corpo is not None: corpo = json.dumps(json_corpo, ensure_ascii=False).encode("utf-8") headers["Content-Type"] = "application/json" status, cabecalhos, conteudo = self._transporte(metodo, url, headers, corpo, self.timeout) if status >= 400 or status == 0: try: dados = json.loads(conteudo or b"{}") except ValueError: dados = {"detail": conteudo[:300].decode("utf-8", "replace")} detalhe = dados.get("detail") if isinstance(dados, dict) else str(dados) if isinstance(detalhe, list): # erro de validação (422) detalhe = "; ".join(str(d.get("msg", d)).replace("Value error, ", "") for d in detalhe) meta = dados.get("meta") if isinstance(dados, dict) else None raise CentralErro(status, str(detalhe or f"HTTP {status}"), (meta or {}).get("codigo"), dados) if bruto: return conteudo, cabecalhos if not conteudo: return None return json.loads(conteudo) def _numero(self, numero_id: Optional[str], telefone: Optional[str]) -> Dict[str, str]: numero_id = numero_id or (None if telefone else self.numero_id) telefone = telefone or (None if numero_id else self.telefone) if not numero_id and not telefone: raise ValueError("Informe numero_id ou telefone (ou defina um padrão ao criar o cliente).") return {"numero_id": numero_id} if numero_id else {"telefone": telefone} # type: ignore[dict-item] def _ident(self, numero: Optional[str]) -> str: valor = numero or self.numero_id or self.telefone if not valor: raise ValueError("Informe o número (id ou telefone).") return urllib.parse.quote(str(valor), safe="") # ------------------------------------------------------------------ identidade def quem_sou_eu(self) -> Dict[str, Any]: """Qual projeto esta chave representa e quantos números ele tem.""" return self._requisitar("GET", "/api/eu") # ------------------------------------------------------------------ números (ciclo de vida) def listar_numeros(self, *, status: Optional[str] = None, cliente_id: Optional[str] = None, incluir_cancelados: bool = False) -> List[Dict[str, Any]]: return self._requisitar("GET", "/api/numeros", params={ "status": status, "cliente_id": cliente_id, "incluir_cancelados": incluir_cancelados or None, })["conexoes"] def obter_numero(self, numero: Optional[str] = None) -> Dict[str, Any]: return self._requisitar("GET", f"/api/numeros/{self._ident(numero)}") def solicitar_numero( self, origem: str = "salvy_api", *, cliente_id: str = "interno", telefone: Optional[str] = None, ddd: Optional[int] = None, webhook_destino_url: Optional[str] = None, cliente_nome: Optional[str] = None, cliente_email: Optional[str] = None, ) -> Dict[str, Any]: """origem: 'salvy_api' (a Central compra a linha) ou 'chip_proprio' (informe telefone). Devolve solicitacao_id e embedded_signup.connect_url (mostre ao dono do número). """ return self._requisitar("POST", "/api/numeros/solicitar", json_corpo={ "origem_linha": origem, "cliente_id": cliente_id, "telefone": telefone, "ddd": ddd, "webhook_destino_url": webhook_destino_url, "cliente_nome": cliente_nome, "cliente_email": cliente_email, }) def acompanhar_conexao(self, numero: str) -> Dict[str, Any]: """Código SMS (linhas Salvy) + status. Chame a cada 3 s enquanto o status não for 'ativo'.""" return self._requisitar("GET", f"/api/numeros/{self._ident(numero)}/sms") def aguardar_ativacao(self, numero: str, *, limite_seg: float = 900, intervalo_seg: float = 3, ao_receber_codigo: Optional[Callable[[str], None]] = None) -> Dict[str, Any]: """Bloqueia até o número ficar ativo (ou estourar o tempo). Chama ao_receber_codigo(código) a cada código novo.""" fim = time.monotonic() + limite_seg ultimo = None while time.monotonic() < fim: visor = self.acompanhar_conexao(numero) if visor.get("codigo") and visor.get("codigo") != ultimo: ultimo = visor["codigo"] if ao_receber_codigo: ao_receber_codigo(visor.get("codigo_formatado") or ultimo) if visor.get("status") == "ativo": return visor if visor.get("status") == "cancelado": raise CentralErro(409, "A conexão foi cancelada.") time.sleep(intervalo_seg) raise CentralErro(408, "O número não ficou ativo dentro do tempo.") def link_conexao(self, numero: str, *, reaproveitar: bool = True) -> Dict[str, Any]: return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/link-conexao", params={"reaproveitar": reaproveitar}) def reconectar(self, numero: Optional[str] = None, *, modo: str = "reconectar") -> Dict[str, Any]: """Link de reconexão (modo 'reconectar') ou fluxo completo de novo (modo 'conectar').""" return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/reconectar", json_corpo={"modo": modo}) def concluir_conexao(self, numero: str, *, phone_number_id: Optional[str] = None, waba_id: Optional[str] = None, meta_access_token: Optional[str] = None) -> Dict[str, Any]: """Sem credenciais: a Central busca no HookCloud. Com credenciais: grava as informadas.""" corpo = {k: v for k, v in {"phone_number_id": phone_number_id, "waba_id": waba_id, "meta_access_token": meta_access_token}.items() if v} return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/concluir-conexao", json_corpo=corpo) def editar_numero(self, numero: str, *, webhook_destino_url: Optional[str] = None, cliente_id: Optional[str] = None, usar_destino_do_projeto: bool = False) -> Dict[str, Any]: corpo: Dict[str, Any] = {} if usar_destino_do_projeto: corpo["webhook_destino_url"] = None elif webhook_destino_url: corpo["webhook_destino_url"] = webhook_destino_url if cliente_id: corpo["cliente_id"] = cliente_id return self._requisitar("PATCH", f"/api/numeros/{self._ident(numero)}", json_corpo=corpo) def pausar(self, numero: str) -> Dict[str, Any]: return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/pausar") def reativar(self, numero: str) -> Dict[str, Any]: return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/reativar") def cancelar(self, numero: str, *, cancelar_linha_salvy: bool = False, desativar_hookcloud: bool = False, motivo: str = "unnecessary") -> Dict[str, Any]: """Definitivo. cancelar_linha_salvy: a Salvy cobra o mês inteiro do cancelamento.""" return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/cancelar", json_corpo={ "cancelar_linha_salvy": cancelar_linha_salvy, "desativar_hookcloud": desativar_hookcloud, "motivo": motivo, }) def credenciais(self, *, cliente_id: Optional[str] = None, telefone: Optional[str] = None) -> List[Dict[str, Any]]: """Só para quem ainda envia direto na Graph API (o recomendado é enviar pela Central).""" return self._requisitar("GET", "/api/numeros/credenciais", params={"cliente_id": cliente_id, "telefone": telefone})["conexoes"] # ------------------------------------------------------------------ mensagens def enviar(self, para: str, tipo: str, *, numero_id: Optional[str] = None, telefone: Optional[str] = None, simular: bool = False, **campos: Any) -> Dict[str, Any]: """Envio genérico (todos os tipos). Ex.: enviar(para, "localizacao", localizacao={...}).""" corpo = {**self._numero(numero_id, telefone), "para": para, "tipo": tipo, "simular": simular, **campos} return self._requisitar("POST", "/api/mensagens/enviar", json_corpo=corpo) def enviar_texto(self, para: str, texto: str, *, preview_url: bool = False, responder_a: Optional[str] = None, **numero: Any) -> Dict[str, Any]: return self.enviar(para, "texto", texto=texto, preview_url=preview_url, responder_a=responder_a, **numero) def enviar_template(self, para: str, nome: str, *, idioma: str = "pt_BR", variaveis: Iterable[str] = (), variaveis_cabecalho: Iterable[str] = (), cabecalho_midia: Optional[Dict[str, Any]] = None, botoes: Optional[List[Dict[str, Any]]] = None, componentes: Optional[List[Dict[str, Any]]] = None, **numero: Any) -> Dict[str, Any]: """cabecalho_midia={"tipo": "imagem", "url": "https://..."}; botoes=[{"indice": 0, "tipo": "url", "valor": "abc"}].""" template: Dict[str, Any] = {"nome": nome, "idioma": idioma, "variaveis": [str(v) for v in variaveis], "variaveis_cabecalho": [str(v) for v in variaveis_cabecalho]} if cabecalho_midia: template["cabecalho_midia"] = cabecalho_midia if botoes: template["botoes"] = botoes if componentes is not None: template["componentes"] = componentes return self.enviar(para, "template", template=template, **numero) def enviar_botoes(self, para: str, texto: str, botoes: List[Any], *, cabecalho: Optional[str] = None, rodape: Optional[str] = None, **numero: Any) -> Dict[str, Any]: """botoes: ["Sim", "Não"] ou [{"id": "sim", "titulo": "Sim"}] (até 3).""" lista = [b if isinstance(b, dict) else {"titulo": str(b)} for b in botoes] return self.enviar(para, "botoes", texto=texto, botoes=lista, cabecalho=cabecalho, rodape=rodape, **numero) def enviar_lista(self, para: str, texto: str, opcoes: List[Any], *, botao: str = "Ver opções", titulo_secao: Optional[str] = None, cabecalho: Optional[str] = None, rodape: Optional[str] = None, **numero: Any) -> Dict[str, Any]: """opcoes: ["Pizza", "Lanche"] ou [{"id": "p1", "titulo": "Pizza", "descricao": "..."}] (até 10).""" linhas = [o if isinstance(o, dict) else {"titulo": str(o)} for o in opcoes] return self.enviar(para, "lista", texto=texto, cabecalho=cabecalho, rodape=rodape, lista={"botao": botao, "secoes": [{"titulo": titulo_secao, "linhas": linhas}]}, **numero) def enviar_midia(self, para: str, url: str, *, tipo: str = "imagem", legenda: Optional[str] = None, nome_arquivo: Optional[str] = None, **numero: Any) -> Dict[str, Any]: """tipo: imagem | video | documento | audio | figurinha. A URL precisa ser pública.""" return self.enviar(para, tipo, midia={"url": url, "legenda": legenda, "nome_arquivo": nome_arquivo}, **numero) def enviar_reacao(self, para: str, mensagem_id: str, emoji: str, **numero: Any) -> Dict[str, Any]: return self.enviar(para, "reacao", mensagem_id=mensagem_id, emoji=emoji, **numero) def marcar_lida(self, mensagem_id: str, *, digitando: bool = False, numero_id: Optional[str] = None, telefone: Optional[str] = None) -> Dict[str, Any]: return self._requisitar("POST", "/api/mensagens/marcar-lida", json_corpo={ **self._numero(numero_id, telefone), "mensagem_id": mensagem_id, "digitando": digitando, }) def baixar_midia(self, media_id: str, *, numero_id: Optional[str] = None, telefone: Optional[str] = None) -> Tuple[bytes, str]: """Arquivo que o cliente mandou (áudio, foto, PDF). Devolve (bytes, content-type).""" params = {"numero_id": numero_id, "telefone": telefone, "baixar": True} conteudo, cabecalhos = self._requisitar("GET", f"/api/midia/{urllib.parse.quote(media_id, safe='')}", params=params, bruto=True) tipo = next((v for k, v in cabecalhos.items() if k.lower() == "content-type"), "application/octet-stream") return conteudo, tipo def historico(self, numero: Optional[str] = None, *, contato: Optional[str] = None, limite: int = 50) -> Dict[str, Any]: """{"mensagens": [...], "janela": {"aberta": bool, "expira_em": ...}} (janela só com contato).""" return self._requisitar("GET", f"/api/numeros/{self._ident(numero)}/mensagens", params={"contato": contato, "limite": limite}) def conversas(self, numero: Optional[str] = None, *, busca: Optional[str] = None) -> List[Dict[str, Any]]: return self._requisitar("GET", f"/api/numeros/{self._ident(numero)}/conversas", params={"busca": busca})["conversas"] # ------------------------------------------------------------------ templates def listar_templates(self, numero: Optional[str] = None, *, so_aprovados: bool = False) -> List[Dict[str, Any]]: templates = self._requisitar("GET", f"/api/numeros/{self._ident(numero)}/templates")["templates"] return [t for t in templates if t["status"] == "APPROVED"] if so_aprovados else templates def criar_template(self, nome: str, corpo: str, *, numero: Optional[str] = None, categoria: str = "UTILITY", idioma: str = "pt_BR", exemplos: Iterable[str] = (), cabecalho: Optional[str] = None, rodape: Optional[str] = None, respostas_rapidas: Iterable[str] = ()) -> Dict[str, Any]: return self._requisitar("POST", f"/api/numeros/{self._ident(numero)}/templates", json_corpo={ "nome": nome, "corpo": corpo, "categoria": categoria, "idioma": idioma, "exemplos": list(exemplos), "cabecalho": cabecalho, "rodape": rodape, "botoes": [{"tipo": "QUICK_REPLY", "texto": t} for t in respostas_rapidas], }) def apagar_template(self, nome: str, *, numero: Optional[str] = None, hsm_id: Optional[str] = None) -> Dict[str, Any]: return self._requisitar("DELETE", f"/api/numeros/{self._ident(numero)}/templates/{nome}", params={"hsm_id": hsm_id}) # ------------------------------------------------------------------ perfil e saúde def perfil(self, numero: Optional[str] = None) -> Dict[str, Any]: return self._requisitar("GET", f"/api/numeros/{self._ident(numero)}/perfil") def atualizar_perfil(self, numero: Optional[str] = None, **campos: Any) -> Dict[str, Any]: """campos: sobre, descricao, endereco, email, sites (lista), categoria (RESTAURANT, RETAIL...).""" return self._requisitar("PATCH", f"/api/numeros/{self._ident(numero)}/perfil", json_corpo=campos) def saude(self, numero: Optional[str] = None, *, sincronizar: bool = False) -> Dict[str, Any]: """Qualidade (GREEN/YELLOW/RED), limite diário, status na Meta, HookCloud e Salvy.""" return self._requisitar("GET", f"/api/numeros/{self._ident(numero)}/saude", params={"sincronizar": sincronizar or None}) # ============================================================================= webhook def verificar_assinatura(segredo: str, corpo: bytes, timestamp: Optional[str], assinatura: Optional[str], tolerancia_seg: int = 300) -> bool: """Confere X-Central-Signature = sha256=HMAC(segredo, "{timestamp}.{corpo}") e o relógio (±5 min).""" if not (segredo and timestamp and assinatura and str(timestamp).isdigit()): return False if abs(time.time() - int(timestamp)) > tolerancia_seg: return False if isinstance(corpo, str): corpo = corpo.encode("utf-8") esperado = "sha256=" + hmac.new(segredo.encode(), str(timestamp).encode() + b"." + corpo, hashlib.sha256).hexdigest() return hmac.compare_digest(assinatura.strip().lower(), esperado) def interpretar_webhook(corpo: Any) -> List[Dict[str, Any]]: """Transforma o corpo recebido da Central numa lista simples de eventos. tipo 'mensagem': {phone_number_id, de, nome, wamid, tipo_mensagem, texto, midia_id, resposta_id, bruto} tipo 'status': {phone_number_id, wamid, status, para, erro, bruto} tipo 'meta': outros eventos da Meta (templates, conta...): {campo, valor} tipo 'evento_admin': aviso do HookCloud: {evento, status, qualidade, limite_mensagens, conexao, dados} """ if isinstance(corpo, (bytes, str)): corpo = json.loads(corpo) if not isinstance(corpo, dict): return [] if corpo.get("object") == "central_whatsapp": conexao = corpo.get("conexao") or {} return [{ "tipo": "evento_admin", "evento": corpo.get("evento"), "status": conexao.get("status"), "status_detalhe": conexao.get("status_detalhe"), "qualidade": conexao.get("qualidade"), "limite_mensagens": conexao.get("limite_mensagens"), "conexao": conexao, "dados": corpo.get("dados"), }] eventos: List[Dict[str, Any]] = [] for entry in corpo.get("entry") or []: for change in entry.get("changes") or []: valor = change.get("value") or {} if change.get("field") != "messages": eventos.append({"tipo": "meta", "campo": change.get("field"), "valor": valor, "waba_id": entry.get("id")}) continue pnid = (valor.get("metadata") or {}).get("phone_number_id") nomes = {c.get("wa_id"): (c.get("profile") or {}).get("name") for c in valor.get("contacts") or []} for m in valor.get("messages") or []: tipo = m.get("type") conteudo = m.get(tipo) if isinstance(m.get(tipo), dict) else {} interativo = m.get("interactive") or {} resposta = interativo.get("button_reply") or interativo.get("list_reply") or {} eventos.append({ "tipo": "mensagem", "phone_number_id": pnid, "de": m.get("from"), "nome": nomes.get(m.get("from")), "wamid": m.get("id"), "tipo_mensagem": tipo, "texto": (m.get("text") or {}).get("body") or conteudo.get("caption") or resposta.get("title") or (m.get("button") or {}).get("text"), "midia_id": conteudo.get("id"), "resposta_id": resposta.get("id") or (m.get("button") or {}).get("payload"), "bruto": m, }) for s in valor.get("statuses") or []: erro = (s.get("errors") or [{}])[0] eventos.append({ "tipo": "status", "phone_number_id": pnid, "wamid": s.get("id"), "status": s.get("status"), "para": s.get("recipient_id"), "erro": erro.get("title") if erro else None, "bruto": s, }) return eventos