Scheduled Messages

Scheduled messages let a user write a message now and have it sent later. The user picks a time, and Stream sends the message to the channel at that time on the user's behalf. Until then the user can edit the message, move it to another time, send it right away, or cancel it.

A scheduled message is private until it is sent. Other channel members see nothing, receive no events and get no push notifications until the message is actually sent. When it is sent, it is a normal message: it goes through the same checks, moderation, webhooks and push notifications as a message sent at that moment.

Scheduled messages are built for one user scheduling one message into one channel, direct message or thread. To send the same message to many users or channels, use Campaigns instead.

Enabling scheduled messages

Scheduled messages are an app-level setting that is off by default. To enable them for your app, contact support.

Permissions

Scheduling a message requires the ScheduleMessage permission in addition to the permissions needed to send the same message right away (CreateMessage, CreateReply for thread replies, attachment, mention and pin permissions, and so on). By default, ScheduleMessage is granted to the same roles as CreateMessage. See the permissions reference for the default grants.

To show or hide a "schedule" option in your UI, check the schedule-message capability in the channel's own_capabilities. The capability is only returned when scheduled messages are enabled for the app.

A user without the ScheduleMessage permission gets the usual permission error: HTTP 403 with error code 17.

Limits

Limit Default Channel config field
Pending scheduled messages per user in a single channel 10 scheduled_messages_max_per_channel
Pending scheduled messages per user across the app 100 scheduled_messages_max_per_user
Earliest send time 1 minute scheduled_messages_min_lead_time_seconds
Latest send time 120 days scheduled_messages_max_lead_time_seconds
  • A pending scheduled message is one with status scheduled or sending. Failed and deleted scheduled messages don't count toward the limits.
  • The earliest send time is fixed at 1 minute and cannot be changed. The other values are defaults that Stream can change for your app.
  • A future send time closer than 1 minute is moved to 1 minute from now, rounded up to the minute. It is never rejected.
  • A send time later than the latest send time is rejected with error code 116.

The app's limits are returned in every channel's config, in the fields listed above, so your UI can respect them before the API refuses a request, for example to bound a date picker or disable the schedule option when the user has reached the limit. The fields are only present when scheduled messages are enabled for the app. The values are the same for every channel of the app: they are app settings, not channel type settings.

Scheduling a message

To schedule a message, send it with scheduled_at set to the time it should be sent. Times are in UTC.

val channelClient = client.channel("messaging", "general")
val scheduledAt = Date().apply { time += 24.hours.inWholeMilliseconds } // In 24 hours

// Show the schedule option only when the user can schedule in the channel.
// `channel` is the Channel returned by a channel query, for example
// channelClient.query(...).
if (ChannelCapabilities.SCHEDULE_MESSAGE in channel.ownCapabilities) {
    showScheduleOption()
}

// Saves the message on the device, and the SDK sends it to the server in the
// background once its attachments are uploaded and the device is online. Until
// then its status is ScheduledMessageStatus.PreparingToSchedule. The message is
// not in the channel until it is sent. The SDK sends it again by itself when
// needed, so there is no need to schedule the same message again.
val message = Message(
    text = "Happy birthday!",
    extraData = mapOf("priority" to "high"),
)
channelClient.scheduleMessage(message, scheduledAt).enqueue { result ->
    // A failure means the message was refused on the device and not saved: a
    // slash command in a channel with commands, a quote of a deleted message, a
    // time later than the latest send time, a message over the channel or user
    // limit, no connected user, or a message ID that is already scheduled on the
    // device. The limits count only pending messages whose time has not passed.
    if (result is Result.Failure) {
        println("Couldn't schedule the message: ${result.value.message}")
    }
}

// A thread reply: set parentId on the message
val reply = Message(text = "See you there!", parentId = parentMessageId)
channelClient.scheduleMessage(reply, scheduledAt).enqueue { /* ... */ }

// The server's answer updates client.scheduledMessages, which holds the current
// user's scheduled messages. It is updated whenever one of them changes, on the
// device or from the server. This flow has the ones in the channel, without
// thread replies.
lifecycleScope.launch {
    client.scheduledMessages(cid = "messaging:general").collect { scheduledMessages ->
        for (scheduledMessage in scheduledMessages) {
            when (val failure = scheduledMessage.failure) {
                // The server refused the change, for example because the
                // channel limit was reached. The message describes it.
                is ScheduledMessageFailure.ServerRejectedScheduling ->
                    println("Couldn't schedule ${scheduledMessage.id}: ${failure.message}")
                // The server couldn't send it at its time, for example because
                // the user was banned. It can only be deleted.
                is ScheduledMessageFailure.ServerFailedPublishing ->
                    println("Couldn't send ${scheduledMessage.id}: ${failure.reason?.value ?: "unknown"}")
                // An attachment upload or the request failed on the device.
                is ScheduledMessageFailure.LocalDeviceFailedScheduling ->
                    println("Couldn't schedule ${scheduledMessage.id} from the device: ${failure.reason.value}")
                else -> Unit
            }
        }
    }
}

The response contains scheduled_message, and nothing is added to the channel. The response's message field is only a preview of what will be sent: it is not in the channel, and its id is the ID of the scheduled message, not the ID the sent message will have. Don't add it to the channel's message list or render it as sent.

Custom data is set on a scheduled message the same way as on a regular message, and the sent message carries it like any other message.

To schedule a thread reply, set parent_id on the message, as you would when replying in a thread.

Send time

Messages are sent on whole minutes. A future scheduled_at is moved to the first whole minute (UTC, seconds set to zero) that is not earlier than the requested time and at least 1 minute from now. A message is never sent earlier than requested.

Requested scheduled_at (now is 10:20:00) Stored scheduled_at
10:30:00 10:30:00
10:30:20 10:31:00
10:20:30 10:21:00
10:20:00 or earlier Sent right away

A scheduled_at that is now or in the past sends the message right away: the response is a normal send message response, with the sent message and no scheduled_message.

Retrying a schedule request

If you set message.id when scheduling, sending the same request again returns the existing scheduled message instead of scheduling a second one, so it is safe to retry after a timeout or replay after the device was offline. If the message was already sent, the retry fails with error code 123: treat it as success. If the user canceled it, a retry with a time that is now or in the past fails with error code 124, so the canceled message is not sent.

Updating a scheduled message

You can change the content of a scheduled message, its send time, or both. A new message replaces the scheduled message as a whole, so send every field you want to keep. Only messages with status scheduled can be updated.

val newScheduledAt = Date().apply { time += 23.hours.inWholeMilliseconds } // In 23 hours

// Like scheduling, saves the change on the device and sends it to the server in
// the background. The new message replaces the whole content, so pass back the
// scheduled message's content with your changes. A thread reply keeps its
// parentId this way.
client.updateScheduledMessage(
    id = scheduledMessage.id,
    message = scheduledMessage.message.copy(text = "Happy birthday, John!"),
    scheduledAt = newScheduledAt, // Optional: null keeps the send time
).enqueue { result ->
    // A failure means the change was refused on the device and not saved: the
    // message is not in client.scheduledMessages (for example, not queried yet
    // or just deleted), a slash command in a channel with commands, a quote of a
    // deleted message, or a new time later than the latest send time.
    if (result is Result.Failure) {
        println("Couldn't update the scheduled message: ${result.value.message}")
    }
}

// Only the send time. Refused on the device when the message is not in
// client.scheduledMessages, for a time later than the latest send time, or for
// a quote of a deleted message.
client.rescheduleMessage(id = scheduledMessage.id, scheduledAt = newScheduledAt).enqueue { /* ... */ }

An update runs the same content and permission checks as scheduling, but not the limits.

A new scheduled_at is rounded up to the minute and checked against the latest send time, as when scheduling. Unlike scheduling, an update never sends the message: a scheduled_at that is now or in the past fails with error code 115 (scheduled_at_too_soon). To send a scheduled message right away, use send now.

Sending a scheduled message now

To send a scheduled message right away instead of waiting for its time, use send now. The send happens in the background: the response returns the scheduled message, and the scheduled_message.sent or scheduled_message.failed event reports the outcome. Only messages with status scheduled can be sent now.

// Marks the message on the device and sends it once its changes and attachments
// are on the server. The message leaves client.scheduledMessages once it is sent.
client.sendScheduledMessageNow(id = scheduledMessageId).enqueue { result ->
    // A failure means it was refused on the device: the message is not in
    // client.scheduledMessages (for example, not queried yet or just deleted),
    // or its quoted message was deleted. Then remove the quote and try again.
    if (result is Result.Failure) {
        println("Couldn't send the scheduled message: ${result.value.message}")
    }
}

Deleting a scheduled message

Deleting a scheduled message cancels it: it will not be sent, and the response returns it with status canceled. Deleting a failed message removes it, and the response returns it as it was, with status failed. After a delete, the scheduled message no longer appears anywhere.

// The message leaves client.scheduledMessages right away, and is deleted on the
// server once the device is online. A message the server never received is only
// deleted on the device, and one whose scheduling request is in flight is also
// deleted on the server. If the server can't delete it, the message comes back
// with a failure, and resendScheduledMessage deletes it again. An ID that is not
// in client.scheduledMessages is deleted on the server directly, and the call
// waits for the server.
client.deleteScheduledMessage(id = scheduledMessageId).enqueue { /* ... */ }

Deleting the user or the channel also affects their scheduled messages:

  • Hard or pruning user delete: the user's scheduled messages are removed.
  • Soft user delete or deactivation: the scheduled messages are kept, and fail with the user_deleted reason at their send time.
  • Channel delete: scheduled messages that were not sent yet fail with the channel_deleted reason, and their owners get scheduled_message.failed. After a soft delete they are kept for 7 days like other failed scheduled messages; a hard delete removes them. Messages that were already sending are removed without an event.

Querying scheduled messages

Query scheduled messages to list a user's pending (scheduled and sending) and failed scheduled messages. Pending messages come first, then failed ones, each ordered by scheduled_at. Client-side, the query returns the current user's scheduled messages. Server-side, user_id is required.

You can filter by channel (cid) and by status (one or more of scheduled, sending and failed). The only supported sort is scheduled_at ascending, which is also the default. The page size defaults to 20 and can be at most 100.

// All the user's scheduled messages, across channels. The SDK asks for 100 per
// page by default, the maximum. The results are also saved in
// client.scheduledMessages.
lifecycleScope.launch {
    val (scheduledMessages, next) = client.queryScheduledMessages().await().getOrThrow()

    // Next page. next is null when the first page holds all of them.
    next?.let { client.queryScheduledMessages(next = it).await() }
}

// Only one channel, and only the failed ones
client.channel("messaging", "general")
    .queryScheduledMessages(statuses = setOf(ScheduledMessageQueryStatus.Failed))
    .enqueue { /* ... */ }

A user can have up to 100 pending scheduled messages plus their failed ones, so a single page may not hold all of them. Follow next until it is empty, and remove duplicates by id across pages, because a message can move between pages when its time changes.

Including scheduled messages in channel state

You can load the user's scheduled messages together with the channels themselves. Set include_scheduled_messages when watching or querying a channel, or when querying channels, and each channel's state contains scheduled_messages: the user's scheduled, sending and failed messages in that channel, or an empty list when there are none.

// One channel: channel.scheduledMessages holds the user's scheduled messages in
// it. They are also saved in client.scheduledMessages. When the server returns
// them, client.scheduledMessages also drops the ones of the channel that the
// server no longer has.
val request = QueryChannelRequest()
    .withWatch()
    .withState()
    .apply { includeScheduledMessages = true }
client.channel("messaging", "general").query(request).enqueue { result ->
    if (result is Result.Success) {
        // An empty list when there are none, and null when the server left the
        // field out. Then use the query instead.
        val scheduledMessages: List<ScheduledMessage>? = result.value.scheduledMessages
    }
}

// A page of channels
val channelsRequest = QueryChannelsRequest(
    filter = Filters.`in`("members", listOf(currentUserId)),
    limit = 30,
).apply { includeScheduledMessages = true }
client.queryChannels(channelsRequest).enqueue { /* ... */ }

scheduled_messages is always the complete list, never a partial one. When the complete list can't be returned, the field is left out instead, and you should use the query for that channel. A missing field means "not loaded", not "none". This happens when:

  • the feature is off for the app;
  • the list would hold more than 100 scheduled messages. Pending messages are limited to 10 per channel, so this only happens when the user also has many failed messages. When querying channels, the 100 applies to all channels of the page together, and the field is then left out on every channel of the page;
  • the scheduled messages could not be loaded.

Keeping scheduled messages in sync on the client

The client-side SDKs keep the current user's scheduled messages for you. They load them with one query and then keep them up to date from the scheduled_message.* events: created and updated messages are added, failed ones are marked as failed, and sent or deleted ones are removed. They also take the scheduled_messages of channels watched or queried with include_scheduled_messages, and the scheduled_message of schedule responses.

// client.scheduledMessages keeps the current user's scheduled messages. Changes
// made on the device show right away. With offline storage enabled, they are
// also kept across app restarts, and changes left pending are sent at the next
// start. Without a connection, changes wait and are sent once online.

// Load them, and load them again each time the connection comes back: the SDK
// doesn't query again by itself after a reconnect. A query of every channel and
// status that returns a single page also removes the ones the server no longer
// has, for example the ones sent while the device was offline.
lifecycleScope.launch {
    client.clientState.connectionState
        .filter { it == ConnectionState.Connected }
        .collect {
            if (!client.hasLoadedAllScheduledMessages.value) {
                client.queryScheduledMessages().await()
            }
        }
}

// Pending ones first, then failed ones, each ordered by scheduledAt
val all: StateFlow<List<ScheduledMessage>> = client.scheduledMessages
val forChannel = client.scheduledMessages(cid = channel.cid) // excludes thread replies
val forThread = client.scheduledMessages(cid = channel.cid, parentId = parentMessageId)

// True once the query above loaded all of them, so an empty list means none.
// It becomes false when the connection is lost, until the next such query.
// A channel list queried with includeScheduledMessages is also refreshed after
// a reconnect, but only for its channels, and it doesn't set this flag.
val hasLoadedAll: StateFlow<Boolean> = client.hasLoadedAllScheduledMessages

// When a change can't reach the server, the status is Failed and `failure` says
// why. The SDK sends a change again on its own only once, when the server
// answers with a conflict (error code 122). Send the change again when it can
// be retried, otherwise change or delete the message.
for (scheduledMessage in client.scheduledMessages.value) {
    if (scheduledMessage.status == ScheduledMessageStatus.Failed && scheduledMessage.failure?.isRetryable == true) {
        // Uploads failed attachments again, then sends the changes
        client.resendScheduledMessage(scheduledMessage.id).enqueue { /* ... */ }
    }
}

The scheduled message object

Field Type Description
id string ID of the scheduled message. Not the ID of the message once it is sent
cid string The channel the message will be sent to
user object The user who scheduled the message
message object The message that will be sent: text, attachments, parent_id, mentioned_users (user IDs), custom data and more
scheduled_at date When the message will be sent
status string See Statuses
failure_reason string Why the send failed. Only set when status is failed. See Failure reasons
channel object The channel's cid, type, id, name and image. Only set in query results
created_at date When the message was scheduled
updated_at date When the scheduled message was last changed

In the scheduled message's message, mentioned_users holds the user IDs from the request, not user objects. Custom data behaves exactly as on regular messages: set it on the message the same way when scheduling or updating, and it comes back in the same shape your SDK uses for regular messages.

Statuses

Status Meaning Allowed actions
scheduled Waiting for its send time Update, send now, delete
sending Being sent, or waiting to retry after a temporary send error None
failed The send failed. failure_reason says why Delete
canceled Deleted by the user. Only returned by the delete call and the scheduled_message.deleted event None
sent Sent. Only reported by the scheduled_message.sent event None

Once a scheduled message is sent, it no longer exists as a scheduled message: it is a normal message in the channel. Failed scheduled messages are kept for 7 days so the user can see what went wrong, and are then removed.

Failure reasons

Every check runs again when the message is sent, including moderation and the before message send webhook, which don't run when it is scheduled. Slow mode doesn't apply. So a message that was valid when it was scheduled can still fail with one of these reasons.

Reason Meaning
banned The user is banned from the channel or the app
no_permission The user no longer has permission to send this message
channel_frozen The channel is frozen. Only for messages scheduled client-side: like a live send, a message scheduled server-side is not blocked by a freeze
channel_deleted The channel was deleted
user_deleted The user was deleted or deactivated
moderation_blocked Moderation blocked the message
hook_rejected The before message send webhook rejected the message
expired The message could not be sent in time. See below
invalid_message The message is no longer valid, for example because the app's message settings changed or a quoted message was deleted
pending_not_supported The channel marks new messages as pending, and the request did not set pending: false
internal_error The send failed 3 times because of a temporary error

A message expires when it could not be sent within 1 hour of its scheduled time, for example during an outage. When many messages are due at the same minute, the ones that were queued on time are still sent after that hour, but never more than 24 hours late.

failure_reason only ever holds one of the values above, so you can switch on it to show your own text.

Events

scheduled_message.* events are sent only to the connections of the user who scheduled the message, never to other channel members. Only scheduled_message.sent and scheduled_message.failed are also sent to webhooks.

Event Trigger Webhook
scheduled_message.created A message was scheduled No
scheduled_message.updated A scheduled message was updated or sent now No
scheduled_message.deleted A scheduled message was canceled or a failed one removed No
scheduled_message.sent A scheduled message was sent Yes
scheduled_message.failed A scheduled message failed to send Yes

Every event carries cid, user and scheduled_message. scheduled_message.sent reports the status as sent and also carries message_id, the ID of the message that was sent to the channel. The sent message itself is delivered like any other message, with message.new to the channel members.

Messages that expire, or fail because their channel was deleted, also send scheduled_message.failed. If the user who scheduled the message was deleted, the scheduled_message.sent and scheduled_message.failed webhooks are still sent, with the deleted user in user.

// Also ScheduledMessageCreatedEvent, ScheduledMessageUpdatedEvent and
// ScheduledMessageDeletedEvent. The SDK already applies them to
// client.scheduledMessages.
// With a LifecycleOwner, such as an Activity, events arrive only while it is
// started, and the listener is removed when it is destroyed. Without one, keep
// the returned Disposable and call dispose() when you are done.
client.subscribeFor(
    lifecycleOwner,
    ScheduledMessageSentEvent::class.java,
    ScheduledMessageFailedEvent::class.java,
) { event ->
    when (event) {
        is ScheduledMessageSentEvent ->
            println("${event.scheduledMessage.id} was sent as ${event.messageId}")
        is ScheduledMessageFailedEvent -> {
            val failure = event.scheduledMessage.failure as? ScheduledMessageFailure.ServerFailedPublishing
            println(failure?.reason?.value ?: "unknown")
        }
        else -> Unit
    }
}

Errors

Scheduled message errors set exception_fields.reason to the name in the table below, so you can handle them without hardcoding the numeric code. Errors caused by a limit also carry the limit in exception_fields, as a string, so you can write your own error text.

Code Reason HTTP status Meaning Extra exception_fields
114 scheduled_messages_disabled 400 Scheduled messages are not enabled for the app
115 scheduled_at_too_soon 400 An update set scheduled_at to now or a past time. Only returned when updating min_lead_time_seconds
116 scheduled_at_too_far 400 scheduled_at is later than the app's latest send time (120 days by default) max_lead_time_seconds
117 scheduled_limit_channel 400 The user has too many pending scheduled messages in this channel limit
118 scheduled_limit_user 400 The user has too many pending scheduled messages limit
119 scheduled_message_id_taken 400 The scheduled message ID belongs to another user's or channel's message
120 scheduled_message_not_editable 400 The scheduled message failed to send and can only be deleted
121 scheduled_message_sending 409 The scheduled message is being sent and cannot change
122 scheduled_message_conflict 409 Another change to the scheduled message happened first. Reload and retry
123 scheduled_message_already_sent 400 A message with this ID was already sent. When retrying a schedule request, treat as success
124 scheduled_message_canceled 400 The scheduled message with this ID was canceled, so a replay with a past time is not sent

For example:

{
  "code": 117,
  "message": "SendMessage failed with error: \"you can schedule at most 10 messages in this channel\"",
  "exception_fields": { "reason": "scheduled_limit_channel", "limit": "10" }
}

Updating, sending now or deleting a scheduled message that does not exist, was already sent or canceled, or belongs to another user (client-side) returns HTTP 404.

REST endpoints

Action Endpoint
Schedule a message POST /channels/{type}/{id}/message with scheduled_at
Query scheduled messages POST /scheduled_messages/query
Update a scheduled message PATCH /scheduled_messages/{id}
Send a scheduled message now POST /scheduled_messages/{id}/send_now
Delete a scheduled message DELETE /scheduled_messages/{id}