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
scheduledorsending. 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.
let cid = ChannelId(type: .messaging, id: "general")
let scheduledAt = Date().addingTimeInterval(24 * 60 * 60) // In 24 hours
// 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 .preparingToSchedule. The message is not in the channel
// until it is sent.
let channelController = chatClient.channelController(for: cid)
channelController.delegate = self
channelController.scheduleMessage(
text: "Happy birthday!",
scheduledAt: scheduledAt,
extraData: ["priority": .string("high")]
) { result in
// An error means the message was refused on the device and not saved: a
// slash command, a deleted quoted message, a time later than the latest
// send time, or a message over the channel or user limit.
if case let .failure(error) = result {
print("Couldn't schedule the message: \(error)")
}
}
// A thread reply, with the message controller of the parent message
let messageController = chatClient.messageController(cid: cid, messageId: parentMessageId)
messageController.scheduleReply(text: "See you there!", scheduledAt: scheduledAt)
// The server's answer updates channel.scheduledMessages, which holds the user's
// scheduled messages in the channel, and didUpdateChannel is called whenever
// one of them changes, on the device or from the server.
func channelController(
_ channelController: ChatChannelController,
didUpdateChannel channel: EntityChange<ChatChannel>
) {
for scheduledMessage in channel.item.scheduledMessages {
switch scheduledMessage.failure {
case let .serverRejectedScheduling(rejection):
// The server refused the change, for example because the channel
// limit was reached. The message describes it, with the limit.
print("Couldn't schedule \(scheduledMessage.id): \(rejection.message)")
case let .serverFailedPublishing(failure):
// The server couldn't send it at its time, for example because the
// user was banned. It can only be deleted.
print("Couldn't send \(scheduledMessage.id): \(failure.reason?.rawValue ?? "unknown")")
default:
break
}
}
}let cid = ChannelId(type: .messaging, id: "general")
let scheduledAt = Date().addingTimeInterval(24 * 60 * 60) // In 24 hours
// Returns once the message is saved 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 .preparingToSchedule. The message is not in
// the channel until it is sent.
// It throws when the message is refused on the device and not saved: a slash
// command, a deleted quoted message, a time later than the latest send time, or
// a message over the channel or user limit.
let chat = chatClient.makeChat(for: cid)
let scheduledMessage = try await chat.scheduleMessage(
with: "Happy birthday!",
scheduledAt: scheduledAt,
extraData: ["priority": .string("high")]
)
// A thread reply
try await chat.scheduleReply(to: parentMessageId, text: "See you there!", scheduledAt: scheduledAt)
// The server's answer updates chat.state.channel?.scheduledMessages, which
// holds the user's scheduled messages in the channel. It is updated whenever
// one of them changes, on the device or from the server.
chat.state.$channel
.sink { channel in
for scheduledMessage in channel?.scheduledMessages ?? [] {
switch scheduledMessage.failure {
case let .serverRejectedScheduling(rejection):
// The server refused the change, for example because the
// channel limit was reached. The message describes it.
print("Couldn't schedule \(scheduledMessage.id): \(rejection.message)")
case let .serverFailedPublishing(failure):
// The server couldn't send it at its time, for example because
// the user was banned. It can only be deleted.
print("Couldn't send \(scheduledMessage.id): \(failure.reason?.rawValue ?? "unknown")")
default:
break
}
}
}
.store(in: &cancellables)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.
let newScheduledAt = Date().addingTimeInterval(23 * 60 * 60) // In 23 hours
// Like scheduling, saves the change on the device and sends it to the server in
// the background. The server's answer updates the message in the scheduled
// message list.
channelController.updateScheduledMessage(
id: scheduledMessageId,
text: "Happy birthday, John!",
scheduledAt: newScheduledAt
) { result in
// An error means the change was refused on the device and not saved: a
// slash command, a deleted quoted message, or a time later than the latest
// send time.
if case let .failure(error) = result {
print("Couldn't update the scheduled message: \(error)")
}
}
// Only the send time
channelController.rescheduleMessage(id: scheduledMessageId, scheduledAt: newScheduledAt)
// A thread reply, with the message controller of the parent message
messageController.updateScheduledReply(id: scheduledMessageId, text: "See you at 8!")let newScheduledAt = Date().addingTimeInterval(23 * 60 * 60) // In 23 hours
// Like scheduling, returns once the change is saved on the device and sends it
// to the server in the background. The server's answer updates the message in
// the scheduled message list.
// It throws when the change is refused on the device and not saved: a slash
// command, a deleted quoted message, or a time later than the latest send time.
try await chat.updateScheduledMessage(
id: scheduledMessageId,
text: "Happy birthday, John!",
scheduledAt: newScheduledAt
)
// Only the send time
try await chat.rescheduleMessage(id: scheduledMessageId, scheduledAt: newScheduledAt)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.
// With the channel controller or the scheduled message list controller.
// Marks the message on the device and sends it once its changes are on the
// server. The message leaves the scheduled message list once it is sent.
channelController.sendScheduledMessageNow(id: scheduledMessageId) { error in
// An error means it was refused on the device, for example because its
// quoted message was deleted. Remove the quote and try again.
if let error {
print("Couldn't send the scheduled message: \(error)")
}
}// With Chat or ScheduledMessageList.
// Marks the message on the device and sends it once its changes are on the
// server. The message leaves the scheduled message list once it is sent.
// It throws when it is refused on the device, for example because its quoted
// message was deleted. Remove the quote and try again.
try await chat.sendScheduledMessageNow(id: scheduledMessageId)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.
// With the channel controller or the scheduled message list controller. Unlike
// the other changes, deleting waits for the server.
channelController.deleteScheduledMessage(id: scheduledMessageId) { error in
if let error {
print("Failed to delete the scheduled message: \(error)")
}
}// With Chat or ScheduledMessageList. Unlike the other changes, deleting waits
// for the server.
try await chat.deleteScheduledMessage(id: scheduledMessageId)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_deletedreason at their send time. - Channel delete: scheduled messages that were not sent yet fail with the
channel_deletedreason, and their owners getscheduled_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 alreadysendingare 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 delegate is called
// with controller.scheduledMessages whenever they change.
let controller = chatClient.scheduledMessageListController()
controller.delegate = self
controller.synchronize()
// Next page
if !controller.hasLoadedAllScheduledMessages {
controller.loadMoreScheduledMessages()
}
// Only one channel
let channelQuery = ScheduledMessageListQuery(
filter: .equal(.cid, to: ChannelId(type: .messaging, id: "general"))
)
let oneChannelController = chatClient.scheduledMessageListController(query: channelQuery)
oneChannelController.delegate = self
oneChannelController.synchronize()// All the user's scheduled messages, across channels
let scheduledMessageList = chatClient.makeScheduledMessageList()
try await scheduledMessageList.get()
print(scheduledMessageList.state.scheduledMessages)
// Next page
try await scheduledMessageList.loadMoreScheduledMessages()
// Only one channel
let channelQuery = ScheduledMessageListQuery(
filter: .equal(.cid, to: ChannelId(type: .messaging, id: "general"))
)
let oneChannelList = chatClient.makeScheduledMessageList(with: channelQuery)
try await oneChannelList.get()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: channelController.channel?.scheduledMessages holds the user's
// scheduled messages in it
var query = ChannelQuery(cid: ChannelId(type: .messaging, id: "general"))
query.includeScheduledMessages = true
let channelController = chatClient.channelController(for: query)
channelController.synchronize()
// A page of channels
var channelListQuery = ChannelListQuery(filter: .containMembers(userIds: [currentUserId]))
channelListQuery.includeScheduledMessages = true
let channelListController = chatClient.channelListController(query: channelListQuery)
channelListController.synchronize()// One channel
var query = ChannelQuery(cid: ChannelId(type: .messaging, id: "general"))
query.includeScheduledMessages = true
let chat = chatClient.makeChat(with: query)
try await chat.get(watch: true)
// The user's scheduled messages in this channel
print(chat.state.channel?.scheduledMessages ?? [])
// A page of channels
var channelListQuery = ChannelListQuery(filter: .containMembers(userIds: [currentUserId]))
channelListQuery.includeScheduledMessages = true
let channelList = chatClient.makeChannelList(with: channelListQuery)
try await channelList.get()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.
// The list observes the local database, so it shows the changes made on the
// device right away.
let controller = chatClient.scheduledMessageListController(
query: ScheduledMessageListQuery(filter: .equal(.cid, to: channelId))
)
controller.delegate = self
controller.synchronize()
func controller(
_ controller: ScheduledMessageListController,
didChangeScheduledMessages scheduledMessages: [ScheduledMessage]
) {
// Thread replies have a parent message
let forChannel = scheduledMessages.filter { $0.message.parentMessageId == nil }
let forThread = scheduledMessages.filter { $0.message.parentMessageId == parentMessageId }
}
// Or with Combine
controller.scheduledMessagesChangesPublisher
.sink { scheduledMessages in
print(scheduledMessages)
}
.store(in: &cancellables)
// When the server rejects a change, the status is .failed and `failure` says
// why. Send the change again when it can be retried, otherwise change or delete
// the message.
for scheduledMessage in controller.scheduledMessages {
if scheduledMessage.status == .failed, scheduledMessage.failure?.isRetryable == true {
controller.resendScheduledMessage(id: scheduledMessage.id)
}
}// The list observes the local database, so it shows the changes made on the
// device right away.
let scheduledMessageList = chatClient.makeScheduledMessageList(
with: ScheduledMessageListQuery(filter: .equal(.cid, to: channelId))
)
try await scheduledMessageList.get()
// ScheduledMessageListState is an ObservableObject
scheduledMessageList.state.$scheduledMessages
.sink { scheduledMessages in
// Thread replies have a parent message
let forChannel = scheduledMessages.filter { $0.message.parentMessageId == nil }
let forThread = scheduledMessages.filter { $0.message.parentMessageId == parentMessageId }
}
.store(in: &cancellables)
// When the server rejects a change, the status is .failed and `failure` says
// why. Send the change again when it can be retried, otherwise change or delete
// the message.
for scheduledMessage in scheduledMessageList.state.scheduledMessages {
if scheduledMessage.status == .failed, scheduledMessage.failure?.isRetryable == true {
try await scheduledMessageList.resendScheduledMessage(id: scheduledMessage.id)
}
}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.
let sentCancellable = chatClient.subscribe(toEvent: ScheduledMessageSentEvent.self) { event in
print("\(event.scheduledMessage.id) was sent as \(event.messageId)")
}
let failedCancellable = chatClient.subscribe(toEvent: ScheduledMessageFailedEvent.self) { event in
if case let .serverFailedPublishing(failure) = event.scheduledMessage.failure {
print(failure.reason?.rawValue ?? "unknown")
}
}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} |