Chat room

Update time: 2024/03/07 11:13:59

Chat room

Overview

A chat room is a space where the number of participants is unlimited. Participants can join or leave chat rooms without restrictions. You can create or delete chat rooms by calling corresponding server APIs.

NIMChatroomInfo representation:

Type Attribute Description
String roomId The ID of a chat room.
String? announcement The announcement of a chat room.
String? broadcastUrl The URL for live streaming in a chat room
String? creator The account that created a chat room.
Map<String, dynamic>? extension The extension field of a chat room.
String? name The name of a chat room
int onlineUserCount The number of online users in a chat room.
NIMChatroomQueueModificationLevel queueModificationLevel The queue permission configuration.
bool mute Whether the chat room is muted.
bool validFlag Whether a chat room is valid.

Join a chat room

To send and receive messages in the chat room, you must join a chat room by calling the interface. Users can join a chat room but cannot invite others to join the chat room. An account can join up to 10 chat rooms simultaneously.

  • You can join a chat room in independent mode or in non-independent mode.
  • The independent mode allows users to join a chat room without logging in the IM server. The independent mode is suitable for business scenarios that only require the chat room.
  • The non-independent mode requires users to log in to the IM server first and join the chat room. It is suitable for scenarios that require IM and chat rooms.
dartclass ChatroomService {
  /// Join a chat room
  Future<NIMResult<NIMChatroomEnterResult>> enterChatroom(
      NIMChatRoomEnterRequest request);
}

NIMChatRoomEnterRequest representation

Type Attribute Description
String roomId The ID of a chat room
String? avatar The avatar displayed in a chat room
Map<String, dynamic>? extension The extension field of a profile displayed in a chat room. Up to 4,000 characters are allowed.
You can query the extension field after using ChatRoomMember.
Also you can get the extension field of a user by NIMChatroomMessage#extension#senderExtension
after receiving a message sent by the user in a chat room.
If unspecified, the value is set to null.
String? nickname The nickname of a profile displayed in a chat room, optional.
If unspecified, use the nickname in UserInfo.
Map<String, dynamic>? notifyExtension The extension field of notifications in chat rooms. Up to 2000 characters are allowed.
You can get the extension field using NIMChatroomNotificationAttachment#extension after receiving notifications in chat rooms.
int retryCount The number of retries for joining a chat room. The parameter is not supported on Windows and macOS.

Non-independent mode

When an account is in the logged-in state, call the method of joining a chat room.

  • Example
dart    NimCore.instance.chatroomService.enterChatroom(
      NIMChatRoomEnterRequest(
        roomId: '123456',
        nickname: 'nickname',
        retryCount: 3,
      ),
    ).then((result) {
      if (result.isSuccess) {
        /// success
      } else {
        /// failure
      }
    });

Independent mode

If you join a chat room in independent mode, you must set the attributes of the NIMChatRoomEnterRequest.independentModeConfig field, and its type is NIMChatRoomIndependentModeConfig.

NIMChatRoomIndependentModeConfig representation:

Parameter Type Description
appKey String AppKey used for the independent mode
linkAddresses List<String> The address of a chat room.
account String? The user name used in the independent mode. If the value is set to null, the SDK will generate an anonymous account for login. In anonymous mode, NIMChatRoomEnterRequest must contain the nickname and avatar.
token String? Token used in independent mode. A token is invalid if the user name is empty.
  • Anonymous mode and non-anonymous mode

**The independent mode can be divided into anonymous mode and non-anonymous mode. The anonymous mode can only receive messagesand cannot send messages. **

If NIMChatRoomIndependentModeConfig.account is set to null, the anonymous mode is used. The SDK will use an automatically generated anonymous account to log in. In anonymous mode, NIMChatRoomEnterRequest must contain the nickname and avatar.

  • Get the URL of a chat room

Since the independent mode does not rely on the connection to the IM server, the SDK cannot automatically obtain the address of the chat room. The client must request the address from the app server and the app server requests the address from the CommsEase server, and then return the request result to the client by the original route. The request path is: `client <-> App server <-> CommsEase server (API: request the address of a chat room.

To join a chat room in independent mode, perform the following steps:

  • Get the URL of a chat room

  • Set NIMChatRoomIndependentModeConfig

  • Initialize NIMChatRoomEnterRequest and assign the independentModeConfig field.

  • Call the method used to join a chat room.

  • Example (Joining a chat room in anonymous mode)

dart    NimCore.instance.chatroomService.enterChatroom(
      NIMChatRoomEnterRequest(
        roomId: '123456',
        nickname: 'nickname',
        avatar: 'http://avatar_url.png'
        retryCount: 3,
        independentModeConfig: NIMChatRoomIndependentModeConfig(
          appKey: 'independent_mode_appkey',
          linkAddresses: ['chatroom_link_address'],
        ),
      ),
    ).then((result) {
      if (result.isSuccess) {
        /// success
      } else {
        /// failure
      }
    });

Multi-device login

You can set multi-device login strategy for joining a chat room, specifying whether the same account can join the same chat room at the same time when logging in on different devices. You can configure the multi-device login in the CommsEase console.

  • Only allow one login session
  • Unlimited simultaneous logins. All clients of different platforms can log in at the same time

Listen to the connection changes of a chat room

After joining a chat room, the SDK maintains keep-alive connections with the server and reconnecting after disconnection. Notifications are sent when a user's online status changes. Notifications are also sent for status changes during the automatic login process. The SDK handles the automatic login of the chat room.

  • API prototype
dartclass ChatroomService {
  /// Chat room events
  ///
  /// [NIMChatroomStatusEvent] Chatroom status events
  ///
  /// [NIMChatroomKickOutEvent] Removed from a chat room
  Stream<NIMChatroomEvent> get onEventNotified;
}

The onEventNotified callback can send notification for two events: the connection status event NIMChatroomStatusEvent and the leaving event NIMChatroomKickOutEvent

  • NIMChatroomStatusEvent types
Attribute Description
roomId Chat room ID
status The status code, see NIMChatroomStatus
code The error code, see NIMChatroomErrors
Code Description
:----- :-----------------------
414 Invalid parameter.
404 Chat room does not exist
403 No permissions
500 internal server error
13001 Connection status error
13002 Invalid chat room state
13003 Members in a blocklist are not allowed to join a chat room
  • Example
dart
    final subscription = NimCore.instance.chatroomService
        .onEventNotified.listen((event) {
      if (event is NIMChatroomStatusEvent) {
        /// Notification for the connection status event
      }
    });

    /// If you do not want to listen to the events, unregister the listener
    /// subscription.cancel();

Listen to being removed

The callback is triggered when a user is removed from a chat room or a chat room is closed..

Note that after receiving the notification of being removed from a chat room, the leave interface is not required, and the SDK will leave the chat room. You can clean related cache and interface operations in the notification received for being removed.

  • API prototype
dartclass ChatroomService {
  /// Chat room events
  ///
  /// [NIMChatroomStatusEvent] Chatroom status events
  ///
  /// [NIMChatroomKickOutEvent] Removed from a chat room
  Stream<NIMChatroomEvent> get onEventNotified;
}
  • NIMChatroomKickOutEvent representation
Attribute Description
roomId Chat room ID
reason The reason for being removed. See NIMChatroomKickOutReason
extension The expansion field
NIMChatroomKickOutReason enum Description
:---------------------------- :---------------
blacklisted The account is added to the blocklist.
dismissed The chat room is closed.
byConflictLogin The account logs in on another device.
byManager The account is removed by an administrator.
unknown Unknown error.
  • Example
dart
    final subscription = NimCore.instance.chatroomService
        .onEventNotified.listen((event) {
      if (event is NIMChatroomKickOutEvent) {
        /// Notification for leaving a chat room
      }
    });

    /// If you do not want to listen to the events, unregister the listener
    /// subscription.cancel();

Leave a chat room

If you leave a chat room, you are disconnected from the chat room and no longer receive messages from the chat room. You can also manually call the leave interface that contains no callback.

###Leave a chat room

  • API prototype
dartclass ChatroomService {
  /// Leave a chat room
  Future<NIMResult<void>> exitChatroom(String roomId);
}
  • Example
dartNimCore.instance.chatroomService.exitChatroom(roomId);

Messaging in chat rooms

The NIMChatroomMessage inherits from NIMMessage. The following methods are added:

Type Attribute Description
NIMChatroomMessageExtension extension The extension field of messages in a chat room.
bool isHighPriorityMessage Whether a message has a high priority.
bool enableHistory Whether the message history is stored on the server.
  • To ensure user experience (such as avoiding server overload), two traffic control methods are in place for message receiving. For regular messages, users in chat room can receive up to 20 messages per second, and the excess will be randomly dropped due to traffic control. For high-priority messages, at most 10 messages are received per second. and the excess part cannot be guaranteed not to be lost.
  • To avoid losing important messages (server messages), you can set the HighPriority parameter in request parameters to true to receive server messages with high priority, and ensure that important messages within the upper limit of high-priority message (10 messages per second) are not lost. For more information, see [Send Chat Room Messages](https://doc.commsease.com/docs/TM5MzM5Njk/TYyMDI1MTg?platformId=60353#Send Chat Room Messages).

Send messages in chat rooms

First create a message object NIMChatroomMessage using the interface provided by ChatroomMessageBuilder, and send the message by calling the sendMessage interface of ChatroomService. Note that the interface for creating message objects is also asynchronous.

  • By default, up to 100 calls per second are allowed. - To increase the limit, contact the sales manager over the Whatsapp on the CommsEase website.
  • ChatRoomMessageBuilder interface
Return value Method Description
Future<NIMResult<NIMChatroomMessage>> createChatroomAudioMessage({required String roomId,required String filePath,required int duration,NIMNosScene nosScene = NIMNosScenes.defaultIm,}) Create an audio message. The method is not supported on Windows and macOS.
<> createChatRoomCustomMessage({required Future<NIMResult<NIMChatroomMessage>> createChatroomCustomMessage({required String roomId,NIMMessageAttachment? attachment,}) Create a custom message
Future<NIMResult> createChatroomFileMessage({required String roomId,required String filePath,required String displayName,NIMNosScene nosScene = NIMNosScenes.defaultIm,}) Create a file message. The method is not supported on Windows and macOS.
Future<NIMResult<NIMChatroomMessage>> createChatroomImageMessage({required String roomId,required String filePath,String? displayName,NIMNosScene nosScene = NIMNosScenes.defaultIm,}) Create an audio message. The method is not supported on Windows and macOS.
Future<NIMResult<NIMChatroomMessage>> createChatroomLocationMessage({required String roomId,required double latitude,required double longitude,required String address,}) Create an location message. The method is not supported on Windows and macOS.
Future<NIMResult<NIMChatroomMessage>> createChatroomTextMessage({required String roomId,required String text,}) Create a plain text message.
Future<NIMResult<NIMChatroomMessage>> createChatroomVideoMessage({required String roomId,required String filePath,required int duration,required int width,required int height,String? displayName,NIMNosScene nosScene = NIMNosScenes.defaultIm,}) Create a video message. The method is not supported on Windows and macOS.
Future<NIMResult<NIMChatroomMessage>> createChatRoomVideoMessage(String roomId, File file, long duration, int width, int height, String displayName, String nosTokenSceneKey) Create a video message with a specified NOS scene. The method is not supported on Windwos and macOS.
Future<NIMResult<NIMChatroomMessage>> createChatroomTipMessage({required String roomId,}) Create an alert message. The method is not supported on Windows and macOS.

For the information about nosTokenSceneKey, see [File resources](/en/docs/ how to/ Send and receive messages?#File resources).

The text message is taken as an example below, and other types of message are similar to sending a text message.

  • API prototype
dartclass ChatroomMessageBuilder {
  /// Create a text message.
  static Future<NIMResult<NIMChatroomMessage>> createChatroomTextMessage({
    required String roomId,
    required String text,
  }) async { ... }
}

class ChatroomService {
    /// Send a message in a chat room
    ///
    /// Create a message using [ChatroomMessageBuilder]
    ///
    | resend   | True: resend a message for failure. Otherwise, false. The default value is true.
    Future<NIMResult<NIMChatroomMessage>> sendChatroomMessage(
      NIMChatroomMessage message,
      [bool resend = false]) async {
    ...
  }
}
  • Example
dart    ChatroomMessageBuilder.createChatroomTextMessage(
        roomId: '123456',
        text: 'Hello World!',
    ).then<NIMResult>((result) {
        if (result.isSuccess) {
            return chatroomService.sendChatroomMessage(result.data!);
        } else {
            return result;
        }
    }).then((value) {
        print('ChatroomService##send message: ${value.code} ${value.errorDetails}');
    });
  • Special error codes
Code Description
13004 The account is included in the muted list and not allowed to speak
13006 The chat room is in the all-muted state. Only administrators can speak

Message options

You can set the enableHistory parameter used to specify whether the chat history is stored on the IM server.

NIMChatroomMessage attribute Description
enableHistory Store the message on the IM server. True: the result retrieved using ChatRoomService#pullMessageHistory}
will contain this message.
The default value is true.
  • Example
dartChatroomMessageBuilder.createChatroomTextMessage(
        roomId: '123456',
        text: 'Hello World!',
    ).then<NIMResult>((result) {
        if (result.isSuccess) {
            result.data!.enableHistory = false;
            return chatroomService.sendChatroomMessage(result.data!);
        } else {
            return result;
        }
    }).then((value) {
        print('ChatroomService##send message: ${value.code} ${value.errorDetails}');
    });

Receive messages in a chat room

When a new message arrives, you can receive a notification by listening to the event of message receiving.

  • API prototype
dartclass ChatroomService {
    /// Chat room message
    ///
    Stream<List<NIMChatroomMessage>> get onMessageReceived;
}
  • Example
dartfinal subsription = NimCore.instance.chatroomService.onMessageReceived.listen((messages) {
      messages.forEach((message) {
        print(
            'ChatroomService##on message received: ${message.fromAccount} ${message.fromNickname} '
            '\'${message.content}\'');
      }
});

/// If you do not want to listen to the events, unregister the listener
/// subscription.cancel();
  • To download attachments, use the downloadAttachment method of ChatroomService.
  • To listen to message status changes, use the onMessageStatusChanged event stream of ChatroomService.
  • To listen to the transfer progress of message attachment upload/download, use onMessageAttachmentProgressUpdate of ChatroomService

Notification messages in chat rooms

Some operations in the chat room will generate chat room notification messages. When the following events occur, a notification message will be generated:

NIMChatroomNotificationTypes Description
chatRoomClose The chat room is closed
chatRoomCommonAdd A user is assigned common membership
chatRoomCommonRemove A user is unassigned common membership
chatRoomInfoUpdated The chat room profile is updated
chatRoomManagerAdd A user is assigned administrator
chatRoomManagerRemove A user is unassigned administrator .
chatRoomMemberBlackAdd A user is added to the blocklist
chatRoomMemberBlackRemove A user is removed from the blocklist
chatRoomMemberExit A user leaves a chat room
chatRoomMemberIn A new user joins the chat room
chatRoomMemberKicked A user is removed from a chat room.
chatRoomMemberMuteAdd A user is muted.
chatRoomMemberTempMuteAdd A user is temporarily muted
chatRoomMemberTempMuteRemove A user is temporarily unmuted
chatRoomMyRoomRoleUpdated A user updates the user profile in a chat room, such as nickname, avator, and extension fields.
chatRoomQueueBatchChange The message queue is updated.
chatRoomQueueChange The message queue changes
chatRoomRoomDeMuted All participants in a chat room are unmuted.
chatRoomRoomMuted The chat room is all muted. Only administrators can send messages. Other members are muted.

Note that you can also specify whether to send notifications of members entering and leaving the chat room:

  • For apps, CommsEase console > select application > message delivery for chat room user entry and exit > enable/disable.
  • For a chat room: close the notification for joining and leaving a specified chat room by calling the server API.
  • If you want the chat room message history excluding the chat room user's joining and leaving messages, contact the business consultant to apply for closing the "chat room user's joining and leaving message history".

All chat room notifications are wrapped in ChatRoomMessage. To parse notifications:

Steps:

  • Obtain the message type using NIMChatRoomMessage.messageType. if the type is NIMMessageType.notification, the message is a chat room notification.
  • Convert the attachment object obtained by NIMChatRoomMessage.messageAttachment to NIMChatroomNotificationAttachment.
  • Get the specific NotificationType using NIMChatroomNotificationAttachment.type.
  • Convert the attachment obtained by NIMChatRoomMessage.messageAttachment to NIMChatroomNotificationAttachment or a subclass based on NotificationType.

NIMChatroomNotificationAttachment representation

Method Description
type The type of a notification. See NIMChatroomNotificationTypes
extension The extension field of a notification.
operator The account that performs the operation.
operatorNick The nickname of an account that performs the operation
targets The target accounts that are handled by the operation
targetNicks The nicknames of targets for the operation

Example:

dart/// Notification types in a chat room
class NIMChatroomNotificationTypes {
    static String typeToString(int type) {
      switch (type) {
        case chatRoomMemberIn:
          return 'chatRoomMemberIn';
        case chatRoomMemberExit:
          return 'chatRoomMemberExit';
        case chatRoomMemberBlackAdd:
          return 'chatRoomMemberBlackAdd';
        case chatRoomMemberBlackRemove:
          return 'chatRoomMemberBlackRemove';
        case chatRoomMemberMuteAdd:
          return 'chatRoomMemberMuteAdd';
        case chatRoomMemberMuteRemove:
          return 'chatRoomMemberMuteRemove';
        case chatRoomManagerAdd:
          return 'chatRoomManagerAdd';
        case chatRoomManagerRemove:
          return 'chatRoomManagerRemove';
        case chatRoomCommonAdd:
          return 'chatRoomCommonAdd';
        case chatRoomCommonRemove:
          return 'chatRoomCommonRemove';
        case chatRoomClose:
          return 'chatRoomClose';
        case chatRoomInfoUpdated:
          return 'chatRoomInfoUpdated';
        case chatRoomMemberKicked:
          return 'chatRoomMemberKicked';
        case chatRoomMemberTempMuteAdd:
          return 'chatRoomMemberTempMuteAdd';
        case chatRoomMemberTempMuteRemove:
          return 'chatRoomMemberTempMuteRemove';
        case chatRoomMyRoomRoleUpdated:
          return 'chatRoomMyRoomRoleUpdated';
        case chatRoomQueueChange:
          return 'chatRoomQueueChange';
        case chatRoomRoomMuted:
          return 'chatRoomRoomMuted';
        case chatRoomRoomDeMuted:
          return 'chatRoomRoomDeMuted';
        case chatRoomQueueBatchChange:
          return 'chatRoomQueueBatchChange';
        default:
          return 'unknown';
      }
    }
}

Query message history in the cloud

No offline messages and roaming messages are stored in the chat room. You can query the chat room message history through the interface below. The message history for the recent 10 days is stored on the IM server. However, for files sent 10 days before (such as images, audio, and video), their urls are still valid. You must manage these urls because these urls cannot be queried with expired messages. If you need to extend the "chat room history message days", contact a business consultant.

Query message history in the cloud

Use startTime (in milliseconds) as the starting point of the query, and select the query direction to retrieve the limit number of messages later or earlier. The retrieved messages also include notification messages. You can specify the type of messages to be fetched. If the type is unspecified, all types of messages will be fetched;

If a query starts from an early point to the newest date, the result is displayed in descending order. Otherwise, in ascending order.

dartclass ChatroomService {
  /// Get history messages. The order of the query result can be specified. If a query starts from an early date to the newest date, the result is displayed in descending order. Otherwise, in ascending order
  ///
  /// [roomId] Chat room ID <p>
  /// [startTime] timestamp in milliseconds<p>
  ///[limit]  limit of returned messages<p>
  /// [direction] query direction <p>
  /// [messageTypeList] message type
  Future<NIMResult<List<NIMChatroomMessage>>> fetchMessageHistory({
    required String roomId,
    required int startTime,
    required int limit,
    required QueryDirection direction,
    List<NIMMessageType>? messageTypeList,
  });
}
  • Parameters
Parameter Description
roomId Chat room ID
startTime timestamp in milliseconds
limit limit of returned messages. The maximum number is 100
direction Query direction
messageTypeList Types of messages to be queried.

QueryDirection attribute

Field Description
QUERY_OLD Query messages earlier than the anchor
QUERY_NEW Query messages later than the anchor
  • Example
dart        NimCore.instance.chatroomService.fetchMessageHistory(
            roomId: '123456',
            startTime: DateTime.now().millisecondsSinceEpoch,
            limit: 10,
            direction: QueryDirection.QUERY_OLD,
            messageTypeList: [NIMMessageType.text],
        ).then((messages) {
            var index = 0;
            messages.data?.forEach((message) {
              print(
                  'ChatroomService##message history: ${index++} ${message.fromAccount} ${message.fromNickname} '
                  '\'${message.content}\'');
            });
        });

Manage chat room information

Get the profile of a chat room

Get the profile of a chat room. The SDK does not cache the chat room information, and you can cache the required information. The extended fields of the basic information of the chat room need to be set on the server and the client SDK can only query the information.

  • API prototype
dartclass ChatroomService {
    /// Get the chat room info.
    Future<NIMResult<NIMChatroomInfo>> fetchChatroomInfo(String roomId);
}
  • Example
dartNimCore.instance.chatroomService.fetchChatroomInfo('123456')
    .then(
        (value) {
            print(
                'ChatroomService##fetch updated chatroom info: ${value.data?.name} '
                '${value.data?.announcement}');
        }
    );

Edit the profile of a chat room

Edit the chat room information. Only creators and administrators have permission to modify chat room information. You can specify whether notifications are sent when the profile of a chat room is edited. If you enable the notification, the chat room will receive a message of type NotificationType#ChatRoomInfoUpdated.

  • API prototype
dartclass ChatroomService {
  /// Update the chat room info.
  Future<NIMResult<void>> updateChatroomInfo({
    required String roomId,
    required NIMChatroomUpdateRequest request,
    bool needNotify = true,
    Map<String, dynamic>? notifyExtension,
  });
}
  • Parameters
Parameter Description
roomId Chat room ID
request Profile fields to be edited.
needNotify Whether notifications will be sent when the profile of a chat room is edited.
notifyExtension The extension field for updating the chat room profile in a notification
NIMChatroomUpdateRequest Description
:----------------------- :--------------------------------------------------------------------------------------------------
name The name of a chat room.
announcement announcement of a chat room.
broadcastUrl The broadcast URL
extension The custom extension field.
queueLevel Queue management permissions. For example, submit the key and message of other users to the queue. 0: all users have the permissions. 1: only the owner and administrators have the permissions.
  • Example
dart        NimCore.instance.chatroomService
              .updateChatroomInfo(
            roomId: '123456',
            request: NIMChatroomUpdateRequest(
              announcement: 'Edit the announcement',
            ),
            needNotify: true,
        ).then((value) {
            print(
                'ChatroomService##set chatroom announcement:  ${value.code} ${value.errorDetails}');
        });

Manage members

Overview

About members

  • Members include into two categories: permanent members and temporary members. The upper limit of permanent members is 1000.
  • Permanent members include the owner, administrators, regular members, restricted members. Restricted members include members in the blocklist and muted list.
  • Except for the creator, when other members join a chat room, they are all guests by default.
  • If a guest is assigned admin and then unassign administrator, it becomes a regular member (not a guest).
  • In the chat rooms, to turn an administrator to regular participant, you can revoke the administrator role. You cannot set admin as regular member.
  • Only the creator can manage administrators. Administrators have no permission to manage the creator.
  • Regular members become guest after being revoked.
  • If a guest is added to the blocklist, the guest becomes a permanent member and is disconnected by the server and cannot join the chat room unless the member is removed from the blocklist. After being removed the blacklist, a permanent member becomes a guest.
  • After being permanently muted, the role becomes a permanent member. After being permanently unmuted, the role becomes a guest. After being permanently unmuted, the expiration time of the temporary mute will not be affected.
  • Temporary muting or unmuting members does not change the role. If you repeatedly muting a member, the later mute will overwrite the expiration time of the previous mute.
  • Guests are temporary members of the chat room. Guests does not belong to any chat rooms.

ChatRoomMember interface

Type NIMChatroomMember attribute Description
String roomId The ID of a chat room.
String account The member account
String? avatar Get the avatar displayed in a chat room. You can get the avatar from NimUserInfo or submitted by users when joining a chat room
int? enterTime The time when a member joins a chat room. The field is empty for offline members
Map<String, dynamic>? extension The extension field. * The extension field can contain 4000 characters and is submitted by users when joining a chat room
NIMChatroomMemberType memberType The member type. Member types: guests or non guests
String? nickname The nickname displayed in a chat room. Get the nickname from NimUserInfo or submitted by users when joining a chat room
int? tempMuteDuration The duration of a temporary mute in seconds
bool isInBlackList Whether a member is included in a blocklist
bool isMuted Whether a member is muted
bool isOnline Whether a member is online. Only special members may be offline, and guests or anonymous users must be online.
bool isTempMuted Whether a member is temporary muted
bool isValid Whether a chat room is valid

NIMChatroomMemberType member types:

Type Description
unknown Unknown member type
guest A guest
restricted Restricted members indicates members included in a muted list or blocklist
normal Regular member (non-guest)
creator The account that creates the chat room (non-guest)
manager Administrator (non-guest)
anonymous anonymous guest

Get the members in a chat room

Get the members in a chat room in pagination

This interface can obtain the list of members. The SDK will not cache the list of members. You must cache the data based on your business requirements.

  • API prototype
dartclass ChatroomService {
  /// Get members in a chat room
  ///
  /// [roomId] Chat room ID <p>
  /// [queryType] Query type, [NIMChatroomMemberQueryType]
  ///[limit]  limit of returned messages<p>
  ///[lastMemberAccount] The last anchor of a member account excluded in the returned data. If the value of `lastMemberAccount is empty, starts the query from the current time. <p>
  Future<NIMResult<List<NIMChatroomMember>>> fetchChatroomMembers({
    required String roomId,
    required NIMChatroomMemberQueryType queryType,
    required int limit,
    String? lastMemberAccount,
  });
}
  • Parameters
Parameter Description
roomId Chat room ID
queryType Member type See NIMChatroomMemberQueryType
lastMemberAccount] The last anchor of a member account excluded in the returned data. If the value of `lastMemberAccount is empty, starts the query from the current time. |
limit Limit of members
NIMChatroomMemberQueryType Description
:------------------------------- :--------------------------------------------------------------------------------------------------------------------
allNormalMember Permanent members
, including the owner, administrators, members, restricted members in a muted list and blacklist.
If members are offline, they are visible in a limited number.
onlineNormalMember Online permanent members
onlineGuestMemberByEnterTimeDesc Temporary members that are visible if online. The number is unlimited.
The guests are displayed in descending order.Guests joining later are shown at the top.
onlineGuestMemberByEnterTimeAsc Temporary members that are visible if online. The number is unlimited.
The guests are displayed in ascending order. Guest joining earlier are shown at the top
  • Example
dart
    NimCore.instance.chatroomService.fetchChatroomMembers(
      roomId: chatroomId,
      queryType: NIMChatroomMemberQueryType.allNormalMember,
      limit: 10,
    ).then((result) {
      var index = 0;
      result.data?.forEach((member) {
        print(
            'ChatroomService fetchChatroomMembers ##member_${index++}: ${member.account} ${member.nickname} ${member.memberType}');
      });
    });

Get the specified members in chat rooms

dartclass ChatroomService {
  /// Get members in a chat room
  ///
  /// [roomId] Chat room ID <p>
  /// [accountList] member accounts <p>
  Future<NIMResult<List<NIMChatroomMember>>> fetchChatroomMembersByAccount({
    required String roomId,
    required List<String> accountList,
  });
}
  • Example
dart    NimCore.instance.chatroomService.fetchChatroomMembersByAccount(
      roomId: chatroomId,
      accountList: ['account1', 'account2'],
    ).then((result) {
      var index = 0;
      result.data?.forEach((member) {
        print(
            'ChatroomService fetchChatroomMembers ##member_${index++}: ${member.account} ${member.nickname} ${member.memberType}');
      });
    });

Edit the profile of the current user

Edit the profile of the current user in a chat room. You can edit the nickname, avatar, and values in extension fields. You can set whether notifications are sent when the profile of a chat room is edited. If you enable the notification, the chat room will receive a message of type NotificationType#ChatRoomInfoUpdated.

dartclass ChatroomService {
  /// Update the profile of the current user in a chat room.
  /// [roomId]               Chat room ID
  /// [request]              Editable profile fields
  /// [needNotify]           Specify whether notifications will be sent
  /// [notifyExtension] extension field for updating the chat room profile in a notification
  Future<NIMResult<void>> updateChatroomMyMemberInfo({
    required String roomId,
    required NIMChatroomUpdateMyMemberInfoRequest request,
    bool needNotify = true,
    Map<String, dynamic>? notifyExtension,
  });
}
  • Parameters
Parameter Description
roomId Chat room ID
request Profile fields to be edited
needNotify Whether notifications will be sent when the profile of a chat room is edited.
notifyExtension The extension field of the notification for updating the chat room profile.

NIMChatroomUpdateMyMemberInfoRequest class

Type Class member Description
String? avatar The avatar displayed in a chat room
Map<String, dynamic>? extension The extension field.
String? nickname The nickname displayed in a chat room
bool needSave Whether the updated information is persisted. The setting is applied only to members. The default value is false.
  • Example
dart    /// Update the nickname of the current user
    NimCore.instance.chatroomService
        .updateChatroomMyMemberInfo(
      roomId: chatroomId,
      request: NIMChatroomUpdateMyMemberInfoRequest(
        nickname: 'New nickname',
        needSave: true,
      ),
    ).then((value) {
      print(
          'ChatroomService##update chatroom my info:  ${value.code} ${value.errorDetails}');
    });

Add or remove admins

dartclass ChatroomService {
  ///
  /// Assign or unassign the administrator role
  ///
  ///[ isAdd ] true: Assign the administrator role; false: unassign the administrator role.
  ///[ memberOption ] Request parameters, such as chat room ID, account ID, and optional extension fields
  Future<NIMResult<NIMChatroomMember>> markChatroomMemberBeManager({
    required bool isAdd,
    required NIMChatroomMemberOptions options,
  });
}
  • NIMChatroomMemberOptions class
Return value Class member Description
String roomId The ID of a chat room.
String account The member account
Map<String, dynamic>? getNotifyExtension() Get the custom extension field of notifications for specified events.
  • Example
dart    /// Assign the administrator role to a member
    NimCore.instance.chatroomService
        .markChatroomMemberBeManager(
      isAdd: true,
      options: NIMChatroomMemberOptions(
        roomId: '123456',
        account: 'account',
      ),
    ).then((value) {
      print(
          'ChatroomService##markChatroomMemberBeManager:  ${value.code} ${value.errorDetails}');
    });

Assign or revoke membership of a user

dartclass ChatroomService {
  ///
  /// Assign or revoke membership of a user
  ///
  ///[ isAdd ] true: Assign the administrator role; false: unassign the administrator role.
  ///[ memberOption ] Request parameters, such as chat room ID, account ID, and optional extension fields
  Future<NIMResult<NIMChatroomMember>> markChatroomMemberBeNormal({
    required bool isAdd,
    required NIMChatroomMemberOptions options,
  });
}
  • Example
java/// Assign a regular member
    NimCore.instance.chatroomService
        .markChatroomMemberBeNormal(
      isAdd: true,
      options: NIMChatroomMemberOptions(
        roomId: '123456',
        account: 'account',
      ),
    ).then((value) {
      print(
          'ChatroomService##markChatroomMemberBeNormal:  ${value.code} ${value.errorDetails}');
    });

Add to or remove from the blocklist

dartclass ChatroomService {
  ///
  /// Add to or remove from the blocklist of a chat room
  ///
  ///[ isAdd ] true: Assign the administrator role; false: unassign the administrator role.
  ///[ memberOption ] Request parameters, such as chat room ID, account ID, and optional extension fields
  Future<NIMResult<NIMChatroomMember>> markChatroomMemberInBlackList({
    required bool isAdd,
    required NIMChatroomMemberOptions options,
  });
}
  • Example
dart    /// Add a member to the blocklist
    NimCore.instance.chatroomService
        .markChatroomMemberInBlackList(
      isAdd: true,
      options: NIMChatroomMemberOptions(
        roomId: '123456',
        account: 'account',
      ),
    ).then((value) {
      print(
          'ChatroomService##markChatroomMemberInBlackList:  ${value.code} ${value.errorDetails}');
    });

Mute or unmute members

When muting a member, a notification message of type ChatRoomMemberMuteAdd will be received.

When unmuting a member, you will receive a notification message of type ChatRoomMemberMuteRemove.

dartclass ChatroomService {
  ///
  /// Mute or unmute members in a chat room.
  ///
  ///[ isAdd ] true: Assign the administrator role; false: unassign the administrator role.
  ///[ memberOption ] Request parameters, such as chat room ID, account ID, and optional extension fields
  Future<NIMResult<NIMChatroomMember>> markChatroomMemberMuted({
    required bool isAdd,
    required NIMChatroomMemberOptions options,
  });
}
  • Example
dart/// Add a member to the muted list
    NimCore.instance.chatroomService
        .markChatroomMemberMuted(
      isAdd: true,
      options: NIMChatroomMemberOptions(
        roomId: '123456',
        account: 'account',
      ),
    ).then((value) {
      print(
          'ChatroomService##markChatroomMemberMuted:  ${value.code} ${value.errorDetails}');
    });

Remove a specified member

Remove a specified member Only administrators can remove members. Only the owner can remove administrators..

When removing a member, a notification message of type ChatRoomMemberKicked will be received.

You can add an extension field for being removed in a notification. The extension field of the notification can contain up to 1000 characters. The type of the extension field is Map<String, dynamic>.

dartclass ChatroomService {
  ///
  /// Remove a specified member in a chat room
  ///
  ///[ memberOption ] Request parameters, such as chat room ID, account ID, and optional extension fields
  Future<NIMResult<void>> kickChatroomMember(NIMChatroomMemberOptions options);
}
  • Example
dart    NimCore.instance.chatroomService
        .kickChatroomMember(
      NIMChatroomMemberOptions(
        roomId: '123456',
        account: 'account',
      ),
    ).then((value) {
      print(
          'ChatroomService##kickChatroomMember:  ${value.code} ${value.errorDetails}');
    });

Temporarily mute a member

When muting a member, a notification message of type ChatRoomMemberTempMuteAdd will be received.

When unmuting a member, you will receive a notification message of type ChatRoomMemberTempMuteRemove.

You can set the duration for muting a user. When the mute state is due, the mute state will be automatically canceled.. In the notification message after the temporary mute, the duration included is the remaining duration of the mute. If the value is set to 0, a member is unmuted. If the mute period set for the first time is not due yet, a second temporary mute starts counting from the time set for the second time.

dartclass ChatroomService {
  ///
  /// Temporarily mute or unmute members in a chat room.
  ///
  /// [duration]   Mute duration in milliseconds. Setting the value to 0 wull unmute a member.
  ///[ memberOption ] Request parameters, such as chat room ID, account ID, and optional extension fields
  /// [needNotify]  Specify whether notifications are broadcast. True: broadcast notifications to all members; false: does not broadcast notifications to all members.
  Future<NIMResult<void>> markChatroomMemberTempMuted({
    required int duration,
    required NIMChatroomMemberOptions options,
    bool needNotify = false,
  });
}
  • Parameters
Parameter Description
duration The duration when a member is muted in milliseconds
memberOption Parameter for members in chat rooms, such as chat room ID, account ID, and optional extension field.
needNotify Whether notifications are broadcast. True: broadcast notifications to all members; false: does not broadcast notifications to all members.
  • Example
dart/// Broadcast a notification and temporarily mute a member for 10 seconds
    NimCore.instance.chatroomService
        .markChatroomMemberTempMuted(
      duration: 10 * 1000,
      options: NIMChatroomMemberOptions(
        roomId: '123456',
        account: 'account',
      ),
      needNotify: true,
    ).then((value) {
      print(
          'ChatroomService##markChatroomMemberTempMuted:  ${value.code} ${value.errorDetails}');
    });

Chat room queue

Chat room queue is provided for seat management in interactive live streaming. Permissions are determined by NIMChatroomInfo.queueModificationLevel and can be modified by updateChatroomInfo. By default, all users can call the interface to modify the queue content.

Get the chat room queue

dartclass ChatroomService {
  ///  Get a chat room queue
  ///
  /// [roomId] Chat room ID <p>
  Future<NIMResult<List<NIMChatroomQueueEntry>>> fetchChatroomQueue(
      String roomId);
}
  • Example
dart    NimCore.instance.chatroomService
        .fetchChatroomQueue('123456')
        .then((value) {
      print('ChatroomService##poll queue: ${value.code} ${value.errorDetails} '
          '${value.data?.map((e) => '${e.key}:${e.value}').toList()}');
    });

Add or update elements

Elements are added or updated using this interface. If the isTransient parameter is true, the server will automatically delete the element added or updated by the user when the user gets disconnected or leaves the chat room.

The server will send a notification message of NIMChatroomNotificationTypes#chatRoomQueueBatchChange type, and the attachment type of the notification message is NIMChatroomQueueChangeAttachment. The notification message are sent when the queue changes. The attachment type includes the queue change type NIMChatroomQueueChangeType#partialClear.

dartclass ChatroomService {
  /// Update a chat room queue
  ///
  /// [roomId] Chat room ID <p>
  /// [entry] Elements to be updated <p>
  /// [isTransient] (optional, the default value is false). true: Elements are deleted when a user gets disconnected or leaves a chat room. The default false value indicates that elements are not deleted.
  Future<NIMResult<void>> updateChatroomQueueEntry({
    required String roomId,
    required NIMChatroomQueueEntry entry,
    bool isTransient = false,
  });
}
  • Parameters
Parameter Description
roomId Chat room ID
entry A new element
isTransient (optional)
true: delete an element when a user that submits the element gets disconnected or leaves a chat room. The default value false indicates that an element is not deleted.

NIMChatroomQueueEntry class

Parameter Description
key unique key for a new or updated element
value value of a new or updated element

NIMChatroomQueueChangeAttachment class

Type Member Description
NIMChatroomQueueChangeType queueChangeType Returns the type of a queue change. The value is NIMChatroomQueueChangeType.
Map<String, String>? contentMap When a user gets disconnected or leaves a chat room, elements are added or updated using updateQueueEx and the isTransient parameter is set to true
  • Example
dartNimCore.instance.chatroomService
        .updateChatroomQueueEntry(
      roomId: chatroomId,
      entry: NIMChatroomQueueEntry(
        key: 'key',
        value: 'value',
      ),
    ).then((value) {
      print(
          'ChatroomService##updateChatroomQueueEntry: ${value.code} ${value.errorDetails}');
    });

Update multiple elements in a chat room queue

Only existing keys will be updated. No new elements will be added.

dartclass ChatroomService {
  /// Update multiple elements in a queue
  ///
  /// [roomId] Chat room ID <p>
  /// [entry] Elements to be updated<p>
  /// [needNotify]     specify whether broadcast notifications are sent. <p>
  /// [notifyExtension] extension field in notifications <p>
  /// Returns a list of elements that are not in the queue
  Future<NIMResult<List<String>>> batchUpdateChatroomQueue({
    required String roomId,
    required List<NIMChatroomQueueEntry> entryList,
    bool needNotify = true,
    Map<String, Object>? notifyExtension,
  });
}
  • Example
dartNimCore.instance.chatroomService
        .batchUpdateChatroomQueue(
      roomId: chatroomId,
      entryList: [
        NIMChatroomQueueEntry(
          key: 'key',
          value: 'value',
      )],
    ).then((value) {
      print(
          'ChatroomService##batchUpdateChatroomQueue: ${value.code} ${value.errorDetails}');
    });

Remove a specified element

The key is unique. If the key is set to null, the first element is selected. If the key is not null, the specified element is selected.

dartclass ChatroomService {
  /// Remove an element from a list
  ///
  /// [roomId] Chat room ID <p>
  /// [key] Key to be deleted. A value of null indicates that the first element will be removed.<p>
  Future<NIMResult<NIMChatroomQueueEntry>> pollChatroomQueueEntry(
      String roomId, String? key);
}
  • Parameters
Parameter Description
roomId Chat room ID
key The unique key of an element to be removed. If a value of null is used, the first element is removed.
  • Example
dart    NimCore.instance.chatroomService
        .pollChatroomQueueEntry(
      chatroomId,
      'key',
    ).then((value) {
      print(
          'ChatroomService##batchUpdateChatroomQueue: ${value.code} ${value.errorDetails}');
    });

Delete a queue

dartclass ChatroomService {
  /// Clear a queue
  Future<NIMResult<void>> clearChatroomQueue(String roomId);
}
  • Example
java    NimCore.instance.chatroomService
        .clearChatroomQueue(
      '123456',
    ).then((value) {
      print(
          'ChatroomService##clearChatroomQueue: ${value.code} ${value.errorDetails}');
    });
Was this page helpful?
Yes
No
  • Overview
  • Join a chat room
  • Non-independent mode
  • Independent mode
  • Multi-device login
  • Listen to the connection changes of a chat room
  • Listen to being removed
  • Leave a chat room
  • Messaging in chat rooms
  • Send messages in chat rooms
  • Message options
  • Receive messages in a chat room
  • Notification messages in chat rooms
  • Query message history in the cloud
  • Query message history in the cloud
  • Manage chat room information
  • Get the profile of a chat room
  • Edit the profile of a chat room
  • Manage members
  • Overview
  • Get the members in a chat room
  • Get the members in a chat room in pagination
  • Get the specified members in chat rooms
  • Edit the profile of the current user
  • Add or remove admins
  • Assign or revoke membership of a user
  • Add to or remove from the blocklist
  • Mute or unmute members
  • Remove a specified member
  • Temporarily mute a member
  • Chat room queue
  • Get the chat room queue
  • Add or update elements
  • Update multiple elements in a chat room queue
  • Remove a specified element
  • Delete a queue