Manage chat rooms
Updated
Shows how to use the Agora Chat SDK to create and manage a chat room in your app.
Chat rooms enable real-time messaging among multiple users.
A chat room does not have a strict membership, and members do not retain any permanent relationship with each other. Once going offline, chat room members cannot receive any messages from the chat room and automatically leave the chat room after 2 minutes (members on the chat room allow list remain in the chat room even if they stay offline for 2 minutes or more). A chat room is widely applied in live broadcast use cases such as stream chat in Twitch.
This page shows how to use the Chat SDK to create and manage a chat room in your app.
Understand the tech
The Chat SDK provides the ChatRoom, ChatRoomManager, and ChatRoomEventListener classes for chat room management, which allows you to implement the following features:
Prerequisites
Before proceeding, ensure that you meet the following requirements:
- You have initialized the Chat SDK. For details, see SDK quickstart.
- You understand the call frequency limit of the Chat APIs supported by different pricing plans as described in Limitations.
- You understand the number of chat rooms supported by different pricing plans as described in Pricing Plan Details.
- Only the app super admin has the privilege of creating a chat room. Ensure that you have added an app super admin by calling the super-admin RESTful API.
Implementation
This section introduces how to call the APIs provided by the Chat SDK to implement the features listed above.
Create a chat room
Only the app super admin can call createChatRoom to create a chat room and set the chat room attributes such as the chat room name, description, and maximum number of members. Once a chat room is created, the super admin automatically becomes the chat room owner.
You are advised to call the RESTful API to create a chat room from the server.
The following code sample shows how to create a chat room:
// The chat room name can be a maximum of 128 characters.
const subject = "";
// The chat room description can be a maximum of 512 characters.
const desc = "this is room description.";
// The welcome message.
const welcomeMsg = "welcome to you.";
// The members to add.
const members = ["Tom", "Json"];
// The maximum number of members.
const maxCount = 10000;
ChatClient.getInstance()
.roomManager.createChatRoom(subject, desc, welcomeMsg, members, maxCount)
.then(() => {
console.log("get room success.");
})
.catch((reason) => {
console.log("get room fail.", reason);
});Destroy a chat room
Only the chat room owner can call destroyChatRoom to disband a chat room. Once a chat room is disbanded, all chat room members receive the onChatRoomDestroyed callback and are immediately removed from the chat room.
The following code sample shows how to destroy a chat room:
ChatClient.getInstance()
.roomManager.destroyChatRoom(roomId)
.then(() => {
console.log("destroy room success.");
})
.catch((reason) => {
console.log("destroy room fail.", reason);
});Join a chat room
Refer to the following steps to join a chat room:
-
Call
FetchPublicRoomsFromServerto retrieve the list of chat rooms from the server and locate the ID of the chat room that you want to join. -
Call
joinChatRoomto pass in the chat room ID and join the specified chat room. Once a user joins a chat room, all the other chat room members receive theonMemberJoinedcallback.
The following code sample shows how to join a chat room:
ChatClient.getInstance()
.roomManager.joinChatRoom(roomId)
.then(() => {
console.log("join room success.");
})
.catch((reason) => {
console.log("join room fail.", reason);
});Leave a chat room
All chat room members can call leaveChatRoom to leave the specified chat room. Once a member leaves the chat room, all the other chat room members receive the onMemberExited callback.
Note: Unlike chat group owners (who cannot leave their groups), a chat room owner can leave a chat room. After re-entering the chat room, this user remains the chat room owner.
The following code sample shows how to leave a chat room:
ChatClient.getInstance()
.roomManager.leaveChatRoom(roomId)
.then(() => {
console.log("join room success.");
})
.catch((reason) => {
console.log("join room fail.", reason);
});By default, after a user leaves a chat room, the Chat SDK removes all chat room messages on the local device. If you do not want these messages removed, set ChatOptions#deleteMessagesAsExitChatRoom to false when initializing the SDK.
The following code sample shows how to retain the chat room messages after leaving a chat room:
ChatOptions options = new ChatOptions();
options.deleteMessagesAsExitChatRoom = false;Retrieve the chat room attributes
All chat room members can call fetchChatRoomInfoFromServer to retrieve the attributes of the a chat room, including the chat room ID, name, description, announcements, owner, admin list, maximum number of members, and whether all members are muted.
The following code sample shows how to retrieve the chat room attributes:
ChatClient.getInstance()
.roomManager.fetchChatRoomInfoFromServer(roomId)
.then((info) => {
console.log("get room info success.", info);
})
.catch((reason) => {
console.log("get room info fail.", reason);
});Retrieve the chat room list from the server
Users can call FetchPublicRoomsFromServer to retrieve the chat room list from the server. You can retrieve a maximum of 1,000 chat rooms at each call.
// You can set the value of `pageSize` to a maximum of 1000.
ChatClient.getInstance()
.roomManager.fetchPublicChatRoomsFromServer(pageNum, pageSize)
.then((rooms) => {
console.log("get room success.", rooms);
})
.catch((reason) => {
console.log("get room fail.", reason);
});Listen for chat room events
To monitor the chat room events, you can listen for the callbacks in the ChatRoomEventListener class and add app logics accordingly. If you want to stop listening for the callback, make sure that you remove the listener to prevent memory leakage.
The following code sample shows how to add and remove the chat room listener:
// Inherits and implements the ChatRoomEventListener class.
const roomListener: ChatRoomEventListener = new (class
implements ChatRoomEventListener
{
that: QuickTestScreenBase;
constructor(parent: QuickTestScreenBase) {
this.that = parent;
}
// Occurs when a chat room instance is destroyed.
onChatRoomDestroyed(params: {
roomId: string;
roomName?: string | undefined;
}): void {
console.log(`onChatRoomDestroyed:`, params.roomId, params.roomName);
}
// Occurs when a user joins a chat room.
onMemberJoined(params: { roomId: string; participant: string }): void {
console.log(`onMemberJoined:`, params.roomId, params.participant);
}
// Occurs when a member leaves a chat room.
onMemberExited(params: {
roomId: string;
participant: string;
roomName?: string | undefined;
}): void {
console.log(
`onMemberJoined:`,
params.roomId,
params.participant,
params.roomName
);
}
// Occurs when a member is removed from a chat room.
onRemoved(params: {
roomId: string;
participant?: string | undefined;
roomName?: string | undefined;
}): void {
console.log(
`onRemoved:`,
params.roomId,
params.participant,
params.roomName
);
}
// Occurs when one or more members are added to the chat room mute list. The muted members receive this event.
// Available since SDK v1.4.0. mutes maps each muted member's user ID to their mute expiration timestamp (a Unix timestamp in milliseconds).
onMuteListAddedV2(params: { roomId: string; mutes: Record<string, number> }): void {
console.log(`onMuteListAddedV2:`, params.roomId, params.mutes);
}
// Occurs when a member is added to the chat room mute list.
// Deprecated since SDK v1.4.0. Use onMuteListAddedV2 instead.
onMuteListAdded(params: {
roomId: string;
mutes: string[];
expireTime?: string | undefined;
}): void {
console.log(
`onMuteListAdded:`,
params.roomId,
params.mutes,
params.expireTime
);
}
// Occurs when a member is removed from the chat room mute list.
onMuteListRemoved(params: { roomId: string; mutes: string[] }): void {
console.log(`onMuteListRemoved:`, params.roomId, params.mutes);
}
// Occurs when a member is promoted to a chat room admin.
onAdminAdded(params: { roomId: string; admin: string }): void {
console.log(`onAdminAdded:`, params.roomId, params.admin);
}
// Occurs when an admin is demoted to a chat room member.
onAdminRemoved(params: { roomId: string; admin: string }): void {
console.log(`onAdminRemoved:`, params.roomId, params.admin);
}
// Occurs when the chat room ownership is transferred.
onOwnerChanged(params: {
roomId: string;
newOwner: string;
oldOwner: string;
}): void {
console.log(
`onOwnerChanged:`,
params.roomId,
params.newOwner,
params.oldOwner
);
}
// Occurs when the chat room announcements are updated.
onAnnouncementChanged(params: {
roomId: string;
announcement: string;
}): void {
console.log(`onAnnouncementChanged:`, params.roomId, params.announcement);
}
// Occurs when one or more chat room members are added to the allow list.
onAllowListAdded(params: { roomId: string; members: string[] }): void {
console.log(`onAllowListAdded:`, params.roomId, params.members);
}
// Occurs when one or more chat room members are removed from the allow list.
onAllowListRemoved(params: { roomId: string; members: string[] }): void {
console.log(`onAllowListRemoved:`, params.roomId, params.members);
}
// Occurs when all members in the chat room are muted or unmuted.
onAllChatRoomMemberMuteStateChanged(params: {
roomId: string;
isAllMuted: boolean;
}): void {
console.log(
`onAllChatRoomMemberMuteStateChanged:`,
params.roomId,
params.isAllMuted ? "true" : "false"
);
}
// Occurs when the chat room specifications change. All chat room members receive this event.
onSpecificationChanged(room: ChatRoom): void {
console.log(`onSpecificationChanged:`, room);
}
// Occurs when the custom chat room attributes (key-value) are updated.
onAttributesUpdated(params: {
roomId: string;
attributes: Map;
from: string;
}): void {
console.log(
`onAttributesUpdated:`,
params.roomId,
params.attributes,
params.from
);
}
// Occurs when the custom chat room attributes (key-value) are removed.
onAttributesRemoved(params: {
roomId: string;
removedKeys: Array;
from: string;
}): void {
console.log(
`onAttributesRemoved:`,
params.roomId,
params.removedKeys,
params.from
);
}
})(this);
// Removes the chat room listener.
ChatClient.getInstance().roomManager.removeAllRoomListener();
// Adds the chat room listener.
ChatClient.getInstance().roomManager.addRoomListener(roomListener);Update the chat room member count in real time
If many members join or leave a chat room in a very short time, you can update the chat room member count in real time:
-
When a user joins a chat room, other members in the chat room receive the
ChatRoomEventListener#onMemberJoinedevent. When a member leaves or is removed from a chat room, other members in the chat room receive theChatRoomEventListener#onMemberExitedevent. -
After the event is received, you can call the
fetchChatRoomInfoFromServermethod to get local details of the chat room, including the current number of members in the chat room.ChatClient.getInstance() .chatManager.fetchChatRoomInfoFromServer( roomId // Room ID ) .then((res) => { // Operation successful, room information obtained }) .catch((error) => { // An error occurred });
