The Message interface represents a single message in a chat room. Messages are received through the messages.subscribe() method or retrieved via messages.history().
Properties
The Message interface has the following properties:
serialStringclientIdStringtextStringtimestampDatemetadataMessageMetadataheadersMessageHeadersactionChatMessageActionversionMessageVersionreactionsMessageReactionSummaryApply an event to a message
message.with(event: ChatMessageEvent | Message | MessageReactionSummaryEvent): MessageCreates a new message instance with an event applied. This is useful for updating a local message state when receiving update or delete events. Returns the same instance if the event would be a no-op (e.g., applying an older version).
1
const updatedMessage = message.with(updateEvent);Parameters
The with() method takes the following parameters:
Returns
Message
Returns a new message instance with the event applied, or the same instance if the event would be a no-op.
Copy a message
message.copy(params?: MessageCopyParams): MessageCreates a copy of the message with specified fields replaced.
1
const messageCopy = message.copy({ text: 'New text' });Parameters
The copy() method takes the following parameters:
paramsoptionalMessageCopyParamsReturns
Message
Returns a new message instance with the specified fields replaced.
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
import { ChatMessageAction } from '@ably/chat';
// Subscribe to messages and handle different actions
room.messages.subscribe((event) => {
const message = event.message;
console.log('Serial:', message.serial);
console.log('From:', message.clientId);
console.log('Text:', message.text);
console.log('Sent at:', message.timestamp);
console.log('Action:', message.action);
// Check if message has metadata
if (Object.keys(message.metadata).length > 0) {
console.log('Metadata:', message.metadata);
}
// Check message version for updates or deletions
if (message.action === ChatMessageAction.MessageUpdate) {
console.log('Updated by:', message.version.clientId);
console.log('Update reason:', message.version.description);
}
if (message.action === ChatMessageAction.MessageDelete) {
console.log('Deleted by:', message.version.clientId);
console.log('Delete reason:', message.version.description);
}
// Check reaction summary
for (const [name, summary] of Object.entries(message.reactions.distinct)) {
console.log(`${name}: ${summary.total} reactions from ${summary.clientIds.length} clients`);
}
});