Manage chat rooms

Update time: 2023/08/08 06:16:47

Overview

CommsEase provides the chat room feature. There is no upper limit for the number of users. Users can freely join and leave a chat room. The creation and closure of a chat room needs to be completed through the server-side API.

A chat room prototype:

Return ChatRoomInfo interface Description
String getAnnouncement() Get announcement of chat room
String getBroadcastUrl() Get live streaming address of chat room
String getCreator() Get owner account of chat room
Map getExtension() Get the extension field of chat room
String getName() Get name of chat room
int getOnlineUserCount() Get number of current online users
int getQueueLevel() Get configuration of queue level
String getRoomId() Get chat room ID
boolean isMute() Get mute state of current chat room
boolean isValid() Set valid tag of chat room
void setAnnouncement(String announcement) Set announcement of chat room
void setBroadcastUrl(String broadcastUrl) Set live streaming address of chat room
void setCreator(String creator) Set owner of chat room
void setExtension(Map extension) Set extension field
void setMute(int mute) Set mute state of current chat room
void setName(String name) Set name of chat room
void setOnlineUserCount(int onlineUserCount) Set number of current online users
void setRoomId(String roomId) Set Chat room ID
void setValidFlag(int validFlag) Set valid tag of chat room
void setQueueLevel(int queueLevel) Set queue level: 0 indicates permission of all members; 1 indicates permission of only streamer/administrator

Joining a chat room

Users must call the interface to join a chat room before sending and receiving messages in a chat room. The chat room allows users to join manually only and cannot send an invitation. Users can join up to 10 chat rooms at the same time.

  • Users can join a chat room in independent mode or non-independent mode.
  • The independent mode refers to the method for joining a chat room when the IM is not logged in, which applies to the service scenarios that only need the chat room feature.
  • The non-independent mode refers to the method for joining a chat room after logging in to the IM, which applies to the service scenarios that need the IM and chat room features.
java/**
 * Enter a chat room
 *
 * @param roomData - Basic data of chat room (Chat room ID is required)
 * @param retryCount - It is the retry count if joining is failed.
 * @return InvocationFuture - Configurable callback feature. The basic information about the chat room is returned in the callback.
 */
AbortableFuture<EnterChatRoomResultData> joinChatRoomEx(EnterChatRoomData roomData, int retryCount);

EnterChatRoomData parameter:

Return EnterChatRoomData parameter Description
String getAccount() Get user account of independent login mode
String getAppKey() Get chat room appKey
String getAvatar() Get profile picture shown in a chat room
Map getExtension() Get the extension field shown in a chat room
ChatRoomIndependentCallback getIndependentModeCallback() Get callback of independent mode
String getNick() Get display name shown in a chat room
Map getNotifyExtension() Get the extension field of notifying developer in a chat room
String getRoomId() Get chat room ID
String getToken() Get user password of independent login mode
boolean isIndependentMode() Log in a chat room independently
void setAppKey(String appKey) Set chat room appKey and enable under independent login mode. If it is not specified, then corresponding appKey of IM is used and corresponding relationship between roomId and appKey needs to be guaranteed.
void setprofile picture(String profile picture) Set profile picture shown in a chat room
void setExtension(Map
extension)
Set extension field of showing user profile after joining chat room, with length limit 4k.
Users can query this extension field when acquiring ChatRoomMember after settings.
In addition, when receiving messages, users can
acquire the extension field of a user profile for message sender from ChatRoomMessage#ChatRoomMessageExtension#getSenderExtension.
If it is not filled, then the field is null.
void setIndependentMode(ChatRoomIndependentCallback cb, String account, String token) Set independent mode of chat room
void setNick(String nick) Set display name shown in a chat room (optional field).
If it is not filled in, display name in NimUserInfo is used.
void setNotifyExtension
(Map
notifyExtension)
Set extension field of a notification message in a chat room, with a length limit of 2k.
Users can get this extension field from
ChatRoomNotificationAttachment after settings.
void setRoomId(String roomId) Set Chat room ID

Non-independent mode

The non-independent mode is simple. When IM is at the login state, users can call the method to join the chat room.

  • Example
java// roomId indicates chat room ID
EnterChatRoomData data = new EnterChatRoomData(roomId);
// Take "log in for once without retry" for an example
NIMClient.getService(ChatRoomService.class).joinChatRoomEx(data, 1).setCallback(new RequestCallback<EnterChatRoomResultData>() {
    @Override
    public void onSuccess(EnterChatRoomResultData result) {
        // Login successful
    }

    @Override
    public void onFailed(int code) {
        // Login failed
    }

    @Override
    public void onException(Throwable exception) {
        // Error
    }
});

Independent mode

When selecting to join the chat room by independent mode, users must set the independent mode of chat room through EnterChatRoomData.setIndependentMode(...) method.

  • API prototype
java/**
 * Set independent mode of chat room
 *
 * @param cb - If it is the independent mode, the callback feature must be provided to acquire the data of chat room address from app by SDK.
 * @param account - Account of independent login, not required. Void indicates anonymous login.
 * @param token - Password for independent login
 */
public void setIndependentMode(ChatRoomIndependentCallback cb, String account, String token);
  • Parameters
Parameter Description
cb If it is an independent mode, the callback feature must be provided to acquire the data of chat room address from app by SDK.
account Account of independent login, not required. Void indicates anonymous login.
token Password of independent login
  • Anonymous mode and non-anonymous mode

The independent mode includes anonymous mode and non-anonymous mode. Users can receive a message and cannot send a message under anonymous mode.

If transfer parameter account of setIndependentMode method is not filled in, then it is an anonymous mode. SDK will log in by an automatically generated anonymous account. Under anonymous mode, users must set display name and profile picture information through SetNick and setprofile picture of EnterChatRoomData.

  • Get the chat room address

Because independent mode does not rely on IM connection, SDK cannot get the address of chat room server automatically, and needs to request the address to developer app server from client, while app server needs to request CommsEase server, and then returns request result to the client, with request path Client <-> Developer Application Server <-> CommsEase Server (API: request chat room address).

The callback method of acquiring chat room address through developer app server by SDK must be set using ChatRoomIndependentCallback - getChatRoomLinkAddresses:

java/**
 * Callback feature for independent login mode of the chat room. It is used to provide data to SDK by upper APP.
 */ 
java.util.List<java.lang.String> getChatRoomLinkAddresses(java.lang.String roomId,
                                                          java.lang.String account);
  • Example

Example 1: Anonymous login under independent mode

java// roomId - Chat room ID
EnterChatRoomData data = new EnterChatRoomData(roomId);

// Log in a chat room by anonymous mode under independent mode
data.setNick("testNick"); // For this mode, display name is required. Take testNick for an example
data.setprofile picture("profile picture"); // For this mode,profile picture is required. Takeprofile picture for an example
data.setIndependentMode(new ChatRoomIndependentCallback() {
    @Override
    public List<String> getChatRoomLinkAddresses(String roomId, String account) {
        // Request chat room address from app server, instead of SDK interface
        return ChatRoomHttpClient.getInstance().fetchChatRoomAddress(roomId, null);
    }
}, null, null);

NIMClient.getService(ChatRoomService.class).joinChatRoomEx(data, 1).setCallback(new RequestCallback<EnterChatRoomResultData>() {
    @Override
    public void onSuccess(EnterChatRoomResultData result) {

    }

    @Override
    public void onFailed(int code) {

    }

    @Override
    public void onException(Throwable exception) {

    }
});

Example 2: Non-anonymous login under independent mode

java// roomId - Chat room ID
EnterChatRoomData data = new EnterChatRoomData(roomId);

// Non-anonymous login of independent mode. Account and password are required. The account and token are taken for examples.
data.setIndependentMode(new ChatRoomIndependentCallback() {
    @Override
    public List<String> getChatRoomLinkAddresses(String roomId, String account) {
        // Request chat room address from app server, instead of SDK interface
        return ChatRoomHttpClient.getInstance().fetchChatRoomAddress(roomId, "account");
    }
}, "account", "token");

NIMClient.getService(ChatRoomService.class).joinChatRoomEx(data, 1).setCallback(new RequestCallback<EnterChatRoomResultData>() {
    @Override
    public void onSuccess(EnterChatRoomResultData result) {

    }

    @Override
    public void onFailed(int code) {

    }

    @Override
    public void onException(Throwable exception) {

    }
});

Multi-device login to the same chat room

The policy for multi-device login to the same chat room can be set, that is, whether multi-device login with the same account to the same chat room at the same time is allowed. Users can join the CommsEase console to set:

  • Login to only one device
  • Simultaneous login at all clients.

Listening for connection changes of a chat room

After successfully joining a chat room, SDK will maintain long-lived connection with the server, disconnection, and re-connection. The notification will be sent when an online state of users has any change. The state callback also occurs in the process of login. In addition, SDK will undertake automatic login of chat room after network connection.

  • API prototype
java/**
 * Register or cancel observer for online/login status of chat room
 *
 * @param observer - Observer. The parameter is chat room ID and chat room status (not join, connecting, joining, joined).
 * @param register true indicates registered, and true indicates unregistered
 */
public void observeOnlineStatus(Observer<ChatRoomStatusChangeData> observer, boolean register);
  • Parameters
ChatRoomStatusChangeData attribute Description
roomId Chat room ID
status Status code (See StatusCode)

In addition, Users can call the SDK interface in a callback of state change observer to acquire the cause of failure in server return and make corresponding processing on the interface.

  • API prototype
java/**
 * Get the error code for failing in joining a chat room
 * If it is manual login, an error code can be found in the callback feature of joinChatRoom.
 * If it is disconnected and re-connected again, when automatic login is failed, i.e. the monitored change in online status is UNLOGIN, the detailed reason for failing in automatic login can be viewed using the interface.
 *
 * @param roomId - Chat room ID
 * @return - Error code for disconnection and re-connection of the chat room and failed automatic login.
 */
int getEnterErrorCode(String roomId);
  • Parameters
Error code Description
414 Error parameter
404 No chat room
403 No permissions
500 Server Internal Error
13001 IM main connection status is abnormal
13002 Chat room status is abnormal
13003 Not allow members in Blocklist to join a chat room
  • Example
javaNIMClient.getService(ChatRoomServiceObserver.class).observeOnlineStatus(onlineStatus, register);

Observer<ChatRoomStatusChangeData> onlineStatus= new Observer<ChatRoomStatusChangeData>() {
        @Override
        public void onEvent(ChatRoomStatusChangeData data) {
            if (data.status == StatusCode.UNLOGIN) {
                int errorCode = NIMClient.getService(ChatRoomService.class).getEnterErrorCode(roomId));
                // If error codes (13001, 13002, 13003, 403, 404, 414) are returned, it indicates that you cannot join the chat room and must invoke the interface for leaving a chat room.
            }
           ...
        }
};

Listening for kickout events

The kickout event triggers a callback function if a user is kicked out of a chat room or the chat room is closed.

Note: After receiving kickout notification, the user is not required to call the interface of leaving chat room, SDK will undertake the leave from chat room. The user can clear related cache in kickout notification and do interface work.

  • API prototype
java/**
 * Register or cancel the observer kicked out of a chat room.
 *
 * @param observer - Observer. The parameter is kick-out event (the removed chat room ID and kick-out reason can be acquired).
 * @param register true indicates registered, and true indicates unregistered
 */
public void observeKickOutEvent(Observer<ChatRoomKickOutEvent> observer, boolean register);
  • Parameters

ChatRoomKickOutEvent.ChatRoomKickOutReason attribute

ChatRoomKickOutEvent.ChatRoomKickOutReason attribute Description
BE_BlocklistED added to a Blocklist
CHAT_ROOM_INVALID Invalid chat room
Invalid_STAT Abnormal status of current connection
KICK_OUT_BY_CONFLICT_LOGIN Kick out by other clients
KICK_OUT_BY_administrator Kick out by the administrator
UNKNOWN Unknown (error)
  • Example
javaNIMClient.getService(ChatRoomServiceObserver.class).observeKickOutEvent(kickOutObserver, register);

Observer<ChatRoomKickOutEvent> kickOutObserver = new Observer<ChatRoomKickOutEvent>() {
        @Override
        public void onEvent(ChatRoomKickOutEvent chatRoomKickOutEvent) {
            // Prompt kick-out reason (the chat room is dismissed; the user is kicked out by administrator or kicked out from other clients)
            // Clear cache data
        }
    };

Leaving a chat room

When leaving from a chat room, the user will disconnect from a chat room and will not receive any message from the chat room. If the user wants to leave from a chat room, he can manually call the interface of leaving from the chat room where there is no callback.

###Leaving a chat room

  • API prototype
java/**
 * Leave a chat room
 *
 * @param roomId - Chat room ID
 */
void leaveChatRoom(String roomId);
  • Example
javaNIMClient.getService(ChatRoomService.class).leaveChatRoom(roomId);

Leave a chat room of a specific type

  • API prototype
java/**
 * Leave a chat room
 *
 * @param mode - Chat room type
 */
void leaveChatRooms(ChatRoomModeEnum mode);
  • Example
javaNIMClient.getService(ChatRoomService.class).leaveChatRoom(ChatRoomModeEnum.DEPENDENT);

Messaging in a chat room

ChatRoomMessage succeeds from IMMessage. New methods include:

Return ChatRoomMessage interface Description
CustomChatRoomMessageConfig getChatRoomConfig() Get message configuration of chat room
ChatRoomMessageExtension getChatRoomMessageExtension() Get extension attribute of chat room message
boolean isHighPriorityMessage() Is it high priority message?
void setChatRoomConfig
(CustomChatRoomMessageConfig config)
Set configuration of chat room message

Sending messages

The user can create a message object using ChatRoomMessageBuilder and then call sendMessage of ChatRoomService to send a message in the chat room.

  • ChatRoomMessageBuilder interface
Return ChatRoomMessageBuilder interface Description
static ChatRoomMessage createChatRoomAudioMessage(String roomId, File file, long duration) Create an audio message
static ChatRoomMessage createChatRoomAudioMessage(String roomId, File file, long duration, String nosTokenSceneKey) Create an audio message and specify scenario of file resource
static ChatRoomMessage createChatRoomCustomMessage(String roomId, MsgAttachment attachment) Create user-defined scenario
static ChatRoomMessage createChatRoomCustomMessage(String roomId, MsgAttachment attachment, String nosTokenSceneKey) Create user-defined message and specify scenario of file resource
static ChatRoomMessage createChatRoomFileMessage(String roomId, File file, String displayName) Create a file message
static ChatRoomMessage createChatRoomFileMessage(String roomId, File file, String displayName, String nosTokenSceneKey) Create a file message and specify scenario of file resource
static ChatRoomMessage createChatRoomImageMessage(String roomId, File file, String displayName) Create an image message
static ChatRoomMessage createChatRoomImageMessage(String roomId, File file, String displayName, String nosTokenSceneKey) Create an image message and specify scenario of file resource
static ChatRoomMessage createChatRoomLocationMessage(String roomId, double lat, double lng, String addr) Create a geolocation information
static ChatRoomMessage createChatRoomTextMessage(String roomId, String text) Create ordinary text message
static ChatRoomMessage createChatRoomVideoMessage(String roomId, File file, long duration, int width, int height, String displayName) Create a video message
static ChatRoomMessage createChatRoomVideoMessage(String roomId, File file, long duration, int width, int height, String displayName, String nosTokenSceneKey) Create a video message and specify scenario of file resource
static ChatRoomMessage createEmptyChatRoomMessage(String roomId, long time) Create an empty message and set room ID and time point only for recording query
static ChatRoomMessage createTipMessage(String roomId) Create a tip message

See scenario of file resource for nosTokenSceneKey.

The following is an example of sending text messages. Other types of message sending modes are similar to IM one-to-one chat and team chat.

  • API prototype
java/**
 * Create an ordinary text message
 *
 * @param roomId - Chat room ID
 * @param text - Content of text message
 * @return ChatRoomMessage - Generated chat room message object
 */
public static ChatRoomMessage createChatRoomTextMessage(String roomId, String text);

/**
 * Send a message
 *
 * @param msg - Message body to be sent, constituted by {@link ChatRoomMessageBuilder}.
 * @param resend - If a message is sent unsuccessfully and then re-sent, it is marked as "true". Otherwise, as "false".
 * @return InvocationFuture - Configurable callback feature. It can be invoked only when the message is sent. If an error occurs, a detailed error code will be returned.
 */
InvocationFuture<Void> sendMessage(ChatRoomMessage msg, boolean resend);
  • Example
java// roomId used for example
String roomId = "50";
// Content of text message
String text = "This is text message of chat room";
// Create chat room text message
ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(roomId, text);
// Send text message
NIMClient.getService(ChatRoomService.class).sendMessage(message, false)
       .setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
	            // Successful
            }

            @Override
            public void onFailed(int code) {
                // Failed
            }

            @Override
            public void onException(Throwable exception) {
               // Error
            }
        });
  • Special error code
Error code Description
13004 DisableSendMsg (mute)
13006 Chat room is mute and only the administrator can send the message.

Configuration options of sending messages

When sending a chat room message, the user can set the configuration option CustomChatRoomMessageConfig for setting to store on cloud history.

CustomChatRoomMessageConfig attribute Description
skipHistory Will the message be saved to a server?
If it is true, the results pulled down using ChatRoomService#pullMessageHistory will not include the message.
It is "false" by default.
  • Example
java// roomId used for example
String roomId = "50";
// Content of text message
String text = "This is text message of chat room";
// Create chat room text message
ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(roomId, text);
// Configure not to store message history
CustomChatRoomMessageConfig config = new CustomChatRoomMessageConfig();
config.skipHistory = true;
message.setChatRoomConfig(config);
// Send Chat room message
NIMClient.getService(ChatRoomService.class).sendMessage(message, false);

Receiving messages

By adding a message observer, the user can receive a message when the message is sent.

  • API prototype
java/**
 * Register or cancel the observer for receiving messages.
 *
 * @param observer - Observer. The parameter is the set of received messages.
 * @param register true indicates registered, and true indicates unregistered
 */
public void observeReceiveMessage(Observer<List<ChatRoomMessage>> observer, boolean register);
  • Example
javaObserver<List<ChatRoomMessage>> incomingChatRoomMsg = new Observer<List<ChatRoomMessage>>() {
        @Override
        public void onEvent(List<ChatRoomMessage> messages) {
            // Handle received new message
        }
    };
NIMClient.getService(ChatRoomServiceObserver.class).observeReceiveMessage(incomingChatRoomMsg, register);
  • Please download attachment by downloadAttachment method of ChatRoomService.
  • Please use observeMsgStatus(Observer<ChatRoomMessage> observer, boolean register) of ChatRoomServiceObserver to register/log out message state observer.
  • Please use observeAttachmentProgress(Observer<AttachmentProgress> observer, boolean register) of ChatRoomServiceObserver to register/log out the attachment uploading/downloading progress observer.

Notifications

Some operations in a chat room will generate chat room notifications. The notification will be generated if:

Type Description
ChatRoomClose Chat room is closed.
ChatRoomCommonAdd Chat room member is set as a fixed member.
ChatRoomCommonRemove Fixed member in a chat room is canceled.
ChatRoomInfoUpdated Chat room information is updated.
ChatRoomadministratorAdd A member is set as an administrator
ChatRoomadministratorRemove Chat room administrator is removed.
ChatRoomMemberBlackAdd Chat room member is added to the Blocklist.
ChatRoomMemberBlackRemove Chat room member is removed from the Blocklist.
ChatRoomMemberExit Member leaves the chat room
ChatRoomMemberIn Member joins the chat room
ChatRoomMemberKicked Member is kicked out.
ChatRoomMemberMuteAdd Member is added to mute
ChatRoomMemberTempMuteAdd Chat room member is added to temporary mute.
ChatRoomMemberTempMuteRemove Chat room member is removed from temporary mute actively.
ChatRoomMyRoomRoleUpdated Chat room member actively updates role information in a chat room (only nick/avator/ext).
ChatRoomQueueBatchChange Queue is changed in batch.
ChatRoomQueueChange Quene has change.
ChatRoomRoomDeMuted : Chat room members are unmuted.
ChatRoomRoomMuted : The chat room is muted, only the administrator can send a message, and others are muted.

In particular, the issuance of notifications of members joining and leaving the chat room can be set:

  • Application level: CommsEase console > Select app > Issue message system of notifications users joining and leaving from chat room > Enable/disable.
  • A one-to-one chat room: Call server API "notification of disabling entry and leave from specified chat room".
  • If you want to exclude the chat room user entry and leave messages when querying the message history of a chat room, please contact a business consultant to apply for disabling the "storage of chat room user entry and leave message history".

All chat room messages are packaged in the form of ChatRoomMessage. Analysis for chat room notification:

Analysis steps for chat room notification:

  • Get message type using ChatRoomMessage.getMsgType(). If the type is MsgTypeEnum.notification, then it is chat room notification message.
  • Transform strong type of attachment object acquired using ChatRoomMessage.getAttachment() into NotificationAttachment.
  • Get detailed NotificationType using NotificationAttachment.getType().
  • Transform strong type of attachment acquired using ChatRoomMessage.getAttachment() into corresponding attachment type (ChatRoomNotificationAttachment or sub-type).

ChatRoomNotificationAttachment parameter:

Method Description
getExtension() Get the extension field of chat room notification
getOperator() Get account of the operator
getOperatorNick() Get display name of the operator
getTargets() Get account list of the targets
getTargetNicks() Get display name list of the targets

Example:

javapublic static String getNotificationText(ChatRoomNotificationAttachment attachment) {
        if (attachment == null) {
            return "";
        }
        String targets = getTargetNicks(attachment);
        String text;
        switch (attachment.getType()) {
            case ChatRoomMemberIn:
                text = buildText("Welcome", targets, "Enter a chat room");
                break;
            case ChatRoomMemberExit:
                text = buildText(targets, "Left a chat room");
                break;
            case ChatRoomMemberBlackAdd:
                text = buildText(targets, "Be added to a Blocklist by administrator");
                break;
            case ChatRoomMemberBlackRemove:
                text = buildText(targets, "Be removed from Blocklist by administrator");
                break;
            case ChatRoomMemberMuteAdd:
                text = buildText(targets, "Be muted by administrator");
                break;
            case ChatRoomMemberMuteRemove:
                text = buildText(targets, "Be unmuted by administrator");
                break;
            case ChatRoomadministratorAdd:
                text = buildText(targets, "Appointed as administrator");
                break;
            case ChatRoomadministratorRemove:
                text = buildText(targets, "De-appointed as administrator");
                break;
            case ChatRoomCommonAdd:
                text = buildText(targets, "Be set as an ordinary member");
                break;
            case ChatRoomCommonRemove:
                text = buildText(targets, "Be canceled as an ordinary member ");
                break;
            case ChatRoomClose:
                text = buildText("The chat room is closed");
                break;
            case ChatRoomInfoUpdated:
                text = buildText("The chat room information is updated");
                break;
            case ChatRoomMemberKicked:
                text = buildText(targets, "Be kicked out of a chat room");
                break;
            case ChatRoomMemberTempMuteAdd:
                text = buildText(targets, "Be muted temporarily");
                break;
            case ChatRoomMemberTempMuteRemove:
                text = buildText(targets, "Temporary mute is canceled");
                break;
            case ChatRoomMyRoomRoleUpdated:
                text = buildText(targets, "Updated your role information");
                break;
            case ChatRoomQueueChange:
                text = buildText(targets, "Change in queue");
                break;
            case ChatRoomRoomMuted:
                text = buildText("All members are muted, but the administrator can send messages");
                break;
            case ChatRoomRoomDeMuted:
                text = buildText("All members are unmuted");
                break;
            case ChatRoomQueueBatchChange:
                text = buildText("Change at a time");
                break;
            default:
                text = attachment.toString();
                break;
        }
        return text;
    }

Querying message history on cloud

There are no offline messages and roaming messages in the chat room. The chat room message history can be queried through the following interface. The server only keeps the chat room message history records of the last 10 days. But URL addresses of files (for example, image, audio, video) sent 10 days before are still valid (But developers must save these addresses, because they cannot be queried through expired message.) For extending "duration of chat room message history", please contact the commercial consultant.

Querying message history on cloud

Starting from startTime (unit: ms), you can select query direction (forward or backward) to pull down a limited number of messages. The pull-down messages also include chat room notifications.

The ranking of query results is related to query direction. If the direction is forward, then results are ranked by time in reversed order. Otherwise, by time in order.

java/**
 * Get message history. The given time can be selected to query forward or backward. If the direction is forward, then results are ranked by time in reversed order. Otherwise, by time in order.
 *
 * @return InvocationFuture - Configurable callback feature. The list of message history will be returned in the callback.
 */
InvocationFuture<List<ChatRoomMessage>> pullMessageHistoryEx(String roomId, long startTime, int limit, QueryDirectionEnum direction);
  • Parameters
Parameter Description
roomId Chat room ID
startTime Timestamp, unit: ms
limit Number of pull-down messages, max. 100
direction Query direction

QueryDirectionEnum attribute

QueryDirectionEnum attribute Description
QUERY_OLD Query message earlier than anchor time
QUERY_NEW Query message later than anchor time
  • Example
javalong startTime = System.currentTimeMillis();
// From on, 100 messages are queried toward QueryDirectionEnum.QUERY_OLD.
NIMClient.getService(ChatRoomService.class).pullMessageHistoryEx(roomId, startTime, 100, QueryDirectionEnum.QUERY_OLD);

Querying messages by type

With startTime (unit: ms) as timestamp, you can select query direction (forward or backward) and specify one or more types of message to pull down a limited number of messages.

  • API prototype
java/**
 * Get message history. The given time can be selected to query forward or backward, and one or multiple specified messages can be queried.
 *
 * If the direction is forward, then results are ranked by time in reversed order. Otherwise, by time in order.
 *
 * Available message types: 0: Text; 1: Image; 2. Audio file; 3. Video; 4. Geographical location; 5. Notification; 6. File; 10: Prompt; 11: Robot; 100: Custom. Others are Invalid parameters.
 *
 * @param roomId - Chat room ID
 * @param startTime - Timestamp, unit: ms
 * @param limit - Number of available messages
 * @param direction query direction
 * @param typeEnums - Message type, array
 * @return InvocationFuture - Configurable callback feature. The list of message history will be returned in callback.
 */
InvocationFuture<List<ChatRoomMessage>> pullMessageHistoryExType(String roomId, long startTime, int limit, QueryDirectionEnum direction, MsgTypeEnum[] typeEnums);
  • Parameters
Parameter Description
roomId Chat room ID
startTime timestamp, unit: ms
limit Number of pull-down messages
direction Query direction
typeEnums Query message type, array
  • Example
javaMsgTypeEnum[] typeEnums = new MsgTypeEnum[]{MsgTypeEnum.text, MsgTypeEnum.image};
int[] types = new int[]{MsgTypeEnum.text.getValue(), MsgTypeEnum.image.getValue()};
long anchorTime = System.currentTimeMillis();

checkResponse(NIMClient.getService(ChatRoomService.class).pullMessageHistoryExType(Constants.CHATROOM_ID, anchorTime, 50, QueryDirectionEnum.QUERY_OLD, typeEnums), new TestRequestResult.Callback<List<ChatRoomMessage>>() {
    @Override
    public boolean onResponseData(int code, List<ChatRoomMessage> data) {
       ...
    }
});

Chat room information management

Get the profile of a chat room

You can get chat room information from the server using this interface. SDK does not provide cache of chat room information, so that developers must make caches as required. The extension field of basic chat room information must be set at the server and client SDK only provides query service.

  • API prototype
java/**
 * Get information about current chat room
 *
 * @param roomId - Chat room ID
 * @return InvocationFuture - Configurable callback feature. The information about the chat room is returned in the callback.
 */
InvocationFuture<ChatRoomInfo> fetchRoomInfo(String roomId);
  • Example
java// roomId - Chat room ID
NIMClient.getService(ChatRoomService.class).fetchRoomInfo(roomId).setCallback(new RequestCallback<ChatRoomInfo>() {
    @Override
    public void onSuccess(ChatRoomInfo param) {
        // Successful
    }

    @Override
    public void onFailed(int code) {
        // Failed
    }

    @Override
    public void onException(Throwable exception) {
        // Error
    }
});

Editing the chat room profile

It supports updating chat room information. Only the owner and administrator can change chat room information. You can set that update is notified. If it is set to send a notification, you can receive NotificationType#ChatRoomInfoUpdated type message in a chat room.

  • API prototype
java/**
 * Update chat room information
 *
 * @param roomId - Chat room ID
 * @param chatRoomUpdateInfo - Updatable chat room information
 * @param needNotify - It determines to send notification.
 * @param notifyExtension - Update extension field of chat room information related operation. This field will be covered in the extension field for updating chat room information.
 * @return InvocationFuture - Configurable callback feature. It can be invoked only after only when chat room information is updated. If an error occurs, a detailed error code will be returned.
 */
InvocationFuture<Void> updateRoomInfo(String roomId, ChatRoomUpdateInfo chatRoomUpdateInfo, boolean needNotify, Map<String, Object> notifyExtension);
  • Parameters
Parameter Description
roomId Chat room ID
chatRoomUpdateInfo Updatable chat room information
needNotify Is it need to notify?
notifyExtension Update extension field of chat room information. This field will be covered in the extension field of notification for updating chat room information.
queueLevel Queue level: 0 indicates permission of all members; 1 indicates permission of only streamer/administrator.
  • Example
java// Take "Update chat room information" for an example
ChatRoomUpdateInfo updateInfo = new ChatRoomUpdateInfo();
updateInfo.setName("New chat room name");

NIMClient.getService(ChatRoomService.class).updateRoomInfo(roomId, updateInfo, false, "")
        .setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                // Successful
            }

            @Override
            public void onFailed(int i) {
                // Failed
            }

            @Override
            public void onException(Throwable throwable) {
				// Error
            }
        });

Chat room member management

Chat room members

About chat room members:

  • Chat room members include fixed members and non-fixed members (temporary member/visitor). The limit of fixed members is 1000.
  • The fixed members include creator, the administrator, ordinary member, and limited user. Except for the creator, other members are considered as visitors by default when adding the team.
  • Except for the creator, other members are considered as visitors by default when adding the team.
  • The visitor who was set as an administrator will become a normal user (not a visitor) after his administration privileges are removed.
  • An administrator will become a normal user after his/her administration permissions are removed. The administrator cannot be set as an ordinary member.
  • Only the owner can perform operations on an administrator, and an administrator cannot perform operations on the owner and other administrators.
  • A normal user will become a visitor after his/her identity is removed.
  • A visitor will become a permanent member after he/she is Blocklisted (at the same time, the visitor will be disconnected from the server and cannot join the chat room unless he/she is removed from the Blocklist). The user will become a visitor after being removed from the Blocklist.
  • The user will become a fixed member after being muted permanently. The user will become a visitor after disabling the permanent mute. The expiry of temporary mute will not be influenced after disabling permanent mute.
  • The setting and relieving of temporary muting will not change the identity of a member. If temporary mute is set repeatedly, the final expiry will cover the previous setting (without accumulation).
  • The visitor is an non-fixed member in the chat room only when being online. The visitor will not be any member of the chat room if he joins and then leaves the chat room (without any relation with the chat room).

Chat room member prototype:

Return ChatRoomMember interface Description
String getAccount() Get member account
String getAvatar() Get profile picture It is possible to getAvatar from NimUserInfo, which can be submitted by the user in a chat room.
long getEnterTime() Get the time of joining chat room The field is void for offline members.
Map getExtension() Get the extension field The length limit is 4k, which can be submitted by users in a chat room.
int getMemberLevel() Get member level ≥0 indicates user-defined level by developers and user.
MemberType getMemberType() Get member type Member type: Mainly including tourist and non-tourist.
String getNick() Get display name It is possible to get display name from NimUserInfo, which can be submitted by the user in a chat room.
String getRoomId() Get chat room ID
long getTempMuteDuration() Get duration of disabling temporary mute, unit: second
long getUpdateTime() Get records updating time of fixed member for ranking and querying the list of fixed members
boolean isInBlocklist() Determine that the user is in Blocklist
boolean isMuted() Determine that the user is muted
boolean isOnline() Determine that the user is online. Only special members may be offline and the state of visitor or anonymous user is online definitely.
boolean isTempMuted() Determine that the user is muted temporarily
boolean isValid() Determine that it is valid
void setAccount(String account) Set user account
void setprofile picture(String profile picture) Set member profile picture
void setEnterTime(long joinTime) Set the time of joining chat Room
void setExtension(Map extension) Set extension field
void setInBlocklist(boolean inBlocklist) Set that the user is in Blocklist
void setMemberLevel(int memberLevel) Set member level
void setMemberType(MemberType type) Set member type
void setMuted(boolean muted) Set mute
void setNick(String nick) Set member profile name
void setOnline(boolean online) Set online state
void setRoomId(String roomId) Set Chat room ID
void setTempMuted(boolean tempMuted) Set temporary mute
void setTempMuteDuration(long tempMuteDuration) Set duration of temporary mute
void setUpdateTime(long updateTime) Set update time of fixed member
void setValid(boolean valid) Set that it is valid

MemberQueryType schema:

Parameter Description
GUEST Non-fixed member
(also temporary member. They can be found in the list only when being online. The number is unlimited.)
NORMAL Fixed member
(including creator, the administrator, ordinary member, limited user (mute + Blocklist)
They can be found in the list even though they are not online. The number is limited.)
ONLINE_NORMAL Only online fixed member
GUEST_DESC Non-fixed member (also temporary member. They can be found in the list only when being online. The number is unlimited.)
They are ranked by the time of joining chat room in inverted order. The later the time is, the more forward the ranking will be.
GUEST_ASC Non-fixed member (also temporary member. They can be found in the list when being online. The number is unlimited.)
They are ranked by the time of joining chat room in order. The earlier the time is, the more forward the ranking will be.
UNKNOWN Unknown

Getting chat room members

Getting chat room members by page

The list of chat room members can be acquired using this interface, SDK will not cache the list of chat room members, and developers need to make cache based on services independently.

  • API prototype
java/**
 * Get information about chat room members
 *
 * @param roomId - Chat room ID
 * @param memberQueryType - Member query type
 * @param time - updateTime for the list of permanent members
 * joinTime for the list of guests
 * If the value is 0, the query starts with the latest server time, i.e. the first page, unit: ms.
 * @param limit - Member limit
 * @return InvocationFuture - Configurable callback feature. The list of member profile will be returned in a callback.
 */
InvocationFuture<List<ChatRoomMember>> fetchRoomMembers(String roomId, MemberQueryType memberQueryType, long time, int limit);
  • Parameters
Parameter Description
roomId Chat room ID
memberQueryType Member query type See MemberQueryType
time The list of fixed members is used with updateTime and the list of visitors is used with joinTime. 0 is filled in
to start query with current server time, i.e. the first page, unit: ms.
limit Member limit
  • Example
java// Take a guest for an example, start from the latest time to query 10 pieces
NIMClient.getService(ChatRoomService.class).fetchRoomMembers(roomId, MemberQueryType.GUEST, 0, 10).setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {
    @Override
    public void onResult(int code, List<ChatRoomMember> result, Throwable exception) {
      ...
    }
});

Getting the specified chat room members

java/**
 * Get information about chat room members by user ID
 *
 * @param roomId - Chat room ID
 * @param accounts - List of member accounts
 * @return InvocationFuture - Configurable callback feature. The list of member profile will be returned in a callback.
 */
InvocationFuture<List<ChatRoomMember>> fetchRoomMembersByIds(String roomId, List<String> accounts)
  • Example
javaList<String> accounts = new ArrayList<>();
accounts.add(account);

NIMClient.getService(ChatRoomService.class).fetchRoomMembersByIds(roomId, accounts)
	    .setCallback(new RequestCallbackWrapper<List<ChatRoomMember>>() {... });

Get the list of chatbots

The robot list cannot be synchronized due to non-existence of IM connection under independent mode of chat room, so that this interface must be called to pull down the robot list. We recommend to call this interface after joining the chat room and take frequency-control measures to prevent high frequency of the interface when the user switches chat room frequently.

  • API prototype
java/**
 * Get all current chatbots in independent chat room scene
 *
 * @param roomId - Current chat room ID
 * @return InvocationFuture - Configurable callback feature. The detailed error codes for successful or failed operations will be returned in callback.
 */
InvocationFuture<List<NimRobotInfo>> pullAllRobots(String roomId);
  • Example
java
/**
 * Get the shortest interval 5min for robot information
 */
private static final long MIN_PULL_ROBOT_INTERNAL = 5 * 60 * 1000;

private long lastTime = 0L;

/**
 * It can be invoked when you join a chat room under independent mode.
 *
 * The shortest time interval MIN_PULL_ROBOT_INTERNAL
 * @param roomId
 */
public void pullRobotListIndependent(String roomId) {
    if (System.currentTimeMillis() - lastTime < MIN_PULL_ROBOT_INTERNAL) {
        return;
    }

    NIMClient.getService(ChatRoomService.class).pullAllRobots(roomId).setCallback(new RequestCallbackWrapper<List<NimRobotInfo>>() {
        @Override
        public void onResult(int code, List<NimRobotInfo> result, Throwable exception) {
            if (code == 200 && result != null) {
                lastTime = System.currentTimeMillis();
                // Update cache
            }
        }
    });
}

Editing the user profile

You can update member profile in a chat room. Only profile name, profile picture, and extension field can be updated now. You can set that update is notified. If it is set to send a notification, you can receive NotificationType#ChatRoomMyRoomRoleUpdated type message in a chat room.

java/**
 * Update my information in a chat room
 *
 * @param roomId - Chat room ID
 * @param chatRoomMemberUpdate - My updatable role information
 * @param needNotify - It determines to send notification.
 * @param notifyExtension - Update extension field of operation. This field will be covered in the extension field of notification for updating chat room information.
 * @return InvocationFuture - Configurable callback feature. It can be invoked only after only when information is updated. If an error occurs, detailed error code will be returned.
 */
InvocationFuture<Void> updateMyRoomRole(String roomId, ChatRoomMemberUpdate chatRoomMemberUpdate, boolean needNotify, Map<String, Object> notifyExtension);
  • Parameters
Parameter Description
roomId Chat room ID
chatRoomMemberUpdate Updatable role information about member
needNotify Is it need to notify?
notifyExtension Update extension field of operation. This field will be covered in the extension field of notification for updating chat room information.

ChatRoomMemberUpdate interface

Return ChatRoomMemberUpdate interface Description
String getAvatar() Get profile picture shown in a chat room
Map getExtension() Get the extension field
String getNick() Get display name shown in a chat room
boolean isNeedSave() Determine that updated information is persisted. It is valid only for fixed members. It is "false" by default. V3.8.0 adds this feature.
void setprofile picture(String profile picture) Set profile picture shown in a chat room
void setExtension(Map extension) Set extension field, length limit 2048
void setNeedSave(boolean needSave) Determine that it is persisted. It is valid only for fixed members. V3.8.0 adds this feature.
void setNick(String nick) Set display name shown in a chat room
  • Example
java// Take "Update my profile name" for an example
ChatRoomMemberUpdate update = new ChatRoomMemberUpdate();
update.setNick("My new profile name");

NIMClient.getService(ChatRoomService.class).updateMyRoomRole(roomId, update, false, "").setCallback(new RequestCallback<Void>() {
    @Override
    public void onSuccess(Void param) {
        // Successful
    }

    @Override
    public void onFailed(int code) {
        // Failed
    }

    @Override
    public void onException(Throwable exception) {
		// Error
    }
});

Adding or removing an administrator

java/**
 * Set or cancel chat room administrator
 *
 * @param isAdd - "true" indicates to set chat room administrator, and "false" indicates to cancel chat room administrator.
 * @param memberOption - Request parameter, including chat room ID, account ID, and optional extension field.
 * @return InvocationFuture - Configurable callback feature. The member profile will be returned in a callback.
 */
InvocationFuture<ChatRoomMember> markChatRoomadministrator(boolean isAdd, MemberOption memberOption);
  • Parameters
Return MemberOption interface Description
String getAccount() Get member account
Map getNotifyExtension() Get the extension field defined by developersin notification event
String getRoomId() Get chat room ID
void setAccount(String account) Set member account
void setNotifyExtension(Map notifyExtension) Set extension field in notification event
void setRoomId(String roomId) Set chat room ID
  • Example
java// Take "Set as administrator" for an example
NIMClient.getService(ChatRoomService.class)
       .markChatRoomadministrator(true, new MemberOption(roomId, account))
       .setCallback(new RequestCallback<ChatRoomMember>() {
            @Override
            public void onSuccess(ChatRoomMember param) {
                // Successful
            }

            @Override
            public void onFailed(int code) {
                // Failed

            @Override
            public void onException(Throwable exception) {
				// Error
            }
        });

Adding or removing ordinary members

java/**
 * Set or cancel normal chat room members.
 *
 * @param isAdd - "true" indicates to set chat room administrator, and "false" indicates to cancel chat room administrator.
 * @param memberOption - Request parameter, including chat room ID, account ID, and optional extension field.
 * @return InvocationFuture - Configurable callback feature. The member profile will be returned in a callback.
 */
InvocationFuture<ChatRoomMember> markNormalMember(boolean isAdd, MemberOption memberOption);
  • Example
java// Take "Set ordinary members" for an example
NIMClient.getService(ChatRoomService.class).markNormalMember(true, new MemberOption(roomId, account)))
       .setCallback(new RequestCallback<ChatRoomMember>() {
            @Override
            public void onSuccess(ChatRoomMember param) {
               // Successful
            }

            @Override
            public void onFailed(int code) {
				// Failed
            }

            @Override
            public void onException(Throwable exception) {
				// Error
            }
        });

Adding or removing a member in a blocklist

java/**
 * Add a member to a blocklist.
 *
 * @param isAdd - "true" is to add, and "false" is to remove.
 * @param memberOption - Request parameter, including chat room ID, account ID, and optional extension field.
 * @return InvocationFuture - Configurable callback feature. The member profile will be returned in a callback.
 */
InvocationFuture<ChatRoomMember> markChatRoomBlocklist(boolean isAdd, MemberOption memberOption);
  • Example
java// Take "Add to the blocklist" for an example
MemberOption option = new MemberOption(roomId, account);
NIMClient.getService(ChatRoomService.class).markChatRoomBlocklist(true, option).setCallback(new RequestCallback<ChatRoomMember>() {
        @Override
        public void onSuccess(ChatRoomMember param) {
        // Successful
        }

        @Override
        public void onFailed(int code) {
        // Failed
        }

        @Override
        public void onException(Throwable exception) {
		// Error
        }
});

Muting or unmuting members

When being added to the mute list, the user will receive ChatRoomMemberMuteAdd type chat room notification.

When being removed from the mute list, the user will receive ChatRoomMemberMuteRemove type chat room notification.

java/**
 * Add to mute list or cancel mute.
 *
 * @param isAdd - "true" is to add, and "false" is to cancel.
 * @param memberOption - Request parameter, including chat room ID, account ID, and optional extension field.
 * @return InvocationFuture - Configurable callback feature. The member profile will be returned in a callback.
 */
InvocationFuture<ChatRoomMember> markChatRoomMutedList(boolean isAdd, MemberOption memberOption);
  • Example
java// Take "Add to mute list" as an example.
MemberOption option = new MemberOption(roomId, account);
NIMClient.getService(ChatRoomService.class).markChatRoomMutedList(true, option)
        .setCallback(new RequestCallback<ChatRoomMember>() {
            @Override
            public void onSuccess(ChatRoomMember param) {
                // Successful
            }

            @Override
            public void onFailed(int code) {
                // Failed
            }

            @Override
            public void onException(Throwable exception) {
				// Error
            }
        });

Kicking members

Only administrators can kick out team members. Only the team owner can kick out an administrator.

If a member is kicked out of the chat room, the member will receive a notification of ChatRoomMemberKicked type.

The extension field of kickout notification can be added. This field will be covered in the extension field of kickout notification. The max. length of extension field of notification is 1K. "Map<String,Object>" must be specified for extension field, and SDK will transform it into Json String.

java/**
 * Kick out special members.
 *
 * @return InvocationFuture - Configurable callback feature. It can be invoked only when members are kicked out. If an error occurs, detailed error code will be returned.
 */
InvocationFuture<Void> kickMember(String roomId, String account, Map<String, Object> notifyExtension);
  • Parameters
Parameter Description
roomId Chat room ID
account Kick out member account Only administrator can kick out team members. If the target is administrator, only the owner can kick him out.
notifyExtension Extension field of kickout notification. This field will be covered in the extension field of kickout notification.
  • Example
javaMap<String, Object> reason = new HashMap<>();
reason.put("reason", "kick");
NIMClient.getService(ChatRoomService.class).kickMember(roomId, account, reason).setCallback(new RequestCallback<Void>() {... });

Temporarily muting members

When being added to the temporary mute list, the user will receive ChatRoomMemberTempMuteAdd type chat room notification.

When being removed from the temporary mute list, the user will receive ChatRoomMemberTempMuteRemove type chat room notification.

Chat room supports to set temporary mute. The mute state will be canceled when it is expired. The duration in notification message after successfully setting temporary mute is remaining time of mute. If the mute duration is set to 0, it indicates to cancel temporary mute. If the first mute duration has not ended and the second temporary mute is set, then the time is counted by the second settings.

java/**
 * Set temporary mute for chat room members
 *
 * @return InvocationFuture - Configurable callback feature. If an error occurs, detailed error code will be returned.
 */
InvocationFuture<Void> markChatRoomTempMute(boolean needNotify, long duration, MemberOption memberOption);
  • Parameters
Parameter Description
needNotify Is it need to send broadcasting notification. True: Yes; false: No.
duration Mute duration, unit: second
memberOption Request parameters, including chat room ID, account ID, and optional extension field.
  • Example
java// Take "Send broadcast notification and set temporary mute for 10s" for an example
MemberOption option = new MemberOption(roomId, account);
NIMClient.getService(ChatRoomService.class).markChatRoomTempMute(true, 10, option)
       .setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                // Successful
            }

            @Override
            public void onFailed(int code) {
                // Failed
            }

            @Override
            public void onException(Throwable exception) {
				// Error
            }
        });

Chat room queue

The chat room provides the queue service, which can be used in conjunction with the speaking queue management in the interactive live streaming scenario. The level is determined by ChatRoomInfo.getQueueLevel() and can be updated using updateChat roomInfo interface. By default, all users can call the interface to update the queue content.

Getting the chat room queue

java/**
 * Chat room queue service: Sort and list all queue elements.
 *
 * @param roomId - Chat room ID.
 * @return InvocationFuture - Configurable callback feature. All sorted key-value pairs of queue elements will be returned in a callback.
 */
InvocationFuture<List<Entry<String, String>>> fetchQueue(String roomId);
  • Example
javaNIMClient.getService(ChatRoomService.class).fetchQueue(roomId).setCallback(new RequestCallback<List<Entry<String, String>>>() {
    @Override
    public void onSuccess(List<Entry<String, String>> param) {
        // Successful
    }

    @Override
    public void onFailed(int code) {
        // Failure
    }

    @Override
    public void onException(Throwable exception) {
		// Error
    }
});

Adding or updating queue elements

For the element added or updated using the interface by the user, if "isTransient" parameter is "true", it indicates the server will automatically delete the element added or updated by the user when the user is offline or leaves the chat room.

Besides, the server will send chat room notifications. The notification message type is NotificationType#ChatRoomQueueBatchChange and its attachment type is ChatRoomPartClearAttachment. It is a queue change notification, so that attachment type includes queue change type ChatRoomQueueChangeType#PARTCLEAR.

java/**
 * Chat room queue service: Add or update queue elements. It determines to delete the element when a user is offline or leaves a chat room.
 * @param roomId - Chat room ID.
 * @param key - Unique key of a new element (or element to be updated).
 * @param value - Content of a new element (element to be updated).
 * @param isTransient - (Optional parameter. If the value is null, it will be false by default). "true" indicates that this element must be deleted when the user who submits this new element is offline or leaves chat room. Default "false" value indicates not to delete.
 * @return InvocationFuture - Configurable callback feature. The detailed error codes for successful or failed operations will be returned in callback.
 */
InvocationFuture<Void> updateQueueEx(String roomId, String key, String value, boolean isTransient);
  • Parameters
Parameter Description
roomId Chat room ID.
key Unique key of a new element (or element to be updated).
value Content of a new element (element to be updated).
isTransient (Optional parameter)
"true" indicates that this element must be deleted when the user who submits this new element is offline or leaves chat room. Default "false" value indicates not to delete.

ChatRoomPartClearAttachment

Return ChatRoomPartClearAttachment interface Description
ChatRoomQueueChangeType getChatRoomQueueChangeType() Returned queue change type, with value ChatRoomQueueChangeType.PARTCLEAR
Map getContentMap() Added or updated element when the user is offline or leaves chat room, and the returned user uses "updateQueueEx" interface and sets "isTransient" parameter is "true".
  • Example
javaNIMClient.getService(ChatRoomService.class)
        .updateQueueEx(roomId, "this is key", "this is value", true)
        .setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                // Successful
            }

            @Override
            public void onFailed(int code) {
                // Failed
            }

            @Override
            public void onException(Throwable exception) {
				// Error
            }
        });

Updating multiple queue elements at a time

Only the existing key is updated and new element will not be added.

java/**
 * Update multiple queue elements at a time
 *
 * @param roomId - Chat room ID.
 * @param queues - Queue elements to be updated.
 * @param needNotify - It determines that broadcast notification must be sent.
 * @param notifyExt - Custom field in notification, with max. length 2k.
 * @return - Unavailable elementKey list.
 */
InvocationFuture<List<String>> batchUpdateQueue(String roomId, List<Entry<String, String>> queues, boolean needNotify, Map<String, Object> notifyExt);
  • Example
javaList<Entry<String, String>> queues = new ArrayList<>();
        queues.add(new Entry<String, String>("key", "value1"));
        queues.add(new Entry<String, String>("key1", "value2"));
        queues.add(new Entry<String, String>("key2", "value3" ));

        Map<String, Object> notifyExt = new HashMap<>();
        notifyExt.put("notes", "notes_vaules");
        NIMClient.getService(ChatRoomService.class).batchUpdateQueue(roomId, queues, true, notifyExt).setCallback(new RequestCallback<List<String>>() {
            @Override
            public void onSuccess(List<String> result) {
               // Successful
               //result : Unavailable key list.
            }

            @Override
            public void onFailed(int code) {
               //Failure
            }

            @Override
            public vo
Was this page helpful?
Yes
No
  • Overview
  • Joining a chat room
  • Non-independent mode
  • Independent mode
  • Multi-device login to the same chat room
  • Listening for connection changes of a chat room
  • Listening for kickout events
  • Leaving a chat room
  • Leave a chat room of a specific type
  • Messaging in a chat room
  • Sending messages
  • Configuration options of sending messages
  • Receiving messages
  • Notifications
  • Querying message history on cloud
  • Querying message history on cloud
  • Querying messages by type
  • Chat room information management
  • Get the profile of a chat room
  • Editing the chat room profile
  • Chat room member management
  • Chat room members
  • Getting chat room members
  • Getting chat room members by page
  • Getting the specified chat room members
  • Get the list of chatbots
  • Editing the user profile
  • Adding or removing an administrator
  • Adding or removing ordinary members
  • Adding or removing a member in a blocklist
  • Muting or unmuting members
  • Kicking members
  • Temporarily muting members
  • Chat room queue
  • Getting the chat room queue
  • Adding or updating queue elements
  • Updating multiple queue elements at a time