Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 63 additions & 1 deletion CHANGELOG.md

Large diffs are not rendered by default.

302 changes: 246 additions & 56 deletions README.md

Large diffs are not rendered by default.

23 changes: 12 additions & 11 deletions examples/_common.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
"""Shared by the examples: a client from the environment.

Admin examples read IC_ADMIN_EMAIL / IC_ADMIN_PASSWORD; frontline examples read IC_DATA_EMAIL /
IC_DATA_PASSWORD. Each is a dedicated integration user.
Administrator examples read IC_ADMIN_EMAIL / IC_ADMIN_PASSWORD. Examples that act as a person read
IC_USER_EMAIL / IC_USER_PASSWORD (the older IC_DATA_EMAIL / IC_DATA_PASSWORD still work here).
"""
import os
import sys

from intelligence_cloud import Client

PAIRS = {"admin": ("IC_ADMIN_EMAIL", "IC_ADMIN_PASSWORD"), "data": ("IC_DATA_EMAIL", "IC_DATA_PASSWORD")}
PAIRS = {"admin": ("IC_ADMIN_EMAIL", "IC_ADMIN_PASSWORD"), "user": ("IC_USER_EMAIL", "IC_USER_PASSWORD")}
OLD_NAMES = {"user": ("IC_DATA_EMAIL", "IC_DATA_PASSWORD")}


def client_from_env(kind: str = "data") -> Client:
"""kind: "admin", "data", or "any" (the first pair that is set)."""
kinds = ["admin", "data"] if kind == "any" else [kind]
def client_from_env(kind: str = "user") -> Client:
"""kind: "admin", "user", or "any" (the first pair that is set)."""
kinds = ["admin", "user"] if kind == "any" else [kind]
for k in kinds:
e, p = PAIRS[k]
email, password = os.environ.get(e), os.environ.get(p)
if email and password:
return Client(email=email, password=password, user_agent="ic-examples/0.2")
for e, p in [PAIRS[k]] + ([OLD_NAMES[k]] if k in OLD_NAMES else []):
email, password = os.environ.get(e), os.environ.get(p)
if email and password:
return Client(email, password, user_agent="ic-examples/0.3")
names = " or ".join(f"{PAIRS[k][0]} and {PAIRS[k][1]}" for k in kinds)
sys.exit(f"Set {names} (a dedicated integration user).")
sys.exit(f"Set {names}.")
35 changes: 12 additions & 23 deletions examples/alert_webhook_receiver.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""A dependency-free First Alert webhook receiver (standard library plus this SDK).

IC_ALERT_WEBHOOK_TOKEN=<32+ random characters> IC_DATA_EMAIL=... IC_DATA_PASSWORD=... \
IC_ALERT_WEBHOOK_TOKEN=<32+ random characters> IC_USER_EMAIL=... IC_USER_PASSWORD=... \
python alert_webhook_receiver.py [port]

Make a token with: python -c "import secrets; print(secrets.token_urlsafe(32))"
Expand All @@ -20,11 +20,9 @@
import sys
import threading
import urllib.request
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Optional

from intelligence_cloud import Deduplicator
from intelligence_cloud import Deduplicator, WebhookPayloadError, parse_first_alert_event

SELF_TEST = "--self-test" in sys.argv
TOKEN = os.environ.get("IC_ALERT_WEBHOOK_TOKEN") or (secrets.token_urlsafe(32) if SELF_TEST else "")
Expand All @@ -37,22 +35,12 @@
dedup = Deduplicator()


def alert_id_from(body: bytes) -> Optional[str]:
"""The alert id from a First Alert delivery, or None. Reads nothing else from the request."""
def event_from(body: bytes):
"""The First Alert event, or None when the body has no valid alert id. The payload is not final."""
try:
data = json.loads(body)
except ValueError:
return parse_first_alert_event(body)
except WebhookPayloadError:
return None
if not isinstance(data, dict):
return None
nested = data.get("alert") if isinstance(data.get("alert"), dict) else {}
for value in (data.get("alert_id"), nested.get("id"), data.get("id")):
if isinstance(value, str):
try:
return str(uuid.UUID(value.strip()))
except ValueError:
continue
return None


class Handler(BaseHTTPRequestHandler):
Expand All @@ -62,13 +50,14 @@ def do_POST(self):
self.end_headers()
return
length = int(self.headers.get("Content-Length") or 0)
alert_id = alert_id_from(self.rfile.read(length)) if 0 < length <= MAX_BODY else None
if alert_id is None:
event = event_from(self.rfile.read(length)) if 0 < length <= MAX_BODY else None
if event is None:
self.send_response(400)
self.end_headers()
return
if not dedup.is_duplicate(alert_id):
alert_ids.put(alert_id)
if not dedup.seen(event):
alert_ids.put(event.alert_id) # an in-memory queue here; use a durable one in production
dedup.remember(event) # after the write
self.send_response(204)
self.end_headers()

Expand All @@ -80,7 +69,7 @@ def worker(fetch: bool):
client = None
if fetch:
from _common import client_from_env
client = client_from_env("data")
client = client_from_env("user")
while True:
alert_id = alert_ids.get()
if client is not None:
Expand Down
2 changes: 1 addition & 1 deletion examples/create_customer.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def phrases(env_name):
threat, upset = phrases("IC_THREAT_PHRASES_FILE"), phrases("IC_UPSET_PHRASES_FILE")
spec = CustomerSpec(
company_id=os.environ.get("IC_COMPANY_ID") or None, # store customer.company_id after the first run
company_name="Riverbend Dental",
company_name="Riverbend Auto Group",
admin=PersonSpec("pat.lee@example.com", "Pat", "Lee", phone_number="+15555550100"),
team=TeamSpec(name="Riverbend - Main", street="1 River Rd", city="Springfield", state="IL",
country="US", zipcode="62701", vertical=os.environ.get("IC_VERTICAL", "<vertical id or key>")),
Expand Down
4 changes: 2 additions & 2 deletions examples/my_day.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""A person's day: today's calls, open tasks and alerts. The person's own login.

IC_DATA_EMAIL=... IC_DATA_PASSWORD=... python my_day.py
IC_USER_EMAIL=... IC_USER_PASSWORD=... python my_day.py

Caller numbers are shown as their last four digits. Printing a brief shows only its id and time,
so this script prints the fields it means to show and writes nothing to logs.
"""
from _common import client_from_env
from intelligence_cloud import WrongLoginError

with client_from_env("data") as client:
with client_from_env("user") as client:
conv = client.conversations
try:
me = conv.me()
Expand Down
82 changes: 62 additions & 20 deletions examples/webhook_receiver.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""A dependency-free After Call webhook receiver (standard library plus this SDK).

IC_WEBHOOK_TOKEN=<32+ random characters> IC_DATA_EMAIL=... IC_DATA_PASSWORD=... \
IC_WEBHOOK_TOKEN=<32+ random characters> IC_USER_EMAIL=... IC_USER_PASSWORD=... \
python webhook_receiver.py [port]

Make a token with: python -c "import secrets; print(secrets.token_urlsafe(32))"
Expand All @@ -10,12 +10,22 @@
- The path token is compared in constant time; a wrong token gets 404.
- Bodies over 256 KB get 413; a body that is not JSON, or a malformed After Call event, gets 400.
Event types this SDK doesn't handle get 204 and are ignored.
- Each event's call id is written to a persistent queue (SQLite, keyed on call.id) BEFORE the
delivery is acknowledged, so nothing is lost on restart and repeats collapse into one entry.
- A worker reads each queued call with the frontline integration user (the event is only a
notification) and then upserts your copy on call.id. A 404 means drop it.

Pass --self-test to post the sample event to itself twice, without reading the API, and exit.
- A delivery is stored by its call id (upsert_key) in a persistent queue (SQLite) BEFORE it is
acknowledged, so nothing is lost on restart. A later delivery for the same call can carry newer data:
it replaces the stored entry and re-opens it. Only an exact re-delivery (same call, same content) is
skipped: the Deduplicator checks with seen(event) and is told remember(event) only after the queue
write succeeded, so a delivery whose write failed (answered 503) is processed when it is retried.
Its default store is per process: with several workers pass Deduplicator(store=...) a shared store
(has/add), or rely on the queue's upsert alone.
- Deliveries can arrive out of order (a failed v1 is retried after v2 was stored): the queue keeps each
call's event timestamp, and a delivery older than the stored one (is_older) is remembered and
acknowledged without overwriting newer data. Ordering relies on the event's timestamp; when two
deliveries carry the same timestamp, the later arrival wins.
- A worker reads each queued call with the person's login (the event is only a notification) and then
upserts your copy on call.id. A 404 means drop it.

Pass --self-test to post the sample event twice, a newer copy, then the older one again, without reading
the API, and exit.
"""
import hmac
import json
Expand All @@ -33,6 +43,8 @@
from intelligence_cloud import (
MAX_EVENT_BYTES,
AfterCallEvent,
Deduplicator,
is_older,
NotFoundError,
PayloadTooLargeError,
WebhookPayloadError,
Expand All @@ -51,18 +63,24 @@


class CallQueue:
"""A persistent queue of call ids. A repeat delivery of a queued call id is one entry."""
"""A persistent queue keyed on call id: a later delivery for a call replaces its entry."""

def __init__(self, path: str):
self._db = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
self._db.execute("CREATE TABLE IF NOT EXISTS calls (call_id TEXT PRIMARY KEY, received REAL, done INTEGER DEFAULT 0)")
self._db.execute("CREATE TABLE IF NOT EXISTS calls (call_id TEXT PRIMARY KEY, received REAL, "
"event_time TEXT, done INTEGER DEFAULT 0)")
self._lock = threading.Lock()

def put(self, call_id: str) -> None:
with self._lock: # a repeat after processing re-opens the entry: it may carry newer data
self._db.execute("INSERT INTO calls (call_id, received) VALUES (?, ?) "
"ON CONFLICT(call_id) DO UPDATE SET done = 0, received = excluded.received",
(call_id, time.time()))
def put(self, call_id: str, event_time: str) -> None:
with self._lock: # a newer delivery re-opens the entry: it may carry newer data
self._db.execute("INSERT INTO calls (call_id, received, event_time) VALUES (?, ?, ?) "
"ON CONFLICT(call_id) DO UPDATE SET done = 0, received = excluded.received, "
"event_time = excluded.event_time", (call_id, time.time(), event_time))

def stored_time(self, call_id: str):
with self._lock:
row = self._db.execute("SELECT event_time FROM calls WHERE call_id = ?", (call_id,)).fetchone()
return row[0] if row else None

def next(self):
with self._lock:
Expand All @@ -79,6 +97,7 @@ def pending(self) -> int:


calls = CallQueue(QUEUE_PATH)
dedup = Deduplicator() # per process; pass store=<shared store> when several workers receive


class Handler(BaseHTTPRequestHandler):
Expand All @@ -102,8 +121,21 @@ def do_POST(self):
return self._answer(413)
except WebhookPayloadError:
return self._answer(400)
if isinstance(event, AfterCallEvent):
calls.put(event.call.id) # stored before the acknowledgement
if isinstance(event, AfterCallEvent) and not event.is_test:
key = dedup.upsert_key(event)
if dedup.seen(event): # an exact re-delivery we already stored
print(f"call {key}: exact re-delivery, skipped")
return self._answer(204)
try:
stored = calls.stored_time(key)
if stored is not None and is_older(event, stored):
print(f"call {key}: older than the stored delivery, not stored")
dedup.remember(event)
return self._answer(204)
calls.put(key, event.timestamp.isoformat() if event.timestamp else "") # the durable write
except sqlite3.Error:
return self._answer(503) # not remembered: the sender's retry is processed
dedup.remember(event) # only after the write succeeded
return self._answer(204)

def log_message(self, *args): # don't log request lines: the path holds the secret token
Expand All @@ -114,7 +146,7 @@ def worker(fetch: bool) -> None:
client = None
if fetch:
from _common import client_from_env
client = client_from_env("data")
client = client_from_env("user")
while True:
call_id = calls.next()
if call_id is None:
Expand All @@ -139,10 +171,20 @@ def worker(fetch: bool) -> None:
threading.Thread(target=server.serve_forever, daemon=True).start()
if SELF_TEST:
url = f"http://127.0.0.1:{PORT}/ic/after-call/{TOKEN}"
body = SAMPLE.read_bytes()
for _ in range(2): # the second delivery is a repeat of the same call id: one queue entry
req = urllib.request.Request(url, data=body, method="POST", headers={"Content-Type": "application/json"})
sample = json.loads(SAMPLE.read_bytes())
sample["is_test"] = False
newer = json.loads(json.dumps(sample))
newer["summary"]["text"] = "The refund was approved."
newer["timestamp"] = "2026-11-02T16:50:00Z"
older = json.loads(json.dumps(sample))
older["summary"]["text"] = "An earlier summary."
older["timestamp"] = "2026-11-02T16:40:00Z"
# the same delivery twice (the second is skipped), newer data (stored), then an older delivery (not stored)
for body in (sample, sample, newer, older):
req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
headers={"Content-Type": "application/json"})
print("delivery answered", urllib.request.urlopen(req).status)
time.sleep(0.3)
while calls.pending():
time.sleep(0.1)
server.shutdown()
Expand Down
12 changes: 9 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "intelligence-cloud"
version = "0.2.0"
version = "0.3.0"
description = "Python client for the Intelligence Cloud partner API: customer lifecycle and conversation intelligence."
readme = "README.md"
requires-python = ">=3.10"
Expand All @@ -19,8 +19,14 @@ classifiers = [
]

[project.urls]
Homepage = "https://docs.intelligence.cloud"
Documentation = "https://docs.intelligence.cloud/api"
Homepage = "https://docs.intelligence.cloud/sdk/"
Documentation = "https://docs.intelligence.cloud/sdk/reference"
"Quick start" = "https://docs.intelligence.cloud/sdk/quick-start"
Configuration = "https://docs.intelligence.cloud/sdk/configuration"
Events = "https://docs.intelligence.cloud/sdk/events"
Changelog = "https://docs.intelligence.cloud/sdk/downloads"
"API guide" = "https://docs.intelligence.cloud/api"
"API reference" = "https://docs.intelligence.cloud/reference"
Source = "https://github.com/tresic-cloud/intelligence-cloud-sdk-python"

[tool.hatch.build.targets.wheel]
Expand Down
14 changes: 13 additions & 1 deletion src/intelligence_cloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@
from ._base import Page, unwrap
from ._version import __version__
from .accounts import (
AlertActivation,
LicenseReport,
LineDiff,
LineSyncReport,
NoManagerTeam,
OffboardSummary,
RemovalSummary,
TeamLines,
AlertSetting,
AlertSettings,
ConnectorSpec,
Expand Down Expand Up @@ -67,6 +75,8 @@
UnknownEvent,
parse_after_call_event,
parse_first_alert_event,
upsert_key,
is_older,
)

__all__ = [
Expand All @@ -77,9 +87,11 @@
"FrontlineRequiredError", "ConnectorError", "ConnectorTimeoutError", "ExtensionMappingError",
"AccountError", "WrongLoginError", "WebhookPayloadError", "PayloadTooLargeError", "WebhookTestResult", "RecordingLink",
"AfterCallEvent", "AfterCallCall", "AfterCallSummary", "AfterCallLocation", "UnknownEvent",
"parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event",
"parse_after_call_event", "MAX_EVENT_BYTES", "FirstAlertEvent", "parse_first_alert_event", "upsert_key", "is_older",
"Deduplicator", "DedupStore", "MemoryDedupStore",
"CustomerSpec", "TeamSpec", "ConnectorSpec", "PersonSpec", "AlertSetting", "AlertSettings",
"Customer", "Team", "TeamGroups", "TeamRules", "Member",
"AlertActivation", "NoManagerTeam", "LineSyncReport", "TeamLines", "LineDiff", "LicenseReport",
"RemovalSummary", "OffboardSummary",
"CallBrief", "AlertBrief", "TaskBrief", "TeamRef", "TeamView", "TopicsView", "Reference", "Me", "mask_number",
]
Loading
Loading