The Messages interface provides methods for sending, receiving, and managing chat messages in a room. Access it via room.messages.
1
const messages = room.messages;Properties
The Messages interface has the following properties:
reactionsMessageReactionsSubscribe to messages
messages.subscribe(listener: MessageListener): MessageSubscriptionResponseSubscribe to chat message events in the room. This method allows you to listen for new messages and provides access to historical messages that occurred before the subscription was established.
The room must be attached for the listener to receive new message events.
1
2
3
4
5
6
7
8
9
const { unsubscribe, historyBeforeSubscribe } = messages.subscribe((event) => {
console.log('Received message:', event.message.text);
});
// Get messages sent before subscribing
const history = await historyBeforeSubscribe();
// To stop receiving messages
unsubscribe();Parameters
The subscribe() method takes the following parameters:
listenerrequiredMessageListenerReturns
MessageSubscriptionResponse
Returns an object with the following methods:
Unsubscribe from messages
unsubscribe(): voidCall unsubscribe() to stop listening for message events.
Get messages from before the subscription started
historyBeforeSubscribe(params?: HistoryBeforeSubscribeParams): Promise<PaginatedResult<Message>>Get messages sent to the room from before the subscription was established.
Parameters
The historyBeforeSubscribe() method takes the following parameters:
paramsoptionalHistoryBeforeSubscribeParamsReturns
Promise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.
Send a message
messages.send(params: SendMessageParams): Promise<Message>Send a message to the chat room. The message will be delivered to all subscribers in real-time.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
const message = await messages.send({
text: 'Hello, world!'
});
console.log('Message sent with serial:', message.serial);Parameters
The send() method takes the following parameters:
paramsrequiredSendMessageParamsReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the sent Message object, or rejected with an ErrorInfo object.
Get message history
messages.history(params: HistoryParams): Promise<PaginatedResult<Message>>Get messages that have been previously sent to the chat room. This method retrieves historical messages based on the provided query options, allowing you to paginate through message history, filter by time ranges, and control the order of results.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
6
7
8
9
10
11
const history = await messages.history({
limit: 50,
orderBy: OrderBy.NewestFirst
});
console.log('Messages:', history.items);
// Get next page if available
if (history.hasNext()) {
const nextPage = await history.next();
}Parameters
The history() method takes the following parameters:
paramsrequiredHistoryParamsReturns
Promise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.
Get a specific message
messages.get(serial: string): Promise<Message>Get a specific message by its unique serial identifier.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
const message = await messages.get('01234567890@abcdefghij');
console.log('Message text:', message.text);Parameters
The get() method takes the following parameters:
serialrequiredStringReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the Message object matching the given serial, or rejected with an ErrorInfo object.
Update a message
messages.update(serial: string, updateParams: UpdateMessageParams, details?: OperationDetails): Promise<Message>Update a message in the chat room. This method modifies an existing message's content, metadata, or headers. The update creates a new version of the message while preserving the original serial identifier. Subscribers will receive an update event in real-time.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
6
7
const updatedMessage = await messages.update(
message.serial,
{ text: 'Updated message text' },
{ description: 'Fixed typo' }
);
console.log('Message updated:', updatedMessage.version);Parameters
The update() method takes the following parameters:
serialrequiredStringupdateParamsrequiredUpdateMessageParamsdetailsoptionalOperationDetailsReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the updated Message object, or rejected with an ErrorInfo object. The returned message will have its action property set to updated.
Delete a message
messages.delete(serial: string, details?: OperationDetails): Promise<Message>Delete a message in the chat room. This method performs a "soft delete" on a message, marking it as deleted rather than permanently removing it. The deleted message will still be visible in message history but will be flagged as deleted. Subscribers will receive a deletion event in real-time.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
4
5
6
const deletedMessage = await messages.delete(
message.serial,
{ description: 'Removed inappropriate content' }
);
console.log('Message deleted:', deletedMessage.action);Parameters
The delete() method takes the following parameters:
serialrequiredStringdetailsoptionalOperationDetailsReturns
Promise<Message>
Returns a promise. The promise is fulfilled with the deleted Message object, or rejected with an ErrorInfo object. The returned message will have its action property set to deleted.
PaginatedResult
A PaginatedResult represents a page of results from a paginated query such as history() or historyBeforeSubscribe().
Properties
itemsMessage[]Check for more pages
hasNext(): booleanReturns true if there are more pages available by calling next().
Check if last page
isLast(): booleanReturns true if this is the last page of results.
Get next page
next(): Promise<PaginatedResult<Message> | null>Returns a promise. The promise is fulfilled with the next page of results, or null if there are no more pages, or rejected with an ErrorInfo object.
Get first page
first(): Promise<PaginatedResult<Message>>Returns a promise. The promise is fulfilled with the first page of results, or rejected with an ErrorInfo object.
Get current page
current(): Promise<PaginatedResult<Message>>Returns a promise. The promise is fulfilled with the current page of results, or rejected with an ErrorInfo object.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { ChatMessageEventType, OrderBy } from '@ably/chat';
const room = await chatClient.rooms.get('my-room');
await room.attach();
// Subscribe to messages
const { unsubscribe, historyBeforeSubscribe } = room.messages.subscribe((event) => {
const msg = event.message;
switch (event.type) {
case ChatMessageEventType.Created:
console.log(`${msg.clientId}: ${msg.text}`);
break;
case ChatMessageEventType.Updated:
console.log(`Message updated: ${msg.text}`);
break;
case ChatMessageEventType.Deleted:
console.log(`Message deleted: ${msg.serial}`);
break;
}
});
// Get recent history
const history = await room.messages.history({ limit: 10 });
history.items.forEach(msg => {
console.log(`[History] ${msg.clientId}: ${msg.text}`);
});
// Send a message
const sent = await room.messages.send({ text: 'Hello everyone!' });
// Update the message
await room.messages.update(sent.serial, { text: 'Hello everyone! (edited)' });
// Clean up
unsubscribe();