# Scheduled messages

`crm.scheduledMessages` — `/v1/audience/scheduled-messages`

A send with a time, and optionally a **condition** checked immediately before it
goes out.

| Action | Route | Scope |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/audience/scheduled-messages` | `messages:read` |
| [`get`](#get) | `GET /v1/audience/scheduled-messages/:id` | `messages:read` |
| [`create`](#create) | `POST /v1/audience/scheduled-messages` | `messages:write` |
| [`createSeries`](#createseries) | `POST /v1/audience/scheduled-messages/series` | `messages:write` |
| [`createRepeating`](#createrepeating) | `POST /v1/audience/scheduled-messages/series` | `messages:write` |
| [`reschedule`](#reschedule) | `PATCH /v1/audience/scheduled-messages/:id` | `messages:write` |
| [`cancel`](#cancel) | `DELETE /v1/audience/scheduled-messages/:id` | `messages:write` |
| [`cancelSeries`](#cancelseries) | `DELETE /v1/audience/scheduled-messages/series/:series` | `messages:write` |
| [`sendNow`](#sendnow) | `POST /v1/audience/scheduled-messages/:id/send-now` | `messages:write` |

**Permissions** — `CRM.CHAT.SCHEDULED_MESSAGE`: `LIST`, `READ`, `CREATE`
(a single schedule or a series), `UPDATE` to reschedule, `DELETE` to cancel
either, and **`SEND` for send-now**, which bypasses the schedule. The rows carry
the account and no per-member creator, so `data_scope` does not narrow them.

---

## Why conditions exist

A drip is easy to start and awkward to stop.

You schedule five messages over two weeks for a lead. They convert after the
third. The last two still go out — now addressed to a paying customer, as a
pitch. Avoiding that means somebody noticing in time and cancelling by hand.

So each occurrence **re-reads the contact a moment before sending** and stands
down if they no longer match the condition you set. Put a `stage` custom field on
your contacts, condition the series on `stage equal to Lead`, and the only thing
you have to do when a lead converts is what you were going to do anyway:

```ts
await crm.contacts.update(contactId, { custom_field_hash: { stage: 'Customer' } });
```

The remaining messages cancel themselves. No scheduled-message ids to track, no
cancellation call, and the record says exactly why each one did not send.

The condition is evaluated **after** the scheduler claims the occurrence and
**immediately before** the message is handed to the channel — not at schedule
time, not a pass earlier. A check run even a minute early is a check that can be
wrong.

---

## Two things that will catch you out

### Templates, not free text

WhatsApp only allows free-form messages within **24 hours** of the contact's last
inbound message. A drip spaced in days is, by construction, outside that window
from the second message onward — so every step but the first has to be an
approved template.

`create` and `createSeries` reject free text that falls outside the window with a
`422`, rather than accepting it and letting the provider refuse it on day four.
That failure mode is the reason to check at schedule time: a drip that silently
dies from message 2 looks like a scheduling bug and isn't one.

### A series is expanded, not recurring

`createSeries` writes **one row per message** immediately. So you can list them,
move one, or cancel one without touching the rest, and "what is queued for this
contact" is a plain list rather than a computation.

The consequence: `until` has to be a real end. There is no rule stored for later
evaluation, so an open-ended cadence has nothing to expand into. Expansions are
capped at 365 occurrences.

---

## The scheduled message object

```ts
interface ScheduledMessage {
  id: string;
  /** The series this belongs to, or null for a one-off. */
  series: string | null;
  /** 1-based position in the series. 1 for a one-off. */
  occurrence: number;
  title: string;
  contact: string;
  channel: string;
  content: MessageContent;
  context: JsonObject;
  /** IANA zone the schedule was expressed in. */
  timezone: string;
  /** The resolved instant, always UTC. What the scheduler fires on. */
  scheduled_at: string;
  /** The same moment as wall-clock in `timezone` — what the user chose. */
  scheduled_at_local: string;
  /** The series condition. null means send unconditionally. */
  conditions: ContactFilter | null;
  /** This occurrence's own extra narrowing, from its step. Both must pass. */
  step_conditions: ContactFilter | null;
  on_condition_fail: 'skip' | 'cancel_series';
  status: 'pending' | 'processing' | 'sent' | 'skipped' | 'failed' | 'cancelled';
  result: ScheduledMessageResult | null;
  processed_at: string | null;
  completed_at: string | null;
  createdAt: string;
  updatedAt: string;
}
```

### Status

| Status | Meaning |
| --- | --- |
| `pending` | Waiting for its moment. The only status that can be rescheduled or cancelled. |
| `processing` | Claimed by the scheduler, mid-send. |
| `sent` | Handed to the channel. What happened next is a **message** status, not this one. |
| `skipped` | Its condition did not match. `result` says what was expected and what was found. |
| `cancelled` | Stood down — by a caller, or by an earlier occurrence failing under `cancel_series`. |
| `failed` | Could not be sent. `result.reason` is one of `contact_missing`, `contact_trashed`, `outgoing_blocked`, `no_channel_identity`. |

`sent` means *accepted by the channel*. Delivery, read receipts and provider
failures live on the message row the send produces, reachable through the inbox —
a scheduled message's job ends when it hands over.

### Result

```ts
interface ScheduledMessageResult {
  reason?: string;        // condition_not_met | series_cancelled_by_condition |
                          // cancelled_by_user | queued | contact_missing |
                          // contact_trashed | outgoing_blocked | no_channel_identity
  scope?: 'series' | 'step';  // condition_not_met: which condition refused
  field_id?: string;      // condition_not_met: the first condition that failed
  condition?: string;     //   its comparison, e.g. "equal to"
  expected?: unknown;     //   the value it was looking for
  at_occurrence?: number; // series_cancelled_by_condition: whose condition failed
}
```

Only the **first** failing condition is named. Listing all of them would be noise
when the first already explains the skip.

This is what makes "why didn't my lead get message 4" answerable:

```ts
const { data } = await crm.scheduledMessages.list({ series });
```

```json
[
  { "occurrence": 1, "status": "sent" },
  { "occurrence": 2, "status": "sent" },
  { "occurrence": 3, "status": "sent" },
  { "occurrence": 4, "status": "skipped",
    "result": { "reason": "condition_not_met", "scope": "series",
                "field_id": "stage", "condition": "equal to", "expected": "Lead" } },
  { "occurrence": 5, "status": "cancelled",
    "result": { "reason": "series_cancelled_by_condition", "at_occurrence": 4 } }
]
```

---

## Time and timezone

`timezone` is **required** on every create, and must be an IANA zone name —
`Asia/Kolkata`, `Europe/London`, `America/New_York`. Abbreviations and offsets
(`IST`, `+05:30`, `GMT+5:30`) are rejected with a `422`.

How it combines with the time you send:

| `scheduled_at` / `starts_at` | Effect of `timezone` |
| --- | --- |
| No offset — `"2026-10-15T10:00:00"` | **Resolves it.** The value is wall-clock in that zone. |
| Carries `Z` or an offset — `"2026-10-15T04:30:00Z"` | **Advisory.** The instant is already pinned; the zone is recorded for display and for later edits. |

Both are accepted because clients differ — an app has a local time and a zone, a
server integration has a UTC instant. The second row is worth reading twice:
passing a zone alongside a `Z` time does not move the send.

Why a zone is stored even when the instant is pinned:

- **Display.** Keep only `04:30Z` and the intent — "ten in the morning" — is
  gone. Every client then re-derives it from the viewer's browser, so an agent in
  Dubai sees a different time from the person who scheduled it.
- **Rescheduling.** `reschedule(id, { scheduled_at: '2026-10-16T10:00:00' })`
  needs a zone to mean anything, and uses the stored one unless you override it.
- **Spacing.** A series spaced in days is expanded in its zone, so a drip that
  crosses a DST boundary keeps landing at 10:00 local rather than walking by an
  hour.

**DST edges.** A wall-clock time can be nonexistent or doubled at a transition —
never in `Asia/Kolkata`, which has no DST, but `2026-03-08T02:30` does not exist
in `America/New_York` and `2026-11-01T01:30` happens twice. The rules:

- **Nonexistent** — shifted **forward by the length of the gap**. `02:30`
  becomes `03:30` local.
- **Ambiguous** — the **earlier** of the two instants. `01:30` resolves to
  `05:30Z`, the one before the clocks go back.

Series spacing in `days`, `weeks` and `months` is **calendar** arithmetic in the
schedule's zone, so a 10:00 drip keeps landing at 10:00 local across a
transition rather than walking by an hour. `minutes` and `hours` are real
elapsed time, not calendar — two hours is two hours even where the clocks
change.

---

## Conditions

The condition is a [contact filter](../contact-filter.md) — the same DSL as
`contacts.list({ filter })`, a saved `Segment`, and a CRM trigger's `filters`.
Nothing new to learn, and a condition that selects a contact in a segment selects
them here too.

```ts
conditions: {
  conditions: [
    { field_id: 'stage', field_type: 'dropdown', condition: 'equal to', value: 'Lead' },
  ],
}
```

| Field | Notes |
| --- | --- |
| `field_id` | The custom field's **slug**, not its id. Also accepts `tags`, `SYSTEM_LAST_SEEN`, `SYSTEM_CREATED_ON`, `SYSTEM_IDENTIFIER`, `SYSTEM_PROFILE_NAME`. |
| `field_type` | Must match the field's real data type. A pairing with no meaning — `greater than` on a dropdown — is a `422`. Use `string` for an untyped value. |
| `condition` | One of the 23 comparisons. |
| `value` | Scalar for text and number; a JSON array string for date comparisons. |
| `operator` | `null` on the first entry, `and` / `or` after. **`and` binds tighter than `or`.** |

Several conditions — still a lead, and not tagged do-not-contact:

```ts
conditions: {
  conditions: [
    { field_id: 'stage', field_type: 'dropdown', condition: 'equal to', value: 'Lead' },
    { operator: 'and', field_id: 'tags', field_type: 'string',
      condition: 'not equal to', value: [doNotContactTagId] },
  ],
}
```

Omit `conditions` and the message always sends.

`REFERRAL_ID` is **not** available here — it resolves against a collection the
scheduler does not read. Using it is a `422` at schedule time rather than a
silent pass.

### `on_condition_fail`

| Value | Effect | Default for |
| --- | --- | --- |
| `skip` | This occurrence only, marked `skipped`. Later ones are still checked, so a contact who leaves and re-enters the condition resumes receiving. | `create` |
| `cancel_series` | This occurrence and every later one. | `createSeries`, `createRepeating` |

`skip` suits "don't message them on a day they already replied". `cancel_series`
suits "they converted, we're done" — and is the default for a series precisely
because a converted lead should drop out for good, rather than re-entering if
someone edits their stage back later.

### Guards you don't have to write

Independently of your condition, a send is refused when the contact is trashed,
`chat_metadata.blocked.outgoing` is set, or the channel has been disabled. Those
end `failed` with a `result.error`, not `skipped` — they are platform state, not
a condition you chose.

---

## list

```ts
crm.scheduledMessages.list(query?: Partial<ListScheduledMessagesQuery>): Promise<Paginated<ScheduledMessage>>
```

`GET /v1/audience/scheduled-messages` · `messages:read` · **200**

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `page` | number | `1` | 1-based. |
| `rows` | number | `25` | 1–100. |
| `search` | string | — | Matches the title. |
| `contact` | ObjectId | — | Everything queued for one person. |
| `series` | ObjectId | — | One drip's occurrences. |
| `status` | status | — | See the table above. |
| `channel` | ObjectId | — | |

Soonest first among `pending`; newest first among the rest.

```ts
// What is still waiting to go out for this contact
const { data } = await crm.scheduledMessages.list({ contact: contactId, status: 'pending' });

// What stood down, and why
const skipped = await crm.scheduledMessages.list({ status: 'skipped' });
```

---

## get

```ts
crm.scheduledMessages.get(id: string): Promise<ScheduledMessage>
```

`GET /v1/audience/scheduled-messages/:id` · `messages:read` · **200**

One occurrence, with its `result` if it has reached a terminal status. `404
not_found` if it does not belong to the caller.

---

## create

```ts
crm.scheduledMessages.create(input: CreateScheduledMessageInput): Promise<ScheduledMessage>
```

`POST /v1/audience/scheduled-messages` · `messages:write` · **201**

One message, one time. `series` comes back `null` and `occurrence` is `1`.

### Body

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `channel` | ObjectId | yes | Channel to send on. |
| `contact` | `{ id }` | yes | The identifier is resolved from the contact's `profile` at send time, so a number corrected in between is the one used. |
| `timezone` | string | yes | IANA zone. See [Time and timezone](#time-and-timezone). |
| `scheduled_at` | ISO string | yes | Must be in the future. |
| `content` | `MessageContent` | yes | The same open body `inbox.messages.send` takes — `{ type }` pinned, the body under a key of that name. |
| `context` | object | no | Provider context: a replied-to id, forwarding flags. |
| `title` | string | no | Shown in the list. Defaults to `'Untitled'`. |
| `conditions` | `ContactFilter` | no | Omit to always send. |
| `on_condition_fail` | `'skip' \| 'cancel_series'` | no | Defaults to `skip`. |

```ts
await crm.scheduledMessages.create({
  title: 'Pricing follow-up',
  channel: channelId,
  contact: { id: contactId },
  timezone: 'Asia/Kolkata',
  scheduled_at: '2026-10-15T10:00:00',          // 10:00 IST
  content: { type: 'text', text: { body: 'Following up on the pricing.' } },
  conditions: {
    conditions: [
      { field_id: 'stage', field_type: 'dropdown', condition: 'equal to', value: 'Lead' },
    ],
  },
});
```

`422` when `scheduled_at` is in the past, `timezone` is not an IANA zone, a
condition names a field type its comparison cannot apply to, or the body is free
text and the send falls outside the channel's reply window.

---

## createSeries

```ts
crm.scheduledMessages.createSeries(input: CreateScheduledSeriesInput): Promise<ScheduledMessageSeries>
```

`POST /v1/audience/scheduled-messages/series` · `messages:write` · **201**

A sequence whose steps carry different copy.

### Body

Everything `create` takes except `scheduled_at`, `content` and `context`, plus:

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `starts_at` | ISO string | yes | The first step's moment. Every `after` is measured from here. |
| `steps` | `ScheduledMessageStep[]` | yes | 1–365. Sorted by `after` before expansion, so declaration order does not matter. |

```ts
interface ScheduledMessageStep {
  /** Cumulative from `starts_at`, never relative to the previous step. */
  after: { value: number; unit: 'minutes' | 'hours' | 'days' | 'weeks' | 'months' };
  content: MessageContent;
  context?: JsonObject;
  /** Checked in addition to the series condition — both must pass. */
  conditions?: ContactFilter | null;
}
```

```ts
const series = await crm.scheduledMessages.createSeries({
  title: 'Lead nurture — 2 weeks',
  channel: channelId,
  contact: { id: contactId },
  timezone: 'Asia/Kolkata',
  starts_at: '2026-10-13T10:00:00',
  conditions: {
    conditions: [
      { field_id: 'stage', field_type: 'dropdown', condition: 'equal to', value: 'Lead' },
    ],
  },
  on_condition_fail: 'cancel_series',
  steps: [
    { after: { value: 0,  unit: 'days' }, content: introTemplate },
    { after: { value: 3,  unit: 'days' }, content: caseStudyTemplate },
    { after: { value: 6,  unit: 'days' }, content: pricingTemplate },
    { after: { value: 9,  unit: 'days' }, content: demoTemplate },
    { after: { value: 12, unit: 'days' }, content: lastCallTemplate },
  ],
});

series.occurrences.length;                  // 5
series.occurrences[1].scheduled_at_local;   // '2026-10-16T10:00:00'
```

**`after` is cumulative from `starts_at`.** Changing step 2's delay therefore
leaves steps 3–5 exactly where they were; relative offsets would shift all of
them, which is almost never what an edit means.

### Response

```ts
interface ScheduledMessageSeries {
  series: string;
  title: string;
  contact: string;
  channel: string;
  timezone: string;
  conditions: ContactFilter | null;
  on_condition_fail: 'skip' | 'cancel_series';
  /** In send order. One row per message, each independently cancellable. */
  occurrences: ScheduledMessage[];
}
```

---

## createRepeating

```ts
crm.scheduledMessages.createRepeating(input: CreateRepeatingScheduleInput): Promise<ScheduledMessageSeries>
```

`POST /v1/audience/scheduled-messages/series` · `messages:write` · **201**

The same route, for when every occurrence sends the same message.

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `starts_at` | ISO string | yes | First occurrence. |
| `repeat.every` | number | yes | At least 1. |
| `repeat.unit` | unit | yes | `minutes` … `months`. |
| `repeat.until` | ISO string | yes | **Inclusive** end. |
| `content` | `MessageContent` | yes | Sent by every occurrence. |

```ts
await crm.scheduledMessages.createRepeating({
  title: 'Weekly check-in',
  channel: channelId,
  contact: { id: contactId },
  timezone: 'Asia/Kolkata',
  starts_at: '2026-10-13T10:00:00',
  repeat: { every: 3, unit: 'days', until: '2026-10-27T10:00:00' },
  content: nudgeTemplate,
  conditions: { conditions: [stillALead] },
});
// → 5 occurrences: 13th, 16th, 19th, 22nd, 25th
```

`until` is inclusive, so the last occurrence is the final one at or before it.
`422` if the expansion would exceed 365 occurrences.

Once created, a repeating schedule and a stepped one are indistinguishable — both
are just rows.

---

## reschedule

```ts
crm.scheduledMessages.reschedule(id: string, input: RescheduleMessageInput): Promise<ScheduledMessage>
```

`PATCH /v1/audience/scheduled-messages/:id` · `messages:write` · **200**

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `scheduled_at` | ISO string | yes | Must be in the future. |
| `timezone` | string | no | Re-reads it in a different zone. Defaults to the stored one. |
| `title` | string | no | |

Only a `pending` occurrence. Rescheduling one that is already `sent`, `skipped`
or `cancelled` is a `409 conflict` — not a silent no-op.

Moving one occurrence does **not** move the rest of its series.

```ts
await crm.scheduledMessages.reschedule(id, { scheduled_at: '2026-10-16T14:00:00' });
```

---

## cancel

```ts
crm.scheduledMessages.cancel(id: string): Promise<ScheduledMessage>
```

`DELETE /v1/audience/scheduled-messages/:id` · `messages:write` · **200**

Stands down one occurrence and answers with the row at `status: 'cancelled'`. The
row is kept rather than deleted, so a message that did not send still shows why.

The other occurrences in its series stay queued — use
[`cancelSeries`](#cancelseries) to stop the whole drip.

---

## cancelSeries

```ts
crm.scheduledMessages.cancelSeries(series: string): Promise<CancelSeriesResult>
```

`DELETE /v1/audience/scheduled-messages/series/:series` · `messages:write` · **200**

```ts
{ series: string, cancelled: number }
```

Cancels every `pending` occurrence. Anything already sent is untouched and not
counted. Idempotent — a second call cancels nothing and answers `0`.

**Usually you do not need this.** If the series carries a condition, changing the
contact so it no longer matches is the better way to stop a drip: the reason ends
up on the record, and it works for every contact in the same sequence rather than
one series at a time.

---

## sendNow

```ts
crm.scheduledMessages.sendNow(id: string): Promise<ScheduledMessage>
```

`POST /v1/audience/scheduled-messages/:id/send-now` · `messages:write` · **200**

Brings a `pending` occurrence forward to immediately.

**The condition is still checked** — that is the point of it. A send-now on a
contact who no longer matches comes back `skipped`, not `sent`. Cancel the
occurrence if you want it gone regardless.

It moves the occurrence rather than copying it, so the original time no longer
fires and the contact receives one message.

`409 conflict` if the occurrence is not `pending`.
