Ir para o conteúdo

tempest_fastapi_sdk.integrations.messaging.zap.inbox

A camada de serviço que todo consumidor do zap-api escreve: reivindicar, acompanhar e enviar.

« Integrações e pagamentos


ZapInboundMessageMixin

Bases: _MixinBase

Columns for an inbound zap-api message, stored once.

Mix into a concrete :class:~tempest_fastapi_sdk.BaseModel table::

class ZapMessageModel(ZapInboundMessageMixin, BaseModel):
    __tablename__ = "zap_messages"

For static typing only, the mixin is declared as a BaseModel subclass, so BaseRepository[...] over it type-checks; at runtime it is a plain, unmapped mixin.

text is Text and nullable: a media message without a caption has none, and a WhatsApp text has no 255-character ceiling.

Attributes:

Name Type Description
message_id str

The WhatsApp message id. UNIQUE — it is the claim :meth:ZapInbox.claim relies on.

chat_key str | None

The sender's number, digits only, resolved by the gateway from a LID. None for groups, broadcasts, channels and an unmapped LID — there is no one to answer.

push_name str | None

The sender's display name, when sent.

text str | None

The text or caption, when there is one.

media_type str | None

The :class:~tempest_fastapi_sdk.integrations.messaging.zap.ZapInboundMediaTypeEnum value, when the message carries media.

ZapDeliveryMixin

Bases: _MixinBase

Columns for the last known status of one outbound zap-api message.

Mix into a concrete :class:~tempest_fastapi_sdk.BaseModel table::

class ZapDeliveryModel(ZapDeliveryMixin, BaseModel):
    __tablename__ = "zap_deliveries"

For static typing only, the mixin is declared as a BaseModel subclass; at runtime it is a plain, unmapped mixin.

Attributes:

Name Type Description
outbound_id str

The outbox row id the 202 returned, which is the id every status callback carries. UNIQUE — the key :meth:ZapInbox.track upserts by.

chat_key str

The recipient, digits only.

idempotency_key str | None

The key the send went out with. UNIQUE, so a retry finds the row it already wrote. None on a row a callback created before the send recorded it.

status str

The :class:~tempest_fastapi_sdk.integrations.messaging.zap.AcceptedResponseStatus value, only ever moved forward.

error str | None

Why the send failed, on failed.

ZapInboundOutcomeEnum

Bases: BaseStrEnum

What :meth:ZapInbox.claim did with an inbound message.

Attributes:

Name Type Description
STORED

Stored for the first time.

DUPLICATE

Already stored — a re-delivery of the same messageId.

MEDIA_LOST

Stored, but it announced media and came without mediaUrl: the gateway failed to download it, or it went over MEDIA_MAX_BYTES. WhatsApp does not serve it again.

SKIPPED

Written from a server outside accepted_servers (a group, a broadcast, a channel by default) and not stored.

ZapStatusOutcomeEnum

Bases: BaseStrEnum

What :meth:ZapInbox.track did with a status callback.

Attributes:

Name Type Description
APPLIED

The status advanced the stored one, or created the row.

STALE

The status repeats or steps down what is stored, and was ignored.

ZapWebhookOutcome module-attribute

ZapWebhookOutcome: TypeAlias = (
    ZapInboundOutcomeEnum | ZapStatusOutcomeEnum | Literal["ignored"]
)

Outcome reported by a webhook endpoint handling a zap-api delivery.

ZapInboundMessageResponseSchema

Bases: BaseResponseSchema

Response schema mirroring :class:ZapInboundMessageMixin.

Validates directly from an ORM model mixing in :class:ZapInboundMessageMixin and :class:~tempest_fastapi_sdk.BaseModel via ZapInboundMessageResponseSchema.model_validate(row).

text uses :data:~tempest_fastapi_sdk.RawTextField so leading or trailing whitespace typed by the sender is preserved on serialization.

Attributes:

Name Type Description
message_id str

The WhatsApp message id.

chat_key str | None

The sender's resolved phone digits, or None when the gateway could not map the sender.

push_name str | None

The sender's display name, when sent.

text str | None

The message text or media caption, when present.

media_type str | None

The media category (a :class:~tempest_fastapi_sdk.integrations.messaging.zap.ZapInboundMediaTypeEnum value), or None for plain text.

ZapDeliveryResponseSchema

Bases: BaseResponseSchema

Response schema mirroring :class:ZapDeliveryMixin.

Validates directly from an ORM model mixing in :class:ZapDeliveryMixin and :class:~tempest_fastapi_sdk.BaseModel via ZapDeliveryResponseSchema.model_validate(row).

Attributes:

Name Type Description
outbound_id str

The gateway outbox row id returned by 202 and carried by status callbacks.

chat_key str

The recipient's phone digits.

idempotency_key str | None

The idempotency key sent on the request, or None when a status callback created the row first.

status str

The last known :class:~tempest_fastapi_sdk.integrations.messaging.zap.AcceptedResponseStatus value.

error str | None

Failure reason reported on failed callbacks.

ZapWebhookResponseSchema

Bases: BaseSchema

Standard 200 response payload for a zap-api webhook endpoint.

Returned by routes wired around :class:ZapInbox to report what happened to a verified delivery without triggering gateway retries (any 2xx stops retries). status carries the :meth:ZapInbox.claim or :meth:ZapInbox.track outcome, or "ignored" when the delivery event is not handled; event optionally echoes :attr:ZapWebhookDelivery.event_name for logs and tests.

Attributes:

Name Type Description
status ZapWebhookOutcome

stored, duplicate, media-lost, skipped, applied, stale or ignored.

event str | None

The raw event name carried by the delivery, when echoed by the route.

ZapInbox

ZapInbox(
    messages: BaseRepository[InboundT],
    deliveries: BaseRepository[DeliveryT],
    client: ZapClient,
    *,
    accepted_servers: frozenset[ZapJidServerEnum] = DEFAULT_ACCEPTED_SERVERS,
)

Bases: Generic[InboundT, DeliveryT]

Store inbound messages once, track delivery status, record sends.

Build one per request, over repositories bound to the request's session and the :class:ZapClient the lifespan opened. Deciding whether to answer a message stays with the consumer: claim only says what happened to it.

Bind the inbox to its tables and to the gateway.

Parameters:

Name Type Description Default
messages BaseRepository[InboundT]

Repository over the table mixing in :class:ZapInboundMessageMixin.

required
deliveries BaseRepository[DeliveryT]

Repository over the table mixing in :class:ZapDeliveryMixin.

required
client ZapClient

The gateway client.

required
accepted_servers frozenset[ZapJidServerEnum]

The address kinds :meth:claim stores. Defaults to a person writing by number or by LID.

DEFAULT_ACCEPTED_SERVERS

claim async

Store an inbound message once, and say what happened to it.

No exists check precedes the insert: two replicas checking at the same time would both see nothing and both store. The UNIQUE on message_id decides, and the loser gets duplicate. A conflict whose message_id is not stored is not a duplicate (another constraint on the consumer's table refused the row), so it propagates.

The media is not downloaded here: it stays on the gateway, and client.get_message_media(message.message_id) reads it when the consumer needs the bytes. chat_key is stored even when None.

Parameters:

Name Type Description Default
message ZapInboundMessage

The verified inbound body.

required

Returns:

Name Type Description
ZapInboundOutcomeEnum ZapInboundOutcomeEnum

stored, duplicate, media-lost or

ZapInboundOutcomeEnum

skipped.

Raises:

Type Description
AppException

The repository's conflict exception, when the insert broke a constraint other than the claim.

track async

Apply a status callback when it advances the stored status.

Upserts by callback.id. A callback for an id with no row creates it: the gateway can call back before the consumer committed the send, and a 404 would only spend the gateway's retries. Two callbacks racing to create the same row collide on the UNIQUE; the loser re-reads the row and applies the ladder against it.

Parameters:

Name Type Description Default
callback ZapStatusCallback

The verified status body.

required

Returns:

Name Type Description
ZapStatusOutcomeEnum ZapStatusOutcomeEnum

applied or stale.

Raises:

Type Description
AppException

The repository's conflict exception, when the insert broke a constraint other than outbound_id.

send_text async

send_text(
    to: str, text: str, *, idempotency_key: str, reply_to: str | None = None
) -> AcceptedResponse

Send a text and record its delivery row, once per key.

Reuse the same idempotency_key when retrying the same message: the gateway answers the original row with deduped=True, and the row found by the key here is updated instead of duplicated. When :meth:track already created the row from a callback, the send attaches its key and never steps the status down.

A gateway running without persistence sends inline and answers 202 with id and status null; the row is then keyed by idempotency_key and starts at sent, because the message already left, and no callback will ever move it.

Parameters:

Name Type Description Default
to str

The recipient, digits only (chat_key, not from_).

required
text str

The message.

required
idempotency_key str

Fresh per message, reused on retry.

required
reply_to str | None

The messageId being quoted.

None

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The gateway's 202.

Raises:

Type Description
ZapSendFailedException

When the 202 already says failed — a reused key whose send failed before. Nothing is recorded.

HTTPStatusError

For a non-2xx answer from the gateway.

send_reply async

send_reply(
    chat_key: str, message_id: str, text: str, *, key_prefix: str = "reply_"
) -> AcceptedResponse

Send an idempotent reply quoting message_id and record its delivery.

Computes idempotency_key=f"{key_prefix}{message_id}" and sets reply_to=message_id before delegating to :meth:send_text. Rejects a raw WhatsApp JID containing "@" (such as @lid or @s.whatsapp.net) or empty identifiers with :class:ValueError before reaching the gateway.

Parameters:

Name Type Description Default
chat_key str

The recipient's resolved phone digits (message.chat_key, never the raw from_ JID).

required
message_id str

The WhatsApp messageId being replied to.

required
text str

The reply text.

required
key_prefix str

Prefix prepended to message_id to build the idempotency key. Defaults to "reply_".

'reply_'

Returns:

Name Type Description
AcceptedResponse AcceptedResponse

The gateway's 202 response.

Raises:

Type Description
ValueError

When chat_key is empty or contains "@", or when message_id is empty.

ZapSendFailedException

When the 202 already reports failed for the computed idempotency key.

HTTPStatusError

For a non-2xx answer from the gateway.

get_message_media async

get_message_media(message_id: str) -> bytes

Fetch the stored media bytes of an inbound message from the gateway.

Convenience facade over :meth:ZapClient.get_message_media so a service holding only a :class:ZapInbox does not reach into inbox.client directly.

Parameters:

Name Type Description Default
message_id str

The WhatsApp message id (messageId in the inbound webhook).

required

Returns:

Name Type Description
bytes bytes

The raw media bytes returned by the gateway.

Raises:

Type Description
HTTPStatusError

When the gateway answers non-2xx (for example 404 when the media was lost or expired).

is_replyable

is_replyable(
    outcome: ZapInboundOutcomeEnum,
    message: ZapInboundMessage,
    *,
    require_text: bool = True,
) -> bool

Decide whether a claimed inbound message can be answered.

A message is replyable when :meth:ZapInbox.claim stored it for the first time (outcome in :data:REPLYABLE_OUTCOMES), the gateway resolved a recipient key (message.chat_key is not None — an unresolved @lid arrives with chat_key=None), and, unless require_text is False, the message carries non-empty text or caption.

Parameters:

Name Type Description Default
outcome ZapInboundOutcomeEnum

The outcome returned by :meth:ZapInbox.claim.

required
message ZapInboundMessage

The verified inbound webhook body.

required
require_text bool

Require message.text to be non-empty. Pass False for handlers that also reply to media without a caption (such as voice notes or images).

True

Returns:

Name Type Description
bool bool

True when the message satisfies every replyability check.

DEFAULT_ACCEPTED_SERVERS module-attribute

DEFAULT_ACCEPTED_SERVERS: frozenset[ZapJidServerEnum] = frozenset(
    {ZapJidServerEnum.USER, ZapJidServerEnum.LID}
)

The servers a one-to-one conversation is written from.

REPLYABLE_OUTCOMES module-attribute

REPLYABLE_OUTCOMES: frozenset[ZapInboundOutcomeEnum] = frozenset(
    {ZapInboundOutcomeEnum.STORED, ZapInboundOutcomeEnum.MEDIA_LOST}
)

Claim outcomes for a newly stored inbound message that can receive a reply.

InboundT module-attribute

InboundT = TypeVar('InboundT', bound=ZapInboundMessageMixin)

The consumer's inbound message model.

DeliveryT module-attribute

DeliveryT = TypeVar('DeliveryT', bound=ZapDeliveryMixin)

The consumer's delivery model.