Pydantic v2 models for the WhatsApp Business API — outgoing messages, incoming webhooks, and template management.
Project description
whatsapp-models
Biblioteca Python de modelos de dados (Pydantic v2) para as APIs do WhatsApp Business da Meta.
Instalação
pip install whatsapp-models
# ou com uv
uv add whatsapp-models
Módulos
| Módulo | Descrição |
|---|---|
messages |
Modelos de envio (POST /messages) |
message_templates |
Criação e envio de templates |
webhooks |
Payloads recebidos via webhook |
phone_numbers |
Gerenciamento de números |
media |
Upload e referência de mídia |
Exemplos
Envio de mensagens
Mensagem de texto
from whatsapp_models import TextMessage
msg = TextMessage(to="+5511999999999", text={"body": "Olá!"})
payload = msg.model_dump()
# POST /messages — body: payload
Mensagem de mídia (imagem, vídeo, documento, áudio, sticker)
from whatsapp_models import ImageMessage, DocumentMessage
# Por ID de mídia previamente enviada
image = ImageMessage(to="+5511999999999", image={"id": "media_id_abc", "caption": "Foto do evento"})
# Por URL hospedada
doc = DocumentMessage(
to="+5511999999999",
document={"link": "https://example.com/relatorio.pdf", "filename": "relatorio.pdf"},
)
Mensagem interativa — botões de resposta rápida
from whatsapp_models import InteractiveMessage
msg = InteractiveMessage(
to="+5511999999999",
interactive={
"type": "button",
"body": {"text": "Confirme sua presença:"},
"action": {
"buttons": [
{"type": "reply", "reply": {"id": "sim", "title": "Sim"}},
{"type": "reply", "reply": {"id": "nao", "title": "Não"}},
]
},
},
)
Mensagem interativa — lista
from whatsapp_models import InteractiveMessage
msg = InteractiveMessage(
to="+5511999999999",
interactive={
"type": "list",
"body": {"text": "Escolha um departamento:"},
"action": {
"button": "Ver opções",
"sections": [
{
"title": "Suporte",
"rows": [
{"id": "tecnico", "title": "Suporte Técnico"},
{"id": "financeiro", "title": "Financeiro"},
],
}
],
},
},
)
Mensagem via template
from whatsapp_models import TemplateMessage
msg = TemplateMessage(
to="+5511999999999",
template={
"name": "hello_world",
"language": {"code": "pt_BR"},
"components": [
{
"type": "body",
"parameters": [{"type": "text", "text": "João"}],
}
],
},
)
Discriminated union — OutgoingMessage
Útil para serializar ou deserializar qualquer mensagem de saída pelo campo type:
from pydantic import TypeAdapter
from whatsapp_models import OutgoingMessage
adapter = TypeAdapter(OutgoingMessage)
msg = adapter.validate_python({
"to": "+5511999999999",
"type": "text",
"text": {"body": "Olá!"},
})
# msg é uma instância de TextMessage
Templates
Criação de template
from whatsapp_models import (
CreateTemplateRequest,
TemplateCategory,
HeaderComponent,
BodyComponent,
FooterComponent,
HeaderFormat,
)
request = CreateTemplateRequest(
name="confirmacao_pedido",
language="pt_BR",
category=TemplateCategory.UTILITY,
components=[
HeaderComponent(format=HeaderFormat.TEXT, text="Pedido confirmado"),
BodyComponent(text="Olá {{1}}, seu pedido #{{2}} foi confirmado."),
FooterComponent(text="Dúvidas? Fale conosco."),
],
)
Webhooks
Deserializar notificação recebida
from whatsapp_models import WebhookNotification
payload = { ... } # dict recebido no endpoint
notification = WebhookNotification.model_validate(payload)
for entry in notification.entry:
for change in entry.changes:
for message in change.value.messages:
print(type(message).__name__, message.type)
Mensagem direta — text
from whatsapp_models.webhooks.messages import IncomingTextMessage
if isinstance(message, IncomingTextMessage):
print(message.from_, message.text.body)
Mensagem de grupo
Mensagens de grupo possuem group_id no payload e são resolvidas automaticamente para o tipo IncomingGroup* correspondente:
from whatsapp_models.webhooks.messages import IncomingGroupTextMessage
if isinstance(message, IncomingGroupTextMessage):
print(f"Grupo {message.group_id}: {message.text.body}")
Status de entrega
from whatsapp_models.webhooks.statuses import DeliveryStatus
for status in change.value.statuses:
if status.status == DeliveryStatus.failed:
print(f"Falha ao entregar {status.id}: {status.errors}")
Números de telefone
from whatsapp_models import PhoneNumber, QualityRating
pn = PhoneNumber(
id="pn_id_1",
display_phone_number="+55 11 99999-9999",
verified_name="Minha Empresa",
quality_rating=QualityRating.GREEN,
)
Mídia
from whatsapp_models import MediaObject
# Referência por ID (após upload)
ref = MediaObject(id="media_id_abc")
# Referência por URL
ref = MediaObject(link="https://example.com/audio.ogg", filename="audio.ogg")
Convenções
- Todos os modelos herdam de
pydantic.BaseModelcomvalidate_by_name=Trueevalidate_by_alias=True - Campos opcionais usam
field: Type | None = None - Enums usam
StrEnum— serializam como string pura - Discriminated unions usam
Field(discriminator="type")para parse direto sem tentativa e erro
Desenvolvimento
uv sync
uv run pytest
uv run ruff check . && uv run ruff format .
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file whatsapp_models-0.1.0.tar.gz.
File metadata
- Download URL: whatsapp_models-0.1.0.tar.gz
- Upload date:
- Size: 20.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
74976ba3629004d7540825bc11ffc5bdfcb727f0543897f9dd9b79b848d4eaf4
|
|
| MD5 |
aae5978b8e790d55f64083a36234b057
|
|
| BLAKE2b-256 |
566e4317f62ad5333ea9a07b1df7f7bd30ffbcf0e80f784fe482db571be7a3ab
|
Provenance
The following attestation bundles were made for whatsapp_models-0.1.0.tar.gz:
Publisher:
release.yml on gabrielbchaves/whatsapp-models
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
whatsapp_models-0.1.0.tar.gz -
Subject digest:
74976ba3629004d7540825bc11ffc5bdfcb727f0543897f9dd9b79b848d4eaf4 - Sigstore transparency entry: 1287935613
- Sigstore integration time:
-
Permalink:
gabrielbchaves/whatsapp-models@00650e4e79eed950b71d971bc93c8cea6f3d498d -
Branch / Tag:
refs/tags/v0.0.1 - Owner: https://github.com/gabrielbchaves
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@00650e4e79eed950b71d971bc93c8cea6f3d498d -
Trigger Event:
push
-
Statement type:
File details
Details for the file whatsapp_models-0.1.0-py3-none-any.whl.
File metadata
- Download URL: whatsapp_models-0.1.0-py3-none-any.whl
- Upload date:
- Size: 33.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d6a795a7ce418721d1bd03842829ae06f409fee5573bed70de967df43fbb5389
|
|
| MD5 |
ce40f88a4ec85c45c253b494e53625f6
|
|
| BLAKE2b-256 |
a9eb64864c0059e1aa8b2ed14b6bd7b1948caaebe80838d5933de22b6477bf46
|
Provenance
The following attestation bundles were made for whatsapp_models-0.1.0-py3-none-any.whl:
Publisher:
release.yml on gabrielbchaves/whatsapp-models
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
whatsapp_models-0.1.0-py3-none-any.whl -
Subject digest:
d6a795a7ce418721d1bd03842829ae06f409fee5573bed70de967df43fbb5389 - Sigstore transparency entry: 1287935693
- Sigstore integration time:
-
Permalink:
gabrielbchaves/whatsapp-models@00650e4e79eed950b71d971bc93c8cea6f3d498d -
Branch / Tag:
refs/tags/v0.0.1 - Owner: https://github.com/gabrielbchaves
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@00650e4e79eed950b71d971bc93c8cea6f3d498d -
Trigger Event:
push
-
Statement type: