Skip to main content

Callstorm SDK para Python

SDK oficial de la API de Callstorm: campañas de voz salientes con audio, voicebot, agente conversacional con IA y agentes humanos; listas de leads, llamadas, exportaciones y webhooks.

  • Sin dependencias: solo la biblioteca estándar, Python 3.9 o superior.
  • Reintentos seguros, paginación con for, errores tipados y verificación de webhooks.
  • Tipado (py.typed) con TypedDict para los objetos principales.

Instalación

pip install callstorm

Inicio rápido

from callstorm import Callstorm

client = Callstorm(api_key="vx_…")   # clave creada en Configuración › Integraciones

me = client.me()
print(me["account"]["companyName"], me["account"]["balanceMicros"] / 1_000_000, "US$")

# Sube una lista de leads y espera a que esté validada.
with open("leads.csv", "rb") as f:
    lead_list = client.lead_lists.create_from_file(
        "Vencimientos octubre", f.read(), "leads.csv",
        column_mapping={"telefono": "phone", "nombre": "nombre_cliente"}, country="CL",
    )
client.lead_lists.wait_until_ready(lead_list["leadListId"])

# Crea un borrador a partir de una plantilla y lánzalo.
campaign = client.campaigns.create({"general": {...}, "templateId": "tpl_…", "leadListId": lead_list["leadListId"]})
client.campaigns.launch(campaign["campaignId"], idempotency_key=f"launch-{campaign['campaignId']}")

# Recorre los resultados.
for call in client.calls.list(campaign_id=campaign["campaignId"]):
    print(call["phone"], call.get("disposition"), call.get("resultCode"))

El ejemplo completo, con manejo de errores, está en la sección Ejemplos completos.

Autenticación

La clave se crea en Configuración › Integraciones y viaja en la cabecera X-Api-Key (o Authorization: Bearer con use_bearer=True). Cada clave tiene scopes; una operación sin el scope necesario lanza ForbiddenError. La URL base es https://api.callstorm.ai/v1/ext; solo cámbiala si soporte te indica otra.

client = Callstorm(api_key, timeout=15, max_retries=3)

Recursos

Recurso Métodos
client.campaigns list, create, get, update, delete, patch (ajuste en vivo), set_lead_lists, estimate, launch, pause, resume, stop, archive, duplicate
client.templates list, create, get, update, delete, duplicate
client.lead_lists list, create, get, delete, leads, create_from_file, wait_until_ready
client.files presign, upload, upload_path, content_type_for
client.dnc list, add, remove
client.calls list, summary, get (transcripción y URLs de grabación)
client.exports list, create, get, wait_until_done
client.account cells, trunks, create_trunk, trunk, update_trunk, delete_trunk, test_trunk, caller_ids, create_caller_id, update_caller_id, delete_caller_id
client.agents list, get, create, update, delete, set_status, sip_credentials, session_token
client.credits ledger, payments, packages, pricing, checkout_options, checkout
client.webhooks list, create, delete
client.api_keys list, create, delete (crear y revocar requieren sesión de usuario)
client me, dashboard, get, post, put, patch, delete, request

Los objetos se devuelven como dict con las claves de la API (campaignId, resultCode…). Los importes van en micro-dólares (1 US$ = 1 000 000) salvo los campos terminados en Usd. El parámetro from de los filtros se llama from_ en Python.

Paginación

Las listas grandes devuelven páginas con nextCursor. El Paginator las recorre por ti:

for call in client.calls.list(campaign_id=campaign_id, limit=200): ...
first = client.calls.list(campaign_id=campaign_id).first_page()      # {"items", "nextCursor"?, "total"?}
top = client.campaigns.list(status="RUNNING").all(50)
for page in client.dnc.list().pages(): print(len(page["items"]))

Una página puede venir corta o vacía con nextCursor presente: el paginador sigue hasta que la API deja de devolver cursor.

Idempotencia y reintentos

Toda escritura acepta idempotency_key (letras, dígitos, _ . : -, hasta 128 caracteres). La API guarda la primera respuesta 24 horas y la repite ante el mismo valor; client.last_replayed indica cuándo pasó.

client.campaigns.launch(campaign_id, idempotency_key=f"launch-{campaign_id}")

El SDK reintenta solo:

  • 429: espera hasta que se abra la ventana (details.resetAt, máximo 60 s) y vuelve a intentar.
  • 502, 503, 504 y fallos de red: espera 0,5 s, 1 s, 2 s… (máximo 8 s). Solo en lecturas o en escrituras con idempotency_key; una escritura sin clave no se repite nunca.

max_retries (2 por defecto) limita el total. client.rate_limit guarda la última ventana vista (limit, remaining, reset_at).

Errores

Todas las excepciones extienden CallstormError y exponen status, code, details y replayed.

Clase HTTP Cuándo
ValidationError 400 cuerpo o filtros inválidos; issues lista cada campo
AuthenticationError 401 clave ausente, inválida, revocada o vencida
InsufficientCreditsError 402 el saldo no cubre la operación
ForbiddenError 403 falta el scope o la cuenta está suspendida
NotFoundError 404 el recurso no existe
ConflictError 409 estado incompatible (INVALID_TRANSITION, NOT_DRAFT, IN_USE…)
PreconditionError 412 falta configurar algo (CARRIER_NOT_CONFIGURED)
PayloadTooLargeError 413 archivo demasiado grande
RateLimitError 429 límite por minuto; reset_at, retry_after_seconds
ServerError 5xx fallo de la API o de un proveedor
NetworkError — sin respuesta: DNS, TLS, timeout
WaitTimeoutError, ProcessingFailedError — de wait_until_ready / wait_until_done
WebhookSignatureError — firma de webhook inválida
from callstorm import ConflictError, InsufficientCreditsError

try:
    client.campaigns.launch(campaign_id)
except InsufficientCreditsError:
    ...  # recargar saldo
except ConflictError as e:
    if e.code == "INVALID_TRANSITION": ...  # ya lanzada
    else: raise

Subida de archivos

files.upload pide una URL prefirmada y sube el archivo con el tipo y tamaño exactos que la firma exige. Listas de leads: CSV, XLS, XLSX o texto plano hasta 10 MB. Audios: WAV o MP3 hasta 20 MB.

key = client.files.upload_path("audio", "mensaje.mp3")

Webhooks

Cada entrega trae X-Voxcore-Signature: sha256=<HMAC-SHA256 del cuerpo con el secreto>. Verifica sobre el cuerpo crudo, nunca sobre el JSON ya parseado:

from callstorm import parse_event, WebhookSignatureError

# Flask
@app.post("/hook")
def hook():
    try:
        event = parse_event(request.get_data(), request.headers, WEBHOOK_SECRET)
    except WebhookSignatureError:
        return "", 401
    if event.is_call_completed:
        call = event.data
    elif event.is_campaign_status_changed:   # campaign.started, .paused, .completed o .status_changed
        ...
    return "", 200

Eventos: call.completed, campaign.status_changed (alias campaign.started, campaign.completed, campaign.paused), lead_list.processed, balance.low (alias credits.low) y payment.succeeded. Responde 2xx en menos de 8 segundos y procesa después. Un receptor sin framework está en la sección Ejemplos completos.

Consola de agente en tu CRM

session = client.agents.session_token(agent_id, ttl_sec=8 * 3600)
# Entrega session["embedUrl"] al navegador y muéstralo en un <iframe allow="microphone">.

Ejemplos completos

Lanzar una campaña de principio a fin

# CALLSTORM_API_KEY=vx_… python run_campaign.py
import os

from callstorm import Callstorm, InsufficientCreditsError, ValidationError

client = Callstorm(api_key=os.environ["CALLSTORM_API_KEY"])

account = client.me()["account"]
print(f"Cuenta {account['companyName']}, saldo US$ {account['balanceMicros'] / 1_000_000:.2f}")

# 1. Lista de leads: el CSV trae las columnas "telefono" y "nombre"; el consentimiento se declara al subirla.
with open("leads.csv", "rb") as f:
    lead_list = client.lead_lists.create_from_file(
        "Vencimientos octubre", f.read(), "leads.csv", column_mapping={"telefono": "phone", "nombre": "nombre_cliente"}, country="CL",
    )
ready = client.lead_lists.wait_until_ready(lead_list["leadListId"])
print(f"{ready['validRows']} filas válidas, {ready['rejectedRows']} rechazadas")

# 2. Borrador a partir de una plantilla existente; el troncal y el caller ID vienen de Configuración › Telefonía.
template = client.templates.list("VOICEBOT")[0]
caller_id = client.account.caller_ids()[0]
campaign = client.campaigns.create({
    "general": {
        "name": "Recordatorio de pago", "type": "VOICEBOT", "language": "es", "callerId": caller_id["e164"], "trunkId": caller_id.get("trunkId"),
        "schedule": {"timezone": "America/Santiago", "windowStart": "09:00", "windowEnd": "20:00", "days": [1, 2, 3, 4, 5]},
        "dialingRules": {"maxAttempts": 3, "retryIntervalMin": 60, "maxConcurrency": 10},
    },
    "templateId": template["templateId"], "leadListId": ready["leadListId"],
}, idempotency_key=f"campaign-oct-{ready['leadListId']}")

# 3. Lanzamiento (o programación con start_at). La clave de idempotencia hace seguro un reintento.
try:
    running = client.campaigns.launch(campaign["campaignId"], idempotency_key=f"launch-{campaign['campaignId']}")
    print(f"Campaña {running['campaignId']} en estado {running['status']}")
except InsufficientCreditsError as e:
    print("Recarga el saldo primero:", e.details)
except ValidationError as e:
    print("Corrige el borrador:", e.issues)

# 4. Resultados a medida que llegan.
for call in client.calls.list(campaign_id=campaign["campaignId"], disposition="ANSWERED"):
    print(call["phone"], call.get("resultCode"), f"{call['durationSec']}s")

Receptor de webhooks sin framework

# CALLSTORM_WEBHOOK_SECRET=whsec_… python webhook_server.py
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

from callstorm import WebhookSignatureError, parse_event

SECRET = os.environ["CALLSTORM_WEBHOOK_SECRET"]   # el `secret` que se muestra una sola vez al crear el webhook


class Hook(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))
        try:
            event = parse_event(raw, self.headers, SECRET)
        except WebhookSignatureError:
            self.send_response(401)
            self.end_headers()
            return
        if event.is_call_completed:
            call = event.data
            print("llamada", call["callId"], call.get("disposition"), call.get("resultCode"), "(no volver a llamar)" if call.get("doNotCall") else "")
        elif event.is_campaign_status_changed:
            c = event.data
            print("campaña", c["campaignId"], f"{c['from']} -> {c['to']}", c.get("pausedReason", ""))
        self.send_response(200)   # responde en menos de 8 s; el trabajo pesado va después
        self.end_headers()


if __name__ == "__main__":
    HTTPServer(("", 8080), Hook).serve_forever()

Versionado

Semver. Mientras la versión sea 0.x, los cambios incompatibles pueden llegar en versiones menores y se anuncian en el CHANGELOG incluido en la distribución. Los objetos conservan los campos nuevos que agregue la API.

Desarrollo

cd sdk/python
python -m venv .venv && . .venv/bin/activate      # en Windows: .venv\Scripts\activate
pip install -e .[dev]
pytest
python -m build                                   # dist/ con wheel y sdist

Licencia MIT. Soporte: support@callstorm.ai.

Metadata

Release files for callstorm 0.1.1

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

Source distribution (sdist)

Source distribution for callstorm 0.1.1
File Size Uploaded Provenance Actions
callstorm-0.1.1.tar.gz 32.3 kB With provenance Details for callstorm-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for callstorm 0.1.1
File Interpreter ABI Platform Actions
callstorm-0.1.1-py3-none-any.whl Python 3 none any Details for callstorm-0.1.1-py3-none-any.whl

Total release size: 61.6 kB

Release files / callstorm-0.1.1.tar.gz

Download URL callstorm-0.1.1.tar.gz
Size 32.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b6a93fe735bf3b861238a4b69e31faccd26edfd25872b93ea1a390c533594d69
BLAKE2b-256 checksum
How to use checksums
e9696e7486cf46075de9b20ba236fd7262009c72a848a2f18cfbb60070efbc38
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 18, 2026.

Transparency log

Release files / callstorm-0.1.1-py3-none-any.whl

Download URL callstorm-0.1.1-py3-none-any.whl
Size 29.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
657620065d8113bab292bb0a4017071bccc7ee6d3ef5422ce2a4160db2c79478
BLAKE2b-256 checksum
How to use checksums
d5048b354346d8d6c7436f0c7de98a1fb289088799b69c7872f83b0f0c6d229f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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 Oct 18, 2026.

Transparency log

Security for callstorm 0.1.1

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 callstorm-0.1.1.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 Oct 18, 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

0.1.1 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