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 allows you to implement the following features:

  • Create and destroy a chat room
  • Join and leave a chat room
  • Retrieve the chat room list from the server
  • Retrieve the attributes of a chat room
  • Listen for chat room 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 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 and destroy a chat room

The app super admin can create a chat room and set the chat room attributes such as the chat room name, description, and the 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.

Only the chat room owner can disband a chat room. Once a chat room is disbanded, all members of that chat room are immediately removed from the chat room.

// The super admin can call createChatRoom to create a chat room.
const options = {
  name: "chatRoomName", // The name of the chat room
  description: "description", // The description of the chat room
  maxusers: 200, // The maximum number of members. Default value: 200. Maximum value: 5,000.
  members: ["user1", "user2"], // (Optional) The chat room members. Specify at least one user.
};
chatClient.createChatRoom(options).then((res) => console.log(res));

// The chat room owner can call destroyChatRoom to disband a chat room.
const options = {
  chatRoomId: "chatRoomId",
};
chatClient.destroyChatRoom(options).then((res) => console.log(res));

Join and leave a chat room

All chat users can call joinChatRoom to join the specified chat room. Once a chat user joins a chat room, all the other chat room members receive the memberPresence callback.

All chat room members can call leaveChatRoom to leave the specified chat room. Once a chat room member leaves a chat room, all the other members receive the memberAbsence callback.

Since SDK v1.4.0, the joinChatRoom response includes an info field with the following chat room information: the creation time (createtimestamp), whether all members are muted (isallmembersmuted), whether the user is on the allow list (isinallowlist), the current member count (membercount), and the user's mute expiration time (muteexpiretimestamp).

// All chat users can call joinChatRoom to join the specified chat room.
const options = {
  roomId: "roomId",
  message: "reason",
};
chatClient.joinChatRoom(options).then((res) => console.log(res));

// All chat room members can call leaveChatRoom to leave the specified chat room.
const options = {
  roomId: "roomId",
};
chatClient.leaveChatRoom(options).then((res) => console.log(res));

Retrieve the chat room list and attributes

All chat users can get the chat room list from the server and retrieve the basic information of the specified chat room using the chat room ID.

// Chat room members can call getChatRooms to retrieve the specified number of chat rooms from the server by page. The maximum value of pageSize is 1,000.
const options = {
  pagenum: 1,
  pagesize: 20,
};
chatClient.getChatRooms(options).then((res) => console.log(res));

// Chat room members can call getChatRoomDetails to get the basic information of the specified chat room by passing the chat room ID.
const options = {
  chatRoomId: "chatRoomId",
};
chatClient.getChatRoomDetails(options).then((res) => console.log(res));

Listen for chat room events

To monitor the chat room events, you can call addEventHandler to listen for the callbacks and add app logics accordingly.

chatClient.addEventHandler("handlerId", {
  onChatroomEvent: function (msg) {
    switch (msg.operation) {
      // Occurs when all the chat room members are unmuted.
      case "unmuteAllMembers":
        break;
      // Occurs when all the chat room members are muted.
      case "muteAllMembers":
        break;
      // Occurs when a member is removed from the chat room allow list.
      case "removeAllowlistMember":
        break;
      // Occurs when a member is added to the chat room allow list.
      case "addUserToAllowlist":
        break;
      // Occurs when a member deletes a chat room announcement.
      case "deleteAnnouncement":
        break;
      // Occurs when a member updates a chat room announcement. Since SDK v1.4.0, the event includes the new announcement content (announcement).
      case "updateAnnouncement":
        break;
      // Occurs when a member is removed from the chat room mute list.
      case "unmuteMember":
        break;
      // Occurs when a member is added to the chat room mute list. Since SDK v1.4.0, the event includes the muted member's user ID (userId) and mute expiration time (muteTimestamp).
      case "muteMember":
        break;
      // Occurs when a chat room admin is removed from the admin list.
      case "removeAdmin":
        break;
      // Occurs when a chat room member is added to the admin list.
      case "setAdmin":
        break;
      // Occurs when the chat room owner is changed.
      case "changeOwner":
        break;
      // Occurs when a chat room member leaves a chat room.
      case "memberAbsence":
        break;
      // Occurs when a user joins a chat room.
      case "memberPresence":
        break;
      // Occurs when custom chat room attributes are set or changed.
      case "updateChatRoomAttributes":
        break;
      // Occurs when custom chat room attributes are removed.
      case "removeChatRoomAttributes":
        break;
      default:
        break;
    }
  },
});

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:

  1. When a user joins a chat room, other members in the chat room receive the memberPresence event. When a member leaves or is removed from a chat room, other members in the chat room receive the memberAbsence event.

  2. After the event is received, you can get the current member count of the chat room by checking the value of the memberCount parameter in the event.

    chatClient.addEventHandler("handlerId", {
      onChatroomEvent: (e) => {
        switch (e.operation) {
          case "memberPresence":
            // The current number of members in the chat room.
            console.log(e?.memberCount);
            break;
          case "memberAbsence":
            // The current number of members in the chat room.
            console.log(e?.memberCount);
            break;
          default:
            break;
        }
      },
    });