# Webhook

> Webhooks and events: everything that happens, delivered to your server, signed.

```python
hook = noclick.Webhook.from_name("https://api.yourco.test/noclick/events", create_if_missing=True,
                                 events=["operation.*", "human.answered"])
secret = hook.reveal_secret()   # needs the webhooks:reveal scope

# in your receiver
event = noclick.Webhook.verify(request_body, request_headers, secret)
print(event.type, event.data)
```

Every event is also kept for 30 days: `noclick.Event.list(type="domain.*")`.

## noclick.Webhook

```python
class Webhook
```

An endpoint on your server that receives events, signed with its secret.
One created for a user (inside `as_user`, or with `user=`) receives
only that user's events; your account's own receive every event, your
users' included.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `str` |  |
| `url` | `str` |  |
| `events` | `list[str]` | The event types it receives; `*` matches the rest of a name. |
| `enabled` | `bool` |  |
| `status` | `str` | `healthy`, `failing` (its latest deliveries failed; retries continue) or `disabled`. |
| `description` | `str | None` |  |
| `success_rate_24h` | `float | None` | The share of attempts in the last 24 hours your server answered 2xx (None if none). |
| `last_failure` | `dict[str, Any] | None` | The latest failed attempt: `at`, `response_status` and `error` (None if none). |
| `user_id` | `str | None` | The user whose events it receives (None: every event). |
| `created_at` | `Any` |  |
| `secret` | `str | None` | The signing secret (`nk_whsec_...`), present on the object that created the webhook (`create`, or `from_name` when it created one), `rotate_secret` or `reveal_secret`; any other read leaves it out. |

### Webhook.create

```python
noclick.Webhook.create(
    url, *, events, description=None, allow_existing=False, user=...,
    idempotency_key=None, client=None
) -> Webhook
```

Start delivering `events` (type names; `operation.*` or `*` for
more at once) to `url`, an `https` address your server answers. A scope has one
webhook per address: another raises `noclick.Conflict` with `existing_id`, or with
`allow_existing=True` returns the one already there, as it is (its events don't change,
and its `secret` isn't shown: `reveal_secret()` reads it).

Parameters:

- `url` (`str`, required)
- `events` (`Sequence[str]`, required)
- `description` (`str | None`, default `None`)
- `allow_existing` (`bool`, default `False`)
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `idempotency_key` (`str | None`, default `None`): Makes a retried create safe: the same key returns the first result. Generated when omitted.
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Webhook` The new webhook. Its `secret` is shown this once: store it where your receiver reads it.

Usage:

Receive what your code waits on:

```python
hook = noclick.Webhook.create(
    "https://api.yourco.test/noclick/events",
    events=["operation.succeeded", "operation.failed", "human.answered"],
    description="Production receiver",
)
print(hook.secret)   # nk_whsec_...: shown once
```

Only one user's events:

```python
with noclick.as_user("acme"):
    hook = noclick.Webhook.create("https://api.yourco.test/acme/events", events=["connection.*"])
```

### Webhook.from_name

```python
noclick.Webhook.from_name(
    url, *, create_if_missing=False, events=None, description=None, user=...,
    client=None
) -> Webhook
```

A lazy reference to the webhook delivering to `url` in the current (or given)
user; `url` names it, since a scope has one webhook per address. Given `events` or
`description`, it gets the webhook and sets them, on every run, so a deploy can own its
endpoint. `create_if_missing=True` creates it with `events` (and `description`) when
there's none; without it, a missing webhook raises `noclick.NotFound`. Each run with
fields is a write: do it at startup or in a setup script, not per request.

Parameters:

- `url` (`str`, required)
- `create_if_missing` (`bool`, default `False`)
- `events` (`Sequence[str] | None`, default `None`)
- `description` (`str | None`, default `None`)
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Webhook` A webhook that loads (or is created, or has your fields set) the first time it's used.
When this call created it, `secret` holds its signing secret; otherwise read it with
`reveal_secret()`.

Usage:

Own your receiver's endpoint in code, and read its secret on every start:

```python
hook = noclick.Webhook.from_name(
    "https://api.yourco.test/noclick/events",
    create_if_missing=True,
    events=["operation.succeeded", "operation.failed", "human.answered"],
)
secret = hook.secret or hook.reveal_secret()
```

### Webhook.from_id

```python
noclick.Webhook.from_id(webhook_id, *, client=None, user=...) -> Webhook
```

A lazy reference to a webhook by id.

Parameters:

- `webhook_id` (`str`, required)
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).

Returns: `Webhook` A webhook that loads the first time you read a field. Nothing is sent yet.

Usage:

```python
hook = noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
print(hook.status, hook.success_rate_24h)
```

### Webhook.get

```python
noclick.Webhook.get(webhook_id, *, user=..., client=None) -> Webhook
```

Load a webhook by id now; an unknown id raises `noclick.NotFound`.

Parameters:

- `webhook_id` (`str`, required)
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Webhook` The webhook, loaded (without its secret).

Usage:

```python
hook = noclick.Webhook.get("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
print(hook.url, hook.events, hook.status)
```

### Webhook.list

```python
noclick.Webhook.list(
    *, limit=None, user_filter=None, user=..., client=None
) -> list[Webhook]
```

Your account's webhooks (or the current user's, or those `user_filter` covers).

Parameters:

- `limit` (`int | None`, default `None`): Return at most this many.
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `list[Webhook]` Every matching webhook, newest first, fetched page by page.

Usage:

```python
for hook in noclick.Webhook.list():
    print(hook.url, hook.status, hook.last_failure)

everyone = noclick.Webhook.list(user_filter=noclick.ALL_USERS)
```

### Webhook.list_page

```python
noclick.Webhook.list_page(
    *, cursor=None, limit=None, user_filter=None, user=..., client=None
) -> Page
```

One page of webhooks; pass `next_cursor` back as `cursor`.

Parameters:

- `cursor` (`str | None`, default `None`): The `next_cursor` of the page before; omit it for the first page.
- `limit` (`int | None`, default `None`): Return at most this many.
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Page` A page whose `data` holds the webhooks and whose `next_cursor` is `None` on the last page.

Usage:

```python
page = noclick.Webhook.list_page(limit=20)
for hook in page.data:
    print(hook.url, hook.status)
```

### Webhook.update

```python
hook.update(*, url=..., events=..., enabled=..., description=...) -> Webhook
```

Change where it delivers, what it receives, or pause it
(`enabled=False`: events that happen meanwhile are not delivered later).
A field you leave out is unchanged.

Parameters:

- `url` (`Any`, default: unchanged)
- `events` (`Any`, default: unchanged)
- `enabled` (`Any`, default: unchanged)
- `description` (`Any`, default: unchanged)

Returns: `Webhook` This webhook, updated.

Usage:

```python
hook = noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
hook.update(events=["operation.*", "human.*"])
hook.update(enabled=False)   # pause it
```

### Webhook.delete

```python
hook.delete() -> None
```

Delete the webhook; deliveries still retrying stop.

Usage:

```python
noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54").delete()
```

### Webhook.rotate_secret

```python
hook.rotate_secret(*, grace_s=None) -> str
```

Replace the signing secret. For `grace_s` (default a day, at most 7
days) each delivery is signed with both, so deliveries keep verifying while
you deploy the new one; pass `grace_s=0` if the old one leaked.

Parameters:

- `grace_s` (`int | None`, default `None`)

Returns: `str` The new secret, shown this once (also on `hook.secret`).

Usage:

```python
hook = noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
secret = hook.rotate_secret()
print(secret)   # store it with your receiver, then deploy
```

### Webhook.reveal_secret

```python
hook.reveal_secret() -> str
```

Read the current signing secret, so a receiver that starts from code (or a
webhook `from_name` found rather than created) can verify deliveries. Needs
a key with the `webhooks:reveal` scope, which full access leaves out; every
reveal is recorded with the key that made it.

Returns: `str` The secret (`nk_whsec_...`), also on `hook.secret`.

Usage:

```python
hook = noclick.Webhook.from_name("https://api.yourco.test/noclick/events")
secret = hook.reveal_secret()
```

### Webhook.test

```python
hook.test(event_type='operation.succeeded') -> WebhookDelivery
```

Send a sample event of `event_type` now, signed like a real one, and
wait up to 10 seconds for your server's answer. It isn't retried and isn't
recorded in `Event.list`.

Parameters:

- `event_type` (`str`, default `'operation.succeeded'`)

Returns: `WebhookDelivery` The delivery: its `status` (`succeeded` or `failed`), `response_status` and `response_body`.

Usage:

```python
hook = noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
sent = hook.test("human.answered")
print(sent.status, sent.response_status, sent.duration_ms)
```

### Webhook.deliveries

```python
hook.deliveries(*, status=None, event=None, limit=None) -> list[WebhookDelivery]
```

Deliveries newest first (the last 30 days), optionally only those with
`status` (`pending`, `retrying`, `succeeded`, `failed`) or of one
`event` (an `Event` or id).

Parameters:

- `status` (`str | Sequence[str] | None`, default `None`)
- `event` (`Any`, default `None`)
- `limit` (`int | None`, default `None`): Return at most this many.

Returns: `list[WebhookDelivery]` Every matching delivery, fetched page by page (or the first `limit`).

Usage:

```python
hook = noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
for delivery in hook.deliveries(status=["retrying", "failed"], limit=20):
    print(delivery.event_type, delivery.attempts, delivery.response_status, delivery.next_retry_at)
```

### Webhook.redeliver

```python
hook.redeliver(delivery) -> WebhookDelivery
```

Send a delivery's event again now (the same event id, so a receiver that
ignores repeats stays correct), whatever its status.

Parameters:

- `delivery` (`str | WebhookDelivery`, required)

Returns: `WebhookDelivery` The delivery, with this attempt counted in `attempts` and its outcome in `status`.

Usage:

Once your receiver is fixed, send what it missed:

```python
hook = noclick.Webhook.from_id("5e2d8c1a-7b4f-4e93-a6d0-3c9f1b2e8a54")
for missed in hook.deliveries(status="failed"):
    hook.redeliver(missed)
```

### Webhook.verify

```python
noclick.Webhook.verify(payload, headers, secret, *, tolerance_s=300) -> Event
```

Check a delivery in your receiver: `payload` is the raw body exactly
as it arrived (not parsed and re-serialized), `headers` its headers (any
mapping; the name is matched whatever its case) and `secret` the
webhook's, or a list of secrets while you rotate. The `NoClick-Signature`
header is `t=<unix seconds>,v1=<hex>`, where the hex is HMAC-SHA256 of
`"<t>.<body>"` keyed with the secret. A timestamp more than
`tolerance_s` from now is refused, so a captured delivery can't be
replayed later. It sends nothing.

Raises `noclick.WebhookSignatureError` when the header is missing or
malformed, the timestamp is outside the tolerance, or no signature matches.

Parameters:

- `payload` (`bytes | str`, required)
- `headers` (`Mapping[str, Any]`, required)
- `secret` (`str | Sequence[str]`, required)
- `tolerance_s` (`int`, default `300`)

Returns: `Event` The event the body carries, ready to act on.

Usage:

In a Flask receiver, answer 400 to anything that doesn't verify, and 2xx
quickly (do slow work after):

```python
import os
from flask import Flask, request

app = Flask(__name__)

@app.post("/noclick/events")
def noclick_events():
    try:
        event = noclick.Webhook.verify(request.get_data(), request.headers, os.environ["NOCLICK_WEBHOOK_SECRET"])
    except noclick.WebhookSignatureError:
        return "", 400
    if event.type == "human.answered":
        print(event.data["answer"])
    return "", 204
```

While you rotate, accept both secrets:

```python
import os

secrets =[os.environ["NOCLICK_WEBHOOK_SECRET"], os.environ["NOCLICK_WEBHOOK_SECRET_OLD"]]
event = noclick.Webhook.verify(request.get_data(), request.headers, secrets)
```

## noclick.WebhookDelivery

```python
class WebhookDelivery
```

One event sent (or on its way) to one webhook. `status` is `pending`
(not tried yet), `retrying` (an attempt failed; `next_retry_at` says when
the next one is), `succeeded` (your server answered 2xx) or `failed` (three
days of retries ran out). `response_status` and `response_body` (its first
4 KB) are from the latest attempt; `request_body` is the JSON that was sent.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `str` |  |
| `webhook_id` | `str | None` |  |
| `event_id` | `str | None` |  |
| `event_type` | `str | None` |  |
| `status` | `str` |  |
| `attempts` | `int` |  |
| `response_status` | `int | None` |  |
| `response_body` | `str | None` |  |
| `request_body` | `str | None` |  |
| `duration_ms` | `int | None` |  |
| `error` | `str | None` | Why the latest attempt failed (`Answered 502`, `No answer within 10 seconds.`); None once it succeeded. |
| `next_retry_at` | `Any` |  |
| `created_at` | `Any` |  |
| `raw` | `dict[str, Any]` | The response JSON exactly as the API sent it. |
| `ok` | `bool` | Whether your server accepted it (a 2xx). |

## noclick.Event

```python
class Event
```

Something that happened: an operation finished, a person answered, a domain
went live. `type` names it (see `Event.types()`) and `data` is the object
it's about, as its own read returns it (`data["object"]` names the kind,
`data["id"]` its id). Delivered to your webhooks, and kept for 30 days.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `str` |  |
| `type` | `str` | What happened, like `operation.succeeded`. |
| `data` | `dict[str, Any]` | The object the event is about, as its own read returns it. |
| `user_id` | `str | None` | The user it happened for (None for your account's own). |
| `created_at` | `Any` |  |
| `deliveries` | `list[WebhookDelivery]` | Where this event went: one delivery per webhook that subscribes to it, each with its status and attempts. An event from a listing loads its full view on first read. |

### Event.from_id

```python
noclick.Event.from_id(event_id, *, client=None, user=...) -> Event
```

A lazy reference to an event by id.

Parameters:

- `event_id` (`str`, required)
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).

Returns: `Event` An event that loads the first time you read a field. Nothing is sent yet.

Usage:

```python
event = noclick.Event.from_id("7c1e9a4b-2d3f-4a8e-9b6c-0f5d2e8a1b37")
print(event.type, event.created_at)
```

### Event.get

```python
noclick.Event.get(event_id, *, user=..., client=None) -> Event
```

Load an event by id now, with its deliveries; an unknown id (or one older
than 30 days) raises `noclick.NotFound`.

Parameters:

- `event_id` (`str`, required)
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Event` The event, loaded.

Usage:

```python
event = noclick.Event.get("7c1e9a4b-2d3f-4a8e-9b6c-0f5d2e8a1b37")
for delivery in event.deliveries:
    print(delivery.webhook_id, delivery.status, delivery.attempts)
```

### Event.list

```python
noclick.Event.list(
    *, type=None, since=None, until=None, limit=None, user_filter=None, user=...,
    client=None
) -> list[Event]
```

Events newest first, from the last 30 days. `type` is one type or
several, and `*` matches the rest of a name (`domain.*`); `since` and
`until` are timezone-aware datetimes or ISO strings. Outside `as_user`
you read your account's own events; `user_filter` reads your users'.

Parameters:

- `type` (`str | Sequence[str] | None`, default `None`)
- `since` (`Any`, default `None`)
- `until` (`Any`, default `None`)
- `limit` (`int | None`, default `None`): Return at most this many.
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `list[Event]` Every matching event, fetched page by page (or the first `limit`).

Usage:

See what happened to your domains this week:

```python
from datetime import datetime, timedelta, timezone

week = datetime.now(timezone.utc) - timedelta(days=7)
for event in noclick.Event.list(type="domain.*", since=week):
    print(event.created_at, event.type, event.data["name"])
```

Every failure, across your users too:

```python
failed = noclick.Event.list(type=["operation.failed", "agent.turn.failed"], user_filter=noclick.ALL_USERS, limit=50)
```

### Event.list_page

```python
noclick.Event.list_page(
    *, cursor=None, limit=None, type=None, since=None, until=None, user_filter=None,
    user=..., client=None
) -> Page
```

One page of events; pass `next_cursor` back as `cursor`.

Parameters:

- `cursor` (`str | None`, default `None`): The `next_cursor` of the page before; omit it for the first page.
- `limit` (`int | None`, default `None`): Return at most this many.
- `type` (`str | Sequence[str] | None`, default `None`)
- `since` (`Any`, default `None`)
- `until` (`Any`, default `None`)
- `user_filter` (`Any`, default `None`): Which users a read covers: `noclick.ALL_USERS`, `noclick.NO_USER`, a `User`, or your id for one. It filters without acting as that user.
- `user` (`Any`, default: the current user): Who the call acts for. Defaults to the user set by `noclick.as_user` (none: the account itself).
- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Page` A page whose `data` holds the events and whose `next_cursor` is `None` on the last page.

Usage:

```python
page = noclick.Event.list_page(type="operation.failed", limit=100)
while True:
    for event in page.data:
        print(event.id, event.data["kind"])
    if page.next_cursor is None:
        break
    page = noclick.Event.list_page(type="operation.failed", limit=100, cursor=page.next_cursor)
```

### Event.types

```python
noclick.Event.types(*, client=None) -> list[EventType]
```

The catalog of event types a webhook can subscribe to.

Parameters:

- `client` (`Client | None`, default `None`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `list[EventType]` Every event type with what it means, in catalog order (grouped by `area`).

Usage:

```python
for kind in noclick.Event.types():
    print(kind.name, kind.description)
```

## noclick.EventType

```python
class EventType
```

One kind of event: its `name` (`operation.succeeded`) and what it means.
`area` is the part before the first dot, the thing the event is about.
`emitted` is whether NoClick sends it today: the rest are listed so your
code can subscribe before the primitive behind them ships.

| Attribute | Type | Description |
| --- | --- | --- |
| `name` | `str` |  |
| `description` | `str` |  |
| `emitted` | `bool` |  |
| `raw` | `dict[str, Any]` | The response JSON exactly as the API sent it. |
| `area` | `str` | What the event is about: `operation`, `human`, `domain`, ... |
