Send, delete, and subscribe to message reactions.
This property provides access to the message reactions functionality, allowing you to add reactions to specific messages, remove reactions, and subscribe to reaction events in real-time.
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.
Important: The Promise may resolve before OR after the deletion event is received from the realtime channel. Subscribers may see the deletion event before this method completes.
Note:
The unique identifier of the message to delete.
Optionaldetails: OperationDetailsOptional details to record about the delete action.
A Promise that resolves to the deleted Message object with
isDeleted set to true and deletion metadata populated, or rejects with:
import * as Ably from 'ably';
import { ChatClient, Message } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
const room = await chatClient.rooms.get('public-chat');
// Serial of the message to delete
const messageSerial = '01726585978590-001@abcdefghij:001';
try {
const deletedMessage = await room.messages.delete(messageSerial, {
description: 'Inappropriate content removed by moderator',
metadata: {
reason: 'policy-violation',
timestamp: Date.now()
}
});
console.log(`Deleted message: ${deletedMessage.text}`);
} catch (error) {
if (error.code === 40400) {
console.error('Message not found:', messageSerial);
} else if (error.code === 40300) {
console.error('Permission denied: Cannot delete this message');
} else {
console.error('Failed to delete message:', error);
}
}
Get a specific message by its unique serial identifier.
This method retrieves a single message using its serial, which is a unique identifier assigned to each message when it's created.
NOTE: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
The unique serial identifier of the message to retrieve.
A Promise that resolves to the Message object, or rejects with:
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
const room = await chatClient.rooms.get('customer-support');
// Get a specific message by its serial
const messageSerial = '01726585978590-001@abcdefghij:001';
try {
const message = await room.messages.get(messageSerial);
console.log(`Serial: ${message.serial}`);
console.log(`From: ${message.clientId}`);
console.log(`Text: ${message.text}`);
} catch (error) {
if (error.code === 40400) {
console.error('Message not found:', messageSerial);
} else {
console.error('Failed to retrieve message:', error);
}
}
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.
NOTE: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
Query parameters to filter and control the message retrieval
A Promise that resolves to a PaginatedResult containing an array of Message objects and methods for pagination control, or rejects with ErrorCode.InvalidArgument when the query fails due to invalid parameters
import * as Ably from 'ably';
import { ChatClient, OrderBy } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
const room = await chatClient.rooms.get('project-updates');
// Retrieve message history with pagination
try {
let result = await room.messages.history({
limit: 50,
orderBy: OrderBy.NewestFirst
});
console.log(`Retrieved ${result.items.length} messages`);
result.items.forEach(message => {
console.log(`${message.clientId}: ${message.text}`);
});
// Paginate through additional pages if available
while (result.hasNext()) {
const nextPage = await result.next();
if (nextPage) {
console.log(`Next page has ${nextPage.items.length} messages`);
nextPage.items.forEach(message => {
console.log(`${message.clientId}: ${message.text}`);
});
result = nextPage;
} else {
break; // No more pages
}
}
console.log('All message history retrieved');
} catch (error) {
console.error('Failed to retrieve message history:', error);
}
Send a message to the chat room.
This method publishes a new message to the chat room using the Ably Chat API. The message will be delivered to all subscribers in real-time.
Important: The Promise may resolve before OR after the message is received from the realtime channel. This means subscribers may see the message before the send operation completes.
NOTE: This method uses the Ably Chat REST API and so does not require the room to be attached to be called.
Message parameters containing the text and optional metadata/headers
A Promise that resolves to the sent Message object, or rejects with:
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
const room = await chatClient.rooms.get('general-chat');
// Send a message with metadata and headers
try {
const message = await room.messages.send({
text: 'Hello, everyone! 👋',
metadata: {
priority: 'high',
category: 'greeting'
},
headers: {
'content-type': 'text',
'language': 'en'
}
});
console.log(`Message sent successfully: ${message.serial}`);
} catch (error) {
console.error('Failed to send message:', error);
}
Subscribe to chat message events in this room.
This method allows you to listen for chat message events and provides access to historical messages that occurred before the subscription was established.
Note: The room must be attached for the listener to receive new message events.
A callback function that will be invoked when chat message events occur.
A MessageSubscriptionResponse object that provides:
- unsubscribe(): Method to stop listening for message events
- historyBeforeSubscribe(): Method to retrieve messages sent before subscription
import * as Ably from 'ably';
import { ChatClient, ChatMessageEvent } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
// Get a room and subscribe to messages
const room = await chatClient.rooms.get('general-chat');
const subscription = room.messages.subscribe((event: ChatMessageEvent) => {
console.log(`Message ${event.type}:`, event.message.text);
console.log('From:', event.message.clientId);
console.log('At:', event.message.timestamp);
// Handle different event types
});
// Attach to the room to start receiving events
await room.attach();
// Later, unsubscribe when done
subscription.unsubscribe();
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.
Important: The Promise may resolve before OR after the update event is received from the realtime channel. Subscribers may see the update event before this method completes.
Note:
The unique identifier of the message to update.
The new message content and properties.
Optionaldetails: OperationDetailsOptional details to record about the delete action.
A Promise that resolves to the updated Message object with
isUpdated set to true and update metadata populated, or rejects with:
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
const chatClient: ChatClient; // existing ChatClient instance
const room = await chatClient.rooms.get('team-updates');
// Update a message with corrected text and tracking
const messageSerial = '01726585978590-001@abcdefghij:001';
try {
const updatedMessage = await room.messages.update(
messageSerial,
{
text: 'Meeting is scheduled for 3 PM (corrected time)',
},
{
description: 'Corrected meeting time',
metadata: {
editTimestamp: Date.now()
}
}
);
console.log(`Updated text: ${updatedMessage.text}`);
} catch (error) {
if (error.code === 40400) {
console.error('Message not found:', messageSerial);
} else if (error.code === 40300) {
console.error('Permission denied: Cannot update this message');
} else {
console.error('Failed to update message:', error);
}
}
This interface is used to interact with messages in a chat room: subscribing to new messages, fetching history, or sending messages.
Get an instance via Room.messages.