Skip to main content

pilot-status (Python SDK)

Official Python SDK for the Pilot Status public API.

Installation

pip install pilot-status

Quickstart

Create an API key in the dashboard and use it only on the backend.

import os

from pilot_status import PilotStatusClient

client = PilotStatusClient(
    api_key=os.environ["PILOT_STATUS_API_KEY"],
)

accepted = client.messages.send(
    {
        "templateId": "onboarding-test",
        "destinationNumber": "+5511999999999",
        "variables": {"name": "John"},
    }
)

message = client.messages.get(accepted["id"])
print(message["status"])

Account-wide keys and the target number (whatsapp_number_id)

Per-number endpoints (referrals, leads, messages.history, ...) act on the number a number-scoped key is bound to. With an account-wide (tenant) key, name the number: it goes out as the x-whatsapp-number-id header.

client = PilotStatusClient(api_key=TENANT_KEY, whatsapp_number_id="wn_1")
client.referrals.list()                       # number wn_1
client.with_number("wn_2").referrals.list()   # one call on another number

with_number returns a new client and leaves the original untouched. Without a number, an account-wide key gets 403 TENANT_SCOPE_NOT_ALLOWED on those endpoints; on ads.summary() and lead_pages it sees the whole workspace. A number-scoped key ignores the header.

Replying without marking the chat read (markRead)

By default a send on a Meta Cloud API number shows the "typing" indicator and marks the contact's last inbound message read (blue ticks). Pass "markRead": False to skip both — e.g. an AI agent answers and a human still sees the conversation as unread later. Meta only allows "typing" as part of a read receipt, so the two cannot be separated. Omit the key to use the number's markReadOnSend setting (default True).

client.messages.send(
    {"destinationNumber": "+5511999999999", "text": "On it!", "markRead": False}
)

No effect on Evolution (unofficial) numbers: sending never marks read there, and read-on-arrival is the number's readMessages setting (turn it off for this use case). Note that POST /v1/messages/typing on a Meta number also marks read.

Safe retries (idempotency_key)

Pass idempotency_key= to send it as the Idempotency-Key header (never in the body; up to 255 chars, no control characters). REUSE THE SAME KEY when retrying after a timeout or network error: within 24 hours (per workspace + number + key) the server returns the first accepted response instead of sending again (Idempotent-Replayed: true).

client.messages.send(
    {"destinationNumber": "+5511999999999", "text": "Your order #42 has shipped"},
    idempotency_key="order-42-shipped",
)

Same key with a different body: 409 IDEMPOTENCY_KEY_REUSED. First call still running: 409 IDEMPOTENCY_KEY_IN_USE. Invalid key: 400 IDEMPOTENCY_KEY_INVALID. Only 2xx responses are remembered, so after an error you can fix the request and retry with the same key. Without the key nothing changes.

User-Agent

Every request carries User-Agent: pilot-status-python/<version> (e.g. pilot-status-python/1.20.0; the version is pilot_status.__version__). Your own user_agent= is kept and goes after it: user_agent="my-app/1.0" sends pilot-status-python/1.20.0 my-app/1.0.

Management (projects, API keys, numbers)

These endpoints create resources within the scope (project + environment) of the current api_key.

Projects

project = client.projects.create(
    {
        "name": "My Project",
        "description": "Optional description",
    }
)

projects = client.projects.list()

API keys

# Regenerate the default key of one number (tenant-scoped). The new usable key
# is returned once — there is no "create another key" concept.
regenerated = client.api_keys.regenerate_number("wn_1")
print(regenerated["key"])  # shown only once

keys = client.api_keys.list()
# With a number-scoped key this returns that number's masked keys (`ApiKeyListItem[]`).
# With a tenant-scoped key it returns a lean per-number list (`NumberApiKeyReveal[]`):
# { numberId, number, displayName, keyId, keyLast4, key, revealable } — `key` is the real usable value when `revealable` is true.

Message history

# Conversation history (both directions, every provider), newest first.
# This is how you read old messages — the webhook does not replay history.
page = client.messages.history(
    start_date="2026-07-01T00:00:00Z",
    end_date="2026-07-31T23:59:59Z",
    page_size=100,
)
print(page["total"], page["messages"][0]["providerTimestamp"])
# Number-scoped key required. Rows outside the PII window come back with
# content/media/peer nulled and "redacted": True — the envelope is kept.

Leads (Meta Lead Ads)

# Leads from Facebook / Instagram Instant Forms of the Pages linked to the key's
# number, newest first by when the person submitted the form.
page = client.leads.list(
    form_id="1234567890",          # also: ad_id=, page_id=
    start_date="2026-10-01T00:00:00Z",
    end_date="2026-10-31T23:59:59Z",
    page_size=100,
)
for lead in page["leads"]:
    print(lead["leadgenId"], lead["fullName"], lead["consentGiven"])

one = client.leads.get(page["leads"][0]["id"])["lead"]
# Number-scoped key required (`chat:read`). `consentGiven` is True / False / None —
# None means unknown, never a refusal. A lead hidden by the number's PII policy comes
# back with "redacted": True, name/e-mail/phone None and `fields` empty; ids and ad
# attribution are kept. `notice` is set when the number is RELAY_ONLY.

Referrals (Click-to-WhatsApp ads)

# Inbound messages that arrived from a Meta ad or post, newest first. Each row is the
# FIRST inbound of a conversation started by that ad (Meta never repeats the referral).
page = client.referrals.list(
    source_type="ad",              # also: source_id=, start_date=, end_date=, page=
    page_size=100,
)
for row in page["referrals"]:
    ref = row["referral"]
    print(ref["sourceId"], ref["campaignName"], ref["namesResolvedAt"])

summary = client.referrals.summary(start_date="2026-10-01T00:00:00Z")
for ad in summary["ads"]:
    print(ad["sourceId"], ad["conversations"], ad["messages"])
# `conversations` counts DISTINCT conversations (the lead count). Capped at 200 ads:
# `truncated` True means a PARTIAL answer -- narrow start_date/end_date.
# Acts on ONE number (`chat:read`): a number-scoped key, or an account-wide key with
# `PilotStatusClient(..., whatsapp_number_id="wn_1")` / `client.with_number("wn_1")`
# (sent as `x-whatsapp-number-id`); without it -> 403 TENANT_SCOPE_NOT_ALLOWED.
# `sourceId` is the stable ad id; campaign/adset/ad names are filled only when the
# advertiser shared the ad account with Pilot Status (see `namesResolvedAt`).

Ads configuration (Meta ad accounts, ads volume)

# Ad accounts connected to the workspace, so campaign / ad set / ad names resolve.
# Account-wide key with `integrations:manage`. The advertiser grants access by adding
# `partnerBusinessId` as a PARTNER (ads_read) of the ad account in Meta Business Manager.
accounts = client.ads.list_accounts()      # linked, candidates, partnerBusinessId, sharingLookup
client.ads.link_account("act_1234567890")  # 409 AD_ACCOUNT_NOT_PROVEN / AD_ACCOUNT_NOT_SHARED
client.ads.unlink_account("act_1234567890")

# Click-to-WhatsApp volume per ad with names and `leadCount` (`analytics:read`).
# Workspace-wide on an account-wide key without a number; `whatsapp_number_id=` narrows.
report = client.ads.summary(start_date="2026-10-01T00:00:00Z")

Lead Ads Pages and forms

# `integrations:manage`. A credential bound to one number sees only its links.
pages = client.lead_pages.list()
link = client.lead_pages.link("1234567890", whatsapp_number_id="wn_1")["link"]
client.lead_pages.update(link["pageLinkId"], whatsapp_number_id="wn_2")  # -> autoSendDisabled
client.lead_pages.resync(link["pageLinkId"])  # 202; 429 RESYNC_COOLDOWN carries retryAfterSeconds

forms = client.lead_pages.list_forms(link["pageLinkId"])
client.lead_pages.update_form(
    link["pageLinkId"],
    forms["forms"][0]["formId"],
    {
        "consentDisclaimerKey": None,
        "autoSendEnabled": True,      # new leads get a WhatsApp message without a human
        "templateId": None,           # official numbers: an APPROVED template id
        "freeText": "Hi {{full_name}}!",  # other numbers: free text
        "variableMap": {"full_name": {"source": "field", "key": "full_name"}},
    },
)

# WARNING: unlink ERASES every lead captured through the Page and its form configs.
client.lead_pages.unlink(link["pageLinkId"])  # -> deletedLeads

Numbers (WhatsApp)

all_numbers = client.numbers.list()
# JSON array: id, instanceName, primaryLink/secondaryLink, apiKeys refs — no upstream tokens

created = client.numbers.create(
    {
        "name": "My WhatsApp",
        "number": "+5511999999999",
    }
)
# created["numberId"] — the NUMBER id (GET /v1/numbers "id", webhooks' data.numberId), not instance.id
# created["qrcodeBase64"], created["pairingCode"] (letter code or None)

refreshed = client.numbers.connect(created["instance"]["id"])
# refreshed["qrcodeBase64"], refreshed["pairingCode"]

status = client.numbers.get_status(created["instance"]["id"])
print(status["state"])
# status["stale"] is False for a live reading (with "checkedAt") and True when
# the provider did not answer and this is the last remembered state (with
# "lastKnownAt"). A 503 raises with body["code"]: PROVIDER_NOT_CONFIGURED is
# permanent (stop polling), UPSTREAM_TIMEOUT / UPSTREAM_ERROR are worth retrying.

detail = client.numbers.get(created["instance"]["id"])
print(detail["settings"]["appliesTo"]["advanced"])  # "evolution-go" | "none"

Per-number settings

numbers.update() is a PARTIAL patch: retention policy and/or the settings block. There is no POST /v1/numbers/{id}/settings, and Evolution's syncFullHistory has no equivalent here.

# stop replaying the device's old messages into the webhook on every reconnect
client.numbers.update_settings(number_id, {"webhookHistoricalMessages": False})

# stop WhatsApp Channel (@newsletter) posts from becoming conversations,
# stored messages and webhook deliveries
client.numbers.update_settings(number_id, {"ignoreNewsletters": True})

# Meta numbers: send without "typing" and without marking the chat read, unless
# a send passes "markRead": True
client.numbers.update_settings(number_id, {"markReadOnSend": False})

client.numbers.update(
    number_id,
    {
        "piiMode": "STORE_X_DAYS",
        "piiRetentionDays": 30,
        "settings": {"rejectCall": True, "msgRejectCall": "I don't take calls here"},
    },
)

historyImportEnabled, webhookHistoricalMessages and ignoreNewsletters apply to every provider. ignoreNewsletters is where a WhatsApp Channel post is refused: the provider exposes no @newsletter gate (unlike ignoreGroups, which it applies itself), so the post always arrives and is dropped on our side — before the conversation, the stored message and the webhook. On a Meta number channels never arrive at all. The other six are the Evolution GO advancedSettings, in the GO dialect (ignoreGroups, not the v2 groupsIgnore); passing None resets one to the provider default. On a Meta number they are stored but never applied — that is what settings["appliesTo"]["advanced"] == "none" means.

markReadOnSend (default True) is the default of the per-send markRead flag and only takes effect on Meta Cloud API numbers; it can also be set at creation ("settings": {"markReadOnSend": False} in numbers.create()).

They are also pushed to the number's connected instances, reported in settingsSync ({applied, failed, skipped}). Best-effort: a disconnected instance keeps the persisted value and picks it up on its next provisioning.

Deleting, restoring and purging

delete() is a 30-day soft delete: the device is logged out right away and the number is kept until restorableUntil, then purged for good. purge() is the permanent delete — immediate and irreversible (history, chats, templates and the number's API keys go with it).

removed = client.numbers.delete(number_id)
print(removed["restorableUntil"])  # ISO-8601 deadline for restore()

client.numbers.restore(number_id)  # gives back the number, NOT the connection:
client.numbers.connect(number_id)  # pair again after restoring

# Delete-and-recreate the SAME phone: create() answers 409 NUMBER_SOFT_DELETED
# while the number is in the window, so purge it first.
client.numbers.delete(number_id)
client.numbers.purge(number_id)

Purging saves nothing compared to delete(): on Pay As You Go a deleted number is already out of the next cycle's charge, and on the other plans paid capacity only drops through a scheduled reduction of extra numbers. Use a tenant-scoped key — a key bound to the deleted number stops authenticating once the number is deleted.

Paying the extra-number charge of a number

A number past the workspace's paid capacity (an extra number) is charged when it first connects. If that charge is refused, the number stays connected but sending from it is blocked — messages.send() raises a 409 NUMBER_BLOCKED with reason: "extra_charge_unpaid" — until the charge is paid. Both numbers.list() and numbers.get(id) say so at the top level of each number:

  • extraChargeUnpaidSince — ISO timestamp of the block; None when the number is not blocked.
  • extraChargeDisconnectAt — ISO timestamp at which the number is disconnected if it stays unpaid (7 days after the block). Always None on a Meta Cloud API number, which is never disconnected for this.

numbers.pay(id) is "pay now" (POST /v1/numbers/{id}/pay, no body). With a card on file it charges it. It needs a tenant-scoped API key with the billing:manage permission. A wallet top-up or a newly saved card also retries the charge on its own, without this call.

from pilot_status import PilotStatusHttpError

blocked = [n for n in client.numbers.list() if n["extraChargeUnpaidSince"] is not None]

for n in blocked:
    try:
        result = client.numbers.pay(n["id"])
        # "paid": charged, the number can send again.
        # "not_required": nothing was owed for it — safe to call again.
        print(n["id"], result["status"])
    except PilotStatusHttpError as e:
        # 402 has no exception class of its own: branch on the status and on body["code"].
        code = e.body.get("code") if isinstance(e.body, dict) else None
        if e.status == 402 and code == "PAYMENT_FAILED":
            # The card was refused. declineCode is the issuer's reason, when it gave one.
            print(e.body.get("declineCode"), e.body.get("proratedTotal"), e.body.get("currency"))
        elif e.status == 402 and code == "INSUFFICIENT_FUNDS":
            pass  # no credits and no usable card: add credits or a card, then pay again
        elif e.status == 409 and code == "PAYMENT_IN_PROGRESS":
            pass  # another payment of this workspace is running: call again in a few seconds
        elif e.status == 502 and code == "PAYMENT_PROVIDER_ERROR":
            pass  # not a refusal: the charge could not be concluded and the server retries it
        else:
            raise  # 404 NUMBER_NOT_FOUND, 403 NUMBER_SCOPE_NOT_ALLOWED / PERMISSION_DENIED
Status body["code"] Raised as Meaning
402 PAYMENT_FAILED PilotStatusHttpError Charge refused. May carry declineCode, proratedTotal, currency.
402 INSUFFICIENT_FUNDS PilotStatusHttpError No credits and no usable card.
502 PAYMENT_PROVIDER_ERROR ServerError The charge could not be concluded; the server retries it.
409 PAYMENT_IN_PROGRESS ConflictError Another payment of the workspace is running.
404 NUMBER_NOT_FOUND NotFoundError No such number in this workspace.
403 NUMBER_SCOPE_NOT_ALLOWED / PERMISSION_DENIED ForbiddenError Key is not tenant-scoped, or lacks billing:manage.

Every class above is a PilotStatusHttpError, so the single except catches them all. The SDK never retries a POST on its own, so pay() sends exactly one request. The body shape is typed as NumberPayErrorBody, the result as NumberPayResult.

Template insights

# Meta's analytics for one template (days: 7 | 30 | 90, default 30). Not available on
# WhatsApp Business App / coexistence numbers (422 TEMPLATE_INSIGHTS_UNAVAILABLE_SMB).
stats = client.templates.insights("tpl_1", days=7)
print(stats["totals"]["read"], stats["readRate"], stats["clicks"])

Templates: submit, sync, delete preview

Number-scoped credential (a number key, or a tenant key with whatsapp_number_id) on a Meta Cloud API number, templates:manage.

# Submit (or re-submit) to Meta for approval on the number's WABA — no body sent.
tpl = client.templates.submit("tpl_1")
print(tpl["metaTemplateId"], tpl["metaStatus"])   # usually "PENDING"; sendable once APPROVED

# Mirror the WABA's catalogue from Meta now.
from pilot_status import RateLimitError
try:
    print(client.templates.sync())                # {"created": 2, "updated": 5}
except RateLimitError as err:                     # 429 TEMPLATE_SYNC_IN_PROGRESS
    retry_after = {k.lower(): v for k, v in err.headers.items()}.get("retry-after")

# What a delete WOULD do (DELETE ?dry_run=true) — changes nothing. Keys are snake_case.
preview = client.templates.delete_preview("tpl_1")
preview["action"]       # "DELETE_ON_META_AND_LOCAL" | "DELETE_LOCAL_ONLY"
preview["warnings"]

⚠️ Meta deletes templates by name: every language version of that name on the WABA goes, and Meta blocks reusing the name for about 30 days. via_number is None on a Meta template when the real delete would be refused (409 META_TEMPLATE_DELETE_REFUSED).

Stories (WhatsApp status)

Number-scoped key, Evolution Go numbers only (Meta numbers get 400 NOT_SUPPORTED_FOR_META).

story = client.stories.create(
    {
        "type": "text",
        "text": "Sale today!",
        "backgroundColor": "#25D366",
        "textColor": "#FFFFFF",
        "font": "calistoga",  # system, system_text, script, system_bold, morningbreeze, calistoga, exo2, courier
        "recipients": ["5511999999999"],  # up to 5000; omit to follow the device's status privacy
    },
    idempotency_key="promo-2026-11-10",  # optional, sent as the Idempotency-Key header
)
# {"id": "...", "status": "QUEUED", "type": "text", "recipients": "explicit"}

# text: 1–700 chars. Media only by mediaUrl (https). Outcome reaches your webhook as
# message.sent / message.failed with type "story".
client.stories.create({"type": "image", "mediaUrl": "https://example.com/a.jpg", "caption": "New!"})

details = client.stories.get(story["id"])  # recipients is None while QUEUED or when redacted
client.stories.delete(story["id"])          # {"id", "revokedAt"}; 409 STORY_NOT_REVOCABLE, 410 STORY_EXPIRED

Analytics

stats = client.analytics.get_dashboard_stats(tz="America/Sao_Paulo")
print(stats["totalSent"], stats["failureRate"])

Calls (WhatsApp Business Calling)

Voice calls over the /v1/calls* endpoints, on two kinds of numbers:

  • Meta Cloud API numbers — signaling-only: initiate/accept carry the SDP (RFC 8866) produced by your WebRTC client, and audio flows directly between the client and WhatsApp. Settings/permissions/pre_accept are Meta-only.
  • Web (Pilot Status / unofficial) numbers — call media is handled server-side, so there is no SDP (omit sdp on initiate/accept). No call permission is required before initiate and there is no Meta per-minute billing. Extra media controls: play (stream an audio file into the call) and realtime_session (full-duplex PCM16 WebSocket).

Numbers on any other provider get 400 FEATURE_NOT_SUPPORTED. call_id arguments accept the Pilot Status id (call_...) or the provider call id (Meta wacid... / Evolution GO CallID).

Billing: on Meta numbers, business-initiated calls (BIC) are billed by Meta directly on your WABA — per minute, in 6-second pulses, only when answered; user-initiated calls (UIC) are free. Calls on web numbers have no Meta billing at all. Pilot Status does not charge for calls.

Web numbers are unofficial (QR-paired) WhatsApp sessions — call quality and availability depend on the paired device/session, and heavy automated calling carries the usual unofficial-number ban risk.

# 1. Permission first (required before calling a user)
perm = client.calls.get_permissions("+5511999999999")
if perm["permission"]["status"] == "no_permission":
    client.calls.request_permission("+5511999999999", text="May we call you?")
    # the user's reply arrives as the call.permission_updated webhook

# 2. Start a business-initiated call (sdp = offer from your WebRTC client)
call = client.calls.initiate({"to": "+5511999999999", "sdp": offer_sdp})

# 3. Answer an inbound call (after the call.ringing webhook)
inbound = client.calls.get("wacid.ABGG...", include_sdp=True)
# feed inbound["sdpOffer"] to your WebRTC client, produce the answer, then:
client.calls.accept(inbound["id"], answer_sdp)

# Other controls
client.calls.reject("wacid.ABGG...")
client.calls.terminate("wacid.ABGG...")

# History + settings (settings are Meta-only)
calls = client.calls.list(limit=25)["calls"]
settings = client.calls.get_settings()
client.calls.update_settings({"status": "ENABLED"})

On a web (Pilot Status) number the same flow needs no SDP and no permission step, and you get server-side media controls:

# Start a call (no sdp, no permission step)
call = client.calls.initiate({"to": "+5511999999999"})

# Answer an inbound call (after the call.ringing webhook) — no sdp
client.calls.accept(call["id"])

# Stream an audio file into the active call (.mp3/.wav/.opus by URL;
# queued and played on connect when the call is not active yet)
client.calls.play(call["id"], "https://cdn.example.com/ivr-greeting.mp3")

# Full-duplex realtime audio: returns {wsUrl, token, expiresInSeconds}.
# Connect a WebSocket to wsUrl and exchange RAW binary PCM16 LE frames
# (plain WebSocket transport, NOT WebRTC; token is single-use, ~2 min)
session = client.calls.realtime_session(call["id"], "talk")

Phone Lines

client.phone_lines requires a tenant-scoped API key (a number-scoped key is refused). The verification routes need phone_lines:purchase, which only the workspace OWNER has; the activation audio needs phone_lines:read. Every verification call returns the same VerificationState: { status, canPurchase, verification } with status one of NONE, PENDING_CONTACT, NEEDS_DOCUMENT, IN_REVIEW, APPROVED, REJECTED.

Account verification

import base64
import uuid

state = client.phone_lines.verification.get()
print(state["status"], state["canPurchase"])

with open("contrato-social.pdf", "rb") as f:
    document = "data:application/pdf;base64," + base64.b64encode(f.read()).decode()

# Idempotency-Key is REQUIRED. Generate it once and REUSE THE SAME KEY when you
# retry this exact request (timeout, network error): the server then returns the
# current state with replayed=True instead of submitting twice.
key = str(uuid.uuid4())
result = client.phone_lines.verification.start(
    document_type="CNPJ",                    # "CPF" | "CNPJ"
    document_number="12.345.678/0001-90",
    contact_email="finance@acme.com.br",
    contact_whatsapp="+55 11 99999-8888",    # country + area code
    document=document,                        # data URL: PDF/JPG/PNG/WEBP, <= 10 MB
    idempotency_key=key,
)
result["state"]["status"]    # usually "PENDING_CONTACT": codes went to the required channels
result["replayed"]           # True when the response is a replay (Idempotent-Replayed: true)

# Contact channels in the PATH are lower-case ("whatsapp" | "email");
# in the response body they are UPPERCASE ("EMAIL" | "WHATSAPP").
client.phone_lines.verification.send_contact_code("whatsapp")   # resend (60 s cooldown)
state = client.phone_lines.verification.confirm_contact("whatsapp", "123456")
state = client.phone_lines.verification.confirm_contact("email", "654321")

# When the document came back UNREADABLE/UNCLEAR, or the status is NEEDS_DOCUMENT:
state = client.phone_lines.verification.submit_document(document)

Errors are the usual typed exceptions with body["code"], e.g. ConflictError IDEMPOTENCY_KEY_REUSED (same key, different body) / IDEMPOTENCY_KEY_IN_USE, RateLimitError RATE_LIMITED (10 submissions/hour, retryAfterSeconds) / CONTACT_CODE_COOLDOWN, ValidationError CONTACT_CODE_INVALID / CONTACT_CODE_EXPIRED.

Activation audio

from pilot_status import NotFoundError

try:
    audio = client.phone_lines.get_activation_audio("act_...")
except NotFoundError as e:
    print(e.body["code"])   # ACTIVATION_NOT_FOUND
else:
    audio.content_type      # e.g. "audio/mpeg"
    audio.content_length    # int | None
    audio.file_name         # from Content-Disposition, or None
    with open(audio.file_name or "activation.mp3", "wb") as f:
        f.write(audio.data)

⚠️ The recording speaks the activation code, which is a credential: never log it, never embed it in a public page. audio.data is left out of repr() on purpose.

Phone-line webhooks

Phone-line events come from a separate webhook registry, signed like the numbers webhooks (x-pilot-status-signature, HMAC-SHA256 hex over the raw body) but with the phone-line secret (plwh_...). Envelope: { id, event, createdAt, data }. They are typed as PhoneLineWebhookEvent (phone_line.purchased, audio_received, code_received, code_failed, renewed, payment_failed, suspended, returned, canceled, verification_updated) and are not accepted by parse_customer_webhook. audioUrl (may be None) points to the audio route above — fetch it with your API key.

Manage that registry with client.phone_lines.webhooks (tenant-scoped key, phone_lines:webhooks, ADMIN and up). Responses are returned verbatim (camelCase).

from pilot_status import NotFoundError

catalogue = client.phone_lines.webhooks.list()
catalogue["webhooks"]   # [{ id, name, url, events, active, lastDeliveryAt, lastStatusCode, createdAt }]
catalogue["events"]     # every phone_line.* event you can subscribe to

# NOT idempotent: two calls create two webhooks. The secret comes back ONLY here, once.
created = client.phone_lines.webhooks.create(
    url="https://hooks.acme.com/phone-lines",       # https + public, else 400 WEBHOOK_URL_REFUSED
    events=["phone_line.code_received", "phone_line.code_failed"],   # or ["*"]
    name="Activation codes",                         # optional: defaults to the URL's hostname
)
secret = created["webhook"]["secret"]               # "plwh_..." — store it now

hook_id = created["webhook"]["id"]
client.phone_lines.webhooks.get(hook_id)["webhook"]
client.phone_lines.webhooks.update(hook_id, active=False)   # only non-None arguments are sent
client.phone_lines.webhooks.update(hook_id, events=["*"], active=True)

# Latest deliveries, newest first, without payloads (limit 1..200, default 50)
deliveries = client.phone_lines.webhooks.list_deliveries(hook_id, limit=20)["deliveries"]
for d in deliveries:
    print(d["event"], d["status"], d["attempts"], d["responseStatus"], d["lastError"])

# One delivery with the exact payload that was POSTed and signed
try:
    delivery = client.phone_lines.webhooks.get_delivery(hook_id, deliveries[0]["id"])["delivery"]
except NotFoundError as e:
    print(e.body["code"])   # WEBHOOK_NOT_FOUND | WEBHOOK_DELIVERY_NOT_FOUND
else:
    delivery["payload"]     # str — verify the signature against it as is

client.phone_lines.webhooks.delete(hook_id)   # {"ok": True}; also deletes the delivery history

Verify a delivery in your handler with verify_webhook_signature (same function as for the numbers webhooks, keyed with the plwh_... secret; see Verifying the signature):

from pilot_status import WEBHOOK_SIGNATURE_HEADER, verify_webhook_signature

raw = request.get_data()   # Flask; FastAPI: `await request.body()` — the RAW bytes
if not verify_webhook_signature(raw, request.headers.get(WEBHOOK_SIGNATURE_HEADER), secret):
    abort(401)

⚠️ A phone_line.code_received payload carries the activation code, a credential: never log delivery["payload"] or the raw body.

Workspace webhooks

client.workspace.webhooks is the same registry seen from the workspace (/v1/workspace/webhooks*): same methods, same plwh_... secret and signature, and it also accepts wallet.topup_paid (a wallet top-up was credited). "*" still means every phone-line event only — wallet events are opt-in, list them by name. Bodies are typed as WorkspaceWebhookEvent (WalletTopupPaidEvent for the wallet one).

created = client.workspace.webhooks.create(
    url="https://hooks.acme.com/workspace",
    events=["*", "wallet.topup_paid"],   # phone-line events + the wallet event
)
secret = created["webhook"]["secret"]   # "plwh_..." — shown ONLY here

Workspace name, settings, archive and ownership

client.workspace.rename(name="Acme Store")                  # {"id", "name"}; 1..60 chars
client.workspace.get_settings()        # {"settings": {mainCurrency, mainTimezone, mainLanguage,
                                       #   billingMode, currencyLocked}, "phoneLinePrice": {...}}
client.workspace.update_settings(main_timezone="America/Sao_Paulo", main_language="en")

rename and update_settings accept a tenant-scoped ps_ key (OAuth / account key: ADMIN and up). Only the arguments you pass are sent, as mainTimezone / mainLanguage. The currency and billing mode are not settable here — the OWNER changes them in the dashboard.

# ⛔ IRREVERSIBLE from the API: locks EVERYONE out (you too), the workspace's ps_ keys
# stop authenticating, and there is no unarchive route (support only).
client.workspace.archive(confirm_name="Acme Store")         # the exact current name

# The member becomes OWNER (and pays the bill); you become ADMIN. OAuth refresh tokens
# of both sides are revoked.
client.workspace.transfer_ownership(email="new-owner@example.com")

archive and transfer_ownership need the OWNER as a user: an OAuth token or the OWNER's account key (ps_account_... + workspace_id). Every classic ps_ key gets 403 MACHINE_CREDENTIAL_CANNOT_MANAGE_WORKSPACE.

Account keys and workspaces (resellers)

An account key (ps_account_..., created in Profile → API) belongs to a USER, not to a workspace. It acts on a workspace with the user's live role there, named by workspace_id (sent as x-workspace-id):

from pilot_status import PilotStatusClient

account = PilotStatusClient(api_key="ps_account_...")

account.workspaces.list()["data"]        # [{ id, name, role, plan, createdAt, sharedCard }]
ws = account.workspaces.create(name="Client A")   # NOT idempotent: list() before retrying
ws["apiKey"]                             # its primary ps_workspace_ key, ONLY here (or None)
ws["sharedCard"]                         # { linked, sourceWorkspaceId }

keys = account.workspaces.api_keys
keys.list(ws["id"])["data"]              # masked
named = keys.create(ws["id"], name="CRM")["apiKey"]["key"]   # shown once
keys.revoke(ws["id"], "key_id")          # named keys only; the primary is rotated

client_a = account.with_workspace(ws["id"])   # x-workspace-id on every call
client_a.billing.get_topup("order_id")

Errors: no workspace_id on a workspace route → 400 WORKSPACE_ID_REQUIRED; a workspace the user is not an active member of → 403 WORKSPACE_MEMBERSHIP_REQUIRED; client.workspaces with a workspace/number key or an OAuth token → 403 ACCOUNT_KEY_REQUIRED.

Reserve card (shared card, 1.19.0)

A reseller whose reserve card was configured by Pilot Status can let a customer's workspace fall back to it (the workspace's own card is always tried first):

# At creation: opt in explicitly. Omitted (or False) = NOT shared.
ws = account.workspaces.create(name="Client B", share_card=True)
ws["sharedCard"]                         # { "linked": True, "sourceWorkspaceId": "..." }

# Later, on any workspace the key's user OWNS (both idempotent: "changed": False):
account.workspaces.link_shared_card(ws["id"])     # PUT    -> { workspaceId, sharedCard, changed }
account.workspaces.unlink_shared_card(ws["id"])   # DELETE -> the reseller's card stops paying it

409 SHARED_CARD_NOT_CONFIGURED (no reserve card for this user), 409 SOURCE_ARCHIVED, 409 NO_SHARED_OWNER (no longer an active OWNER of the source) and, on link, 400 SELF_SOURCE. With share_card=True, any of those 409s means NO workspace was created.

Billing

Tenant-scoped credential (or an account key with workspace_id). Nothing is charged by the call itself.

# Pix top-up (BRL workspaces only, else 400 PIX_NOT_ELIGIBLE)
pix = client.billing.create_checkout(purpose="wallet_topup", amount=50, method="pix")
pix["pix"]["copyPaste"], pix["pix"]["qrCode"], pix["pix"]["expiresAt"]
client.billing.get_topup(pix["orderId"])["topup"]["status"]   # pending | paid | expired | failed

# Hosted card page (default method)
client.billing.create_checkout(purpose="wallet_topup", amount=50, success_url="https://...")["url"]

# Card on your own page (Stripe Elements). 503 PAYMENTS_NOT_CONFIGURED when unavailable.
si = client.billing.create_card_setup_intent()          # clientSecret, setupIntentId, publishableKey
# ... stripe.confirmSetup(...) in the browser, then:
client.billing.sync_card_setup_intent(si["setupIntentId"])   # { saved, card }

pi = client.billing.create_payment_intent(amount=50, save_card=True, idempotency_key="order-42")
# ... stripe.confirmPayment(...) in the browser, then:
client.billing.sync_payment_intent(pi["paymentIntentId"])    # { credited, balance, orderStatus }

With idempotency_key, a retry with the same key and body returns the same order and PaymentIntent; the same key with another body is 409 IDEMPOTENCY_KEY_REUSED, and while the first call is still running 409 IDEMPOTENCY_KEY_IN_USE.

Number webhooks: secret rotation and circuit breaker

client.webhooks acts on the number webhooks (/v1/webhooks*, webhooks:manage). Creating one (POST /v1/webhooks) returns hasSecret and secret — the signing secret in clear, only in that response. deliveryTimeoutMs on create/update is platform-staff only (403 DELIVERY_TIMEOUT_STAFF_ONLY).

rotated = client.webhooks.rotate_secret("wh_1")   # {"id", "hasSecret": True, "secret"}
new_secret = rotated["secret"]                     # returned ONCE — store it now

# Resume a destination paused by the circuit breaker (it closes only by hand). Idempotent.
r = client.webhooks.reactivate("wh_1")
print(r["released"], r["stillHeld"], r["circuitOpen"])

⚠️ Rotation is immediate with no overlap: the old secret stops at once, but deliveries already in flight may still carry its signature — accept both on your receiver for a short window, or rotate when traffic is quiet. Webhooks created before 2026-09-15 have no secret (unsigned deliveries) until rotated: rotate_secret is the only way to get one.

Webhooks (parse / validation)

from pilot_status import is_unknown_customer_webhook_event, parse_customer_webhook

def handler(payload: dict):
    event = parse_customer_webhook(payload)

    # An event newer than this SDK version: acknowledge it (2xx), never fail on it.
    if is_unknown_customer_webhook_event(event):
        return

    if event["event"] == "message.failed":
        print(event["data"]["errorMessage"])

    if event["event"] == "call.ended":
        # call.* payloads are FLAT (no "data" wrapper)
        print(event["status"], event.get("duration"))

Every number.* event carries a top-level id (UUID), the same on every retry or replay of that event — deduplicate on it. number.connected also carries data["connectedAt"] (ISO-8601). Both are NotRequired: a backend that predates them does not send them.

Verifying the signature

parse_customer_webhook only proves the shape of an event — anyone can POST that JSON to your URL. A webhook created with a secret receives x-pilot-status-signature: HMAC-SHA256, hex, over the raw body, keyed with the full secret (number webhooks and phone-line plwh_... webhooks use the same algorithm). verify_webhook_signature(raw_body, signature_header, secret) checks it in constant time and returns False — it never raises — for a missing, empty or malformed header, an empty secret or a tampered body. raw_body is bytes (or str, encoded as UTF-8).

import json
from pilot_status import WEBHOOK_SIGNATURE_HEADER, parse_customer_webhook, verify_webhook_signature

# Flask
@app.post("/webhooks/pilot-status")
def pilot_status_webhook():
    raw = request.get_data()   # the bytes we signed — not json.dumps(request.json)
    if not verify_webhook_signature(raw, request.headers.get(WEBHOOK_SIGNATURE_HEADER), SECRET):
        return "invalid signature", 401
    event = parse_customer_webhook(json.loads(raw))
    ...

# FastAPI
@app.post("/webhooks/pilot-status")
async def pilot_status_webhook(request: Request):
    raw = await request.body()
    if not verify_webhook_signature(raw, request.headers.get(WEBHOOK_SIGNATURE_HEADER), SECRET):
        raise HTTPException(status_code=401)
    event = parse_customer_webhook(json.loads(raw))

⚠️ Pass the body as received. Re-serializing parsed JSON reorders keys and changes escapes, so legitimate deliveries fail. The header is compared exactly: no sha256= prefix, lowercase hex. A webhook created without a secret gets no header — accepting it anyway is your explicit decision. client.webhooks.rotate_secret(id) gives it one.

Events this SDK version does not know

The platform adds events, and a webhook subscribed to "*" receives a new one the day it ships — before you upgrade. parse_customer_webhook does not raise on an event name it does not know: it returns {"type": "unknown", "event", "data", "raw"} (UnknownCustomerWebhookEvent) — event and data as received (data is None for a flat event), raw the whole body, nothing validated. Answer it with a 2xx and ignore it; is_unknown_customer_webhook_event(event) tells it apart (no known event has a top-level type).

It still raises WebhookParseError on a body that is not an object with a string event, and on a known event whose fields break its contract. Pass unknown_events="raise" to keep the old behaviour. is_customer_webhook_event stays strict: False for an unknown event name.

Notes:

  • Customer webhook payloads do not include: projectSlug, lastMessageId. Optional correlationId (same as HTTP 202 when present) may appear on outbound status events and on message.reply / message.received when correlated to a prior send.
  • message.received includes fromMe (boolean).
  • message.group is delivered for inbound group messages (includes groupName).
  • message.newsletter is delivered for inbound channel messages (JID ending in @newsletter).
  • Supported events in the parser: message.sent, message.delivered, message.read, message.failed, message.reply, message.received, message.group, message.newsletter, number.created, number.connected, number.disconnected, number.removed, number.restored, lead.received, call.ringing, call.connected, call.ended, call.missed, call.permission_updated.
  • lead.received: data is the whole lead — { leadId, leadgenId, whatsappNumberId, pageId, pageName?, formId, formName?, adId?, adsetId?, campaignId?, adName?, adsetName?, campaignName?, platform?, isOrganic?, createdAt, fullName?, email?, phone?, fields: [{ key, label?, values }], consentGiven?, conversationId? }. Use leadgenId (Meta's lead id) as the idempotency key; leadId is the id for client.leads.get. In fields, label is absent when it could not be resolved; on client.leads.* it is always present, falling back to the key.
  • call.* payloads are flat (fields sit next to event, no data wrapper): { event, callId, externalCallId?, direction, status, from, to, timestamp, duration? }. duration (seconds) appears on call.ended only when the call was answered; call.permission_updated has callId/direction None and status NO_PERMISSION | TEMPORARY | PERMANENT.

Metadata

Release files for pilot-status 1.22.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pilot-status 1.22.0
File Size Uploaded Provenance Actions
pilot_status-1.22.0.tar.gz 138.3 kB With provenance Details for pilot_status-1.22.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pilot-status 1.22.0
File Interpreter ABI Platform Actions
pilot_status-1.22.0-py3-none-any.whl Python 3 none any Details for pilot_status-1.22.0-py3-none-any.whl

Total release size: 222.7 kB

Release files / pilot_status-1.22.0.tar.gz

Download URL pilot_status-1.22.0.tar.gz
Size 138.3 kB
Tags Source
SHA-256 checksum
How to use checksums
e699c7be360ba553e06546cd0a85576bda0df011e1e27c48a8e8ef4e70d34b9b
BLAKE2b-256 checksum
How to use checksums
4ba111fae7ef85e5af0a6ef24fc5c7ba0a9ac8af1b1fb09f3f6a55fd696031c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Release files / pilot_status-1.22.0-py3-none-any.whl

Download URL pilot_status-1.22.0-py3-none-any.whl
Size 84.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d141ada3ef416cf7161301bb99271f9b89c23a0f75d3e2bcdbadf75b6e4634e2
BLAKE2b-256 checksum
How to use checksums
ddc7914aa5a2b69d8bc492abb0f1d0bb1189839984844962c47fb13322fe25e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

Security for pilot-status 1.22.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pilot_status-1.22.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 11, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.22.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page