Manage chat groups
Updated
Introduces chat group functionalities.
Chat groups enable real-time messaging among multiple users.
This page shows how to use the Chat SDK to create and manage a chat group in your app.
Understand the tech
The Chat SDK provides the ChatGroup, ChatGroupManager, and ChatGroupEventListener classes for chat group management, which allows you to implement the following features:
- Create and destroy a chat group
- Join and leave a chat group
- Retrieve the chat group attributes
- Retrieve the chat group member list
- Retrieve the chat group list
- Block and unblock a chat group
- Listen for chat group events
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 limits of the Chat APIs supported by different pricing plans as described in Limitations.
- You understand the number of chat groups and chat group members supported by different pricing plans as described in Pricing Plan Details.
Implementation
This section describes how to call the APIs provided by the Chat SDK to implement features.
Create a chat group
Set GroupStyle and inviteNeedConfirm before creating a chat group.
- Is the group public or private, and who can invite members (
GroupStyle):
PrivateOnlyOwnerInvite: A private group. Only the chat group owner and admins can add users to the chat group.PrivateMemberCanInvite: A private group. All chat group members can add users to the chat group.PublicJoinNeedApproval: A public group. The chat group owner and admins can add users, and users can send join requests to the chat group.PublicOpenJoin: A public group. All users can join the chat group automatically without any need for approval from the chat group owner and admins.
- Does a group invitation require consent from an invitee to add them to the group (
inviteNeedConfirm):
- Yes (
ChatGroupOptions#inviteNeedConfirmis set totrue). After creating a group and sending group invitations, the subsequent logic varies based on whether an invitee automatically consents to the group invitation (autoAcceptGroupInvitation):- Yes (
autoAcceptGroupInvitationis set totrue). The invitee automatically joins the chat group and receives theChatGroupEventListener#onAutoAcceptInvitationcallback, the chat group owner receives theChatGroupEventListener#onInvitationAcceptedandChatGroupEventListener#onMembersJoinedcallbacks, and the other chat group members receives theChatGroupEventListener#onMembersJoinedcallback. - No (
autoAcceptGroupInvitationis set tofalse). The invitee receives theChatGroupEventListener#onInvitationReceivedcallback and chooses whether to join the chat group:- If the invitee accepts the group invitation, the chat group owner receives the
ChatGroupEventListener#onInvitationAcceptedandChatGroupEventListener#onMembersJoinedcallbacks, and the other chat group members receive theChatGroupEventListener#onMembersJoinedcallback; - If the invitee declines the group invitation, the chat group owner receives the
ChatGroupEventListener#onInvitationDeclinedcallback.
- If the invitee accepts the group invitation, the chat group owner receives the
- Yes (
- No (
ChatGroupOptions#inviteNeedConfirmis set tofalse). After creating a chat group and sending group invitations, an invitee is added to the chat group regardless of theirautoAcceptGroupInvitationsetting. The invitee receives theChatGroupEventListener#onAutoAcceptInvitationcallback, the chat group owner receives theChatGroupEventListener#onInvitationAcceptedandChatGroupEventListener#onMembersJoinedcallbacks, and the other chat group members receive theChatGroupEventListener#onMembersJoinedcallback.
Users can call createGroup to create a chat group and set the chat group attributes such as the chat group name, description, maximum number of members, and reason for creating the group, by specifying ChatGroupOptions.
The following code sample shows how to create a chat group:
// The permission style of the chat group.
option.style = PrivateOnlyOwnerInvite;
// The name of the chat group can be a maximum of 128 characters.
const groupName = "study";
// The description of the chat group can be a maximum of 512 characters.
const desc = "this is study group";
// The members to add.
const allMembers = ["Tom", "Jason"];
ChatClient.getInstance()
.groupManager.createGroup(option, groupName, desc, allMembers, reason)
.then(() => {
console.log("create group success.");
})
.catch((reason) => {
console.log("create group fail.", reason);
});Since SDK v1.4.0, you can call createGroupEx to create a chat group, set the group attributes through ChatGroupOptions, and set the group avatar. The createGroup method is deprecated.
ChatClient.getInstance().groupManager.createGroupEx({
// The group options. The key option is `style`, which sets the group type. See `ChatGroupStyle`.
options: new ChatGroupOptions({ style: ChatGroupStyle.PrivateOnlyOwnerInvite }),
// The group name, which cannot exceed 128 characters.
groupName: '<GROUP_NAME>',
// The group description, which cannot exceed 512 characters.
desc: '<GROUP_DESC>',
// The members to invite.
inviteMembers: ['<USER_ID_1>', '<USER_ID_2>'],
inviteReason: '<INVITE_REASON>',
});Destroy a chat group
Only the chat group owner can call destroyGroup to disband a chat group. Once a chat group is disbanded, all chat group members receive the onGroupDestroyed callback and are immediately removed from the chat group.
Once a chat group is destroyed, all chat group data is deleted from the local database and memory.
The following code sample shows how to destroy a chat group:
const groupId = "100";
ChatClient.getInstance()
.groupManager.destroyGroup(groupId)
.then(() => {
console.log("destroy group success.");
})
.catch((reason) => {
console.log("destroy group fail.", reason);
});Join a chat group
The logic of joining a chat group varies according to the GroupStyle setting you choose when creating the chat group:
- If the
GroupStyleis set toPublicOpenJoin, all users can join the chat group without the consent from the chat group owner and admins. Once a user joins a chat group, all chat group members receive theChatGroupEventListener#onMembersJoinedcallback. - If the
GroupStyleis set toPublicJoinNeedApproval, users can send join requests to the chat group. The chat group owner and chat group admins receive theChatGroupEventListener#onRequestToJoinReceivedcallback and choose whether to accept the join request:- If the request is accepted, the user joins the chat group and receives the
ChatGroupEventListener#onRequestToJoinAcceptedcallback, while all the other chat group members receive theChatGroupEventListener#onMembersJoinedcallback. - If the request is declined, the user receives the
ChatGroupEventListener#onRequestToJoinDeclinedcallback.
- If the request is accepted, the user joins the chat group and receives the
Users can only request to join public groups; private groups do not allow join requests.
Users can refer to the following steps to join a chat group:
-
Call
fetchPublicGroupsFromServerto retrieve the list of public groups from the server, and locate the ID of the chat group that you want to join. -
Call
requestToJoinPublicGroupto pass in the chat group ID and request to join the specified chat group.
The following code sample shows how to join a chat group:
// Retrieve the list of public groups with pagination.
// The maximum number of public groups to retrieve with pagination.
const pageSize = 10;
// The position from which to start getting data.
const cursor = "";
ChatClient.getInstance()
.groupManager.fetchPublicGroupsFromServer(pageSize, cursor)
.then(() => {
console.log("get group list success.");
})
.catch((reason) => {
console.log("get group list fail.", reason);
});
// Request to join the specified chat group.
const groupId = "100";
const reason = "study typescript";
ChatClient.getInstance()
.groupManager.requestToJoinPublicGroup(groupId, reason)
.then(() => {
console.log("request send success.");
})
.catch((reason) => {
console.log("request send fail.", reason);
});Leave a chat group
Chat group members can call leaveGroup to leave the specified chat group, whereas the chat group owner cannot perform this operation. Once a member leaves a chat group, all the other chat group members receive the ChatGroupEventListener#onMembersExited callback.
The following code sample shows how to leave a chat group:
ChatClient.getInstance()
.groupManager.leaveGroup(groupId)
.then(() => {
console.log("leave group success.");
})
.catch((reason) => {
console.log("leave group fail.", reason);
});Retrieve the attributes of a chat group
All chat group members can call getGroupWithId to retrieve the chat group attributes from memory. The attributes contain the chat group ID, name, description, owner, announcements, number of members, admin list, and whether to mute all members.
All chat group members can also call fetchGroupInfoFromServer to retrieve the chat group attributes from the server. The attributes contain the chat group ID, name, description, owner, announcements, number of members, admin list, and whether to mute all members.
The following code sample shows how to retrieve the chat group attributes:
// Retrieve the chat group attributes from memory.
ChatClient.getInstance()
.groupManager.getGroupWithId(groupId)
.then((groupInfo) => {
console.log("get group info success: ", groupInfo);
})
.catch((reason) => {
console.log("get group info fail.", reason);
});
// Retrieve the chat group attributes from the server.
ChatClient.getInstance()
.groupManager.fetchGroupInfoFromServer(groupId)
.then((groupInfo) => {
console.log("get group info success: ", groupInfo);
})
.catch((reason) => {
console.log("get group info fail.", reason);
});Retrieve the chat group member list
All chat group members can call fetchMemberListFromServer to retrieve the chat group member list from the server with pagination.
The following code sample shows how to retrieve the chat group member list:
// The ID of the chat group.
// The maximum number of members to retrieve with pagination.
// The position from which to start getting data. `cursor` is set to `null` or an empty string by default at the first call.
ChatClient.getInstance()
.groupManager.fetchMemberListFromServer(groupId, pageSize, cursor)
.then((members) => {
console.log("get group info success: ", members);
})
.catch((reason) => {
console.log("get group info fail.", reason);
});Since SDK v1.4.0, you can call fetchMemberInfoListFromServer to retrieve a member list in which each entry includes the member's user ID, role, and the time they joined the group:
const groupId = '<GROUP_ID>';
const cursor = ''; // The position to start from. Pass an empty string for the first page.
const limit = 200; // The number of members to retrieve per page; the maximum depends on the server.
ChatClient.getInstance()
.groupManager.fetchMemberInfoListFromServer(groupId, cursor, limit)
.then((result) => {
console.log('Fetch member info list result:', result);
})
.catch((error) => {
console.error('Error fetching member info list:', error);
});Retrieve the chat group list
-
Users can call
fetchJoinedGroupsFromServerto retrieve the joined chat group list from the server with pagination.// The maximum number of chat groups to retrieve with pagination. const pageSize = 10; // The page number from which to start getting data. const pageNum = 1; ChatClient.getInstance() .groupManager.fetchJoinedGroupsFromServer(pageSize, pageNum) .then((groups) => { console.log("get group list success: ", groups); }) .catch((reason) => { console.log("get group list fail.", groups); }); -
Users can call
getJoinedGroupsto retrieve the joined chat group list from the local database. To ensure the accuracy of results, retrieve the joined chat group list from the server first.ChatClient.getInstance() .groupManager.getJoinedGroups() .then((groups) => { console.log("get group list success: ", groups); }) .catch((reason) => { console.log("get group list fail.", groups); }); -
Users can also call
fetchPublicGroupsFromServerto retrieve public chat group list from the server with pagination.
ChatClient.getInstance()
.groupManager.fetchPublicGroupsFromServer(pageSize, cursor)
.then((groups) => {
console.log("get group list success: ", groups);
})
.catch((reason) => {
console.log("get group list fail.", groups);
});Retrieve the number of groups joined by the current user
Users can call fetchJoinedGroupCount to retrieve the number of groups they have joined directly from the server. The limit on the number of groups a user can join is determined by the pricing package. For more details, please refer to the product pricing.
ChatClient.getInstance()
.groupManager.fetchJoinedGroupCount()
.then((count: number) => {
// TODO: Retrieve the number of joined groups.
})
.catch();Block and unblock a chat group
Block a chat group
All chat group members can call blockGroup to block a chat group. Once a member blocks a chat group, this member can no longer receive messages from the chat group.
The following code sample shows how to block a chat group:
ChatClient.getInstance()
.groupManager.blockGroup(groupId)
.then(() => {
console.log("block group success. ");
})
.catch((reason) => {
console.log("block group fail.", groups);
});Unblock a chat group
All chat group members can call unblockGroup to unblock a chat group.
The following code sample shows how to unblock a chat group:
ChatClient.getInstance()
.groupManager.unblockGroup(groupId)
.then(() => {
console.log("unblock group success. ");
})
.catch((reason) => {
console.log("unblock group fail.", groups);
});Listen for chat group events
To monitor the chat group events, users can listen for the callbacks in the ChatGroupEventListener class and add app logics accordingly. If a user wants to stop listening for the callbacks, make sure that the user removes the listener to prevent memory leakage.
Refer to the following code sample to listen for chat group events:
// Inherit and implement the ChatGroupEventListener class.
const groupListener: ChatGroupEventListener = new (class
implements ChatGroupEventListener
{
// Occurs when a user receives a group invitation.
onInvitationReceived(params: {
groupId: string;
inviter: string;
groupName?: string | undefined;
reason?: string | undefined;
}): void {
console.log(
`onInvitationReceived:`,
params.groupId,
params.inviter,
params.groupName,
params.reason
);
}
// Occurs when the chat group owner and chat group admins receive a join request.
onRequestToJoinReceived(params: {
groupId: string;
applicant: string;
groupName?: string | undefined;
reason?: string | undefined;
}): void {
console.log(
`onRequestToJoinReceived:`,
params.groupId,
params.applicant,
params.groupName,
params.reason
);
}
// Occurs when the chat group owner and chat group admins approve a join request.
onRequestToJoinAccepted(params: {
groupId: string;
accepter: string;
groupName?: string | undefined;
}): void {
console.log(
`onRequestToJoinAccepted:`,
params.groupId,
params.accepter,
params.groupName
);
}
// Occurs when the chat group owner and chat group admins decline a join request.
onRequestToJoinDeclined(params: {
groupId: string;
decliner: string;
groupName?: string | undefined;
applicant?: string;
reason?: string | undefined;
}): void {
console.log(
`onRequestToJoinDeclined:`,
params.groupId,
params.decliner,
params.groupName,
params.applicant
params.reason
);
}
// Occurs when a user accepts a group invitation.
onInvitationAccepted(params: {
groupId: string;
invitee: string;
reason?: string | undefined;
}): void {
console.log(
`onInvitationAccepted:`,
params.groupId,
params.invitee,
params.reason
);
}
// Occurs when a user declines a group invitation.
onInvitationDeclined(params: {
groupId: string;
invitee: string;
reason?: string | undefined;
}): void {
console.log(
`onInvitationDeclined:`,
params.groupId,
params.invitee,
params.reason
);
}
// Occurs when a member is removed from a chat group.
onUserRemoved(params: {
groupId: string;
groupName?: string | undefined;
}): void {
console.log(`onUserRemoved:`, params.groupId, params.groupName);
}
// Occurs when a chat group is destroyed.
onGroupDestroyed(params: {
groupId: string;
groupName?: string | undefined;
}): void {
console.log(`onGroupDestroyed:`, params.groupId, params.groupName);
}
// Occurs when a user automatically accepts a chat group invitation.
onAutoAcceptInvitation(params: {
groupId: string;
inviter: string;
inviteMessage?: string | undefined;
}): void {
console.log(
`onGroupDestroyed:`,
params.groupId,
params.inviter,
params.inviteMessage
);
}
// Occurs when a member is added to the chat group mute list.
onMuteListAdded(params: {
groupId: string;
mutes: string[];
muteExpire?: number | undefined;
}): void {
console.log(
`onMuteListAdded:`,
params.groupId,
params.mutes,
params.muteExpire?.toString
);
}
// Occurs when a member is removed from the chat group mute list.
onMuteListRemoved(params: { groupId: string; mutes: string[] }): void {
console.log(`onMuteListRemoved:`, params.groupId, params.mutes);
}
// Occurs when a chat group member is promoted to an admin.
onAdminAdded(params: { groupId: string; admin: string }): void {
console.log(`onAdminAdded:`, params.groupId, params.admin);
}
// Occurs when a chat group admin is demoted to a regular member.
onAdminRemoved(params: { groupId: string; admin: string }): void {
console.log(`onAdminRemoved:`, params.groupId, params.admin);
this.that.setState({
group_listener: `onAdminRemoved: ` + params.groupId + params.admin,
});
}
// Occurs when the chat group owner is changed.
onOwnerChanged(params: {
groupId: string;
newOwner: string;
oldOwner: string;
}): void {
console.log(
`onOwnerChanged:`,
params.groupId,
params.newOwner,
params.oldOwner
);
}
// Occurs when one or more members join a chat group. All group members except the new members receive this callback.
// Available since SDK v1.4.0.
onMembersJoined(params: { groupId: string; members: string[] }): void {
console.log(`onMembersJoined:`, params.groupId, params.members);
}
// Occurs when a user joins a chat group.
// Deprecated since SDK v1.4.0. Use onMembersJoined instead.
onMemberJoined(params: { groupId: string; member: string }): void {
console.log(`onMemberJoined:`, params.groupId, params.member);
}
// Occurs when one or more members leave a chat group. All group members except those who left receive this callback.
// Available since SDK v1.4.0.
onMembersExited(params: { groupId: string; members: string[] }): void {
console.log(`onMembersExited:`, params.groupId, params.members);
}
// Occurs when a member leaves a chat group.
// Deprecated since SDK v1.4.0. Use onMembersExited instead.
onMemberExited(params: { groupId: string; member: string }): void {
console.log(`onMemberExited:`, params.groupId, params.member);
}
// Occurs when the chat group announcements are updated.
onAnnouncementChanged(params: {
groupId: string;
announcement: string;
}): void {
console.log(`onAnnouncementChanged:`, params.groupId, params.announcement);
}
// Occurs when a shared file is uploaded to a chat group.
onSharedFileAdded(params: { groupId: string; sharedFile: string }): void {
console.log(`onSharedFileAdded:`, params.groupId, params.sharedFile);
}
// Occurs when a shared file is deleted in a chat group.
onSharedFileDeleted(params: { groupId: string; fileId: string }): void {
console.log(`onSharedFileDeleted:`, params.groupId, params.fileId);
}
// Occurs when a member is added to the chat group allow list.
onAllowListAdded(params: { groupId: string; members: string[] }): void {
console.log(`onAllowListAdded:`, params.groupId, params.members);
}
// Occurs when a member is removed from the chat group allow list.
onAllowListRemoved(params: { groupId: string; members: string[] }): void {
console.log(`onAllowListRemoved:`, params.groupId, params.members);
}
// Occurs when all chat group members are muted or unmuted.
onAllGroupMemberMuteStateChanged(params: {
groupId: string;
isAllMuted: boolean;
}): void {
console.log(
`onAllGroupMemberMuteStateChanged:`,
params.groupId,
params.isAllMuted
);
}
// Occurs when the chat group detail change. All chat group members receive this event.
onDetailChanged(group: ChatGroup): void {
console.log(`onDetailChanged:`, group);
}
// Occurs when the disabled state of group changes.
onStateChanged(group: ChatGroup): void {
console.log(`onStateChanged:`, group);
}
})();
// Remove the chat group listener.
ChatClient.getInstance().groupManager.removeAllGroupListener();
// Add the chat group listener.
ChatClient.getInstance().groupManager.addGroupListener(groupListener);