Chat Room

Update time: 2022/09/02 09:54:46

Read the chat room FAQRead the Chat room FAQ before developing the chat room feature to get a general idea about the feature.

Features of Chat Room

Chat Room Features:

  • If a user enters a chat room, the new connection must be created. If the user leaves or is removed from the chat room, the connection will be disabled. If the user is disconnected from chat room, automatic re-connection will be executed. Developers need to track connection status of chat room to make the correct interface action.
  • The number of online members in a chat room is not limited.
  • A user is allowed to enter multiple chat rooms and create multiple connections.
  • Chat room does not support multi-terminal login, so currently logged in client will be kicked out if another client logs in.
  • After disconnecting from a chat room, the user will no longer receive messages related to the chat room from the server.
  • The chat room members include fixed members and guests.
  • At present, server control supports simultaneous entry to up to 10 chat rooms, so when logging into the 11th room, the client will be kicked out from one of the 10 previous rooms.

All events and callbacks for the chat room are not handled in the main thread. To handle UI elements, tasks will be thrown to the main thread.

Initialization and Clearup

To use chat room features, you must perform initialization by calling NIMChatRoom.ChatRoomApi.Init() ,and perform cleanup by calling NIMChatRoom.ChatRoomApi.Cleanup() before exiting the feature. The two operations must be used in pairs. Otherwise, exceptions may occur.Cleanup()` .

We recommend you make a global call of NIMChatRoom.ChatRoomApi.Init() once

Notification of Chat Room Event

Login, logout, message reception, and other operations in the chat room are all notified to the caller by monitoring global events. You must monitor all chat room event notifications before calling a login operation. It is recommended to register event monitoring upon completion of initialization.

To rejoin a chat room, you must wait until you have left the chat room.

Chat Room Login Event

After calling the chat room login interface, the developer is notified of the login progress and result through this event. The login process has 5 steps: local service initialization, server connection, server connection establishment, login authentication, login authenticated, and When login authentication is completed, you can get the information of the current chat room and your chat room member information.

NIMChatRoomLoginStepEnumeration description

Enumeration Value Description
kNIMChatRoomLoginStepInit 1 Local service initialization
kNIMChatRoomLoginStepServerConnecting 2 Server connecting
kNIMChatRoomLoginStepServerConnectOver 3 End of server connection, connection result is error_code
kNIMChatRoomLoginStepRoomAuthing 4 Chat room in authentication
kNIMChatRoomLoginStepRoomAuthOver 5 End of chat room authentication, the result of which is shown in error_code, if the error_code is not 408, the developer needs to request again the chat room login information
  • API prototype
public static event ChatRoomLoginDelegate LoginHandler;

  • Example
void OnLoginHandler(NIMChatRoomLoginStep loginStep, ResponseCode errorCode, ChatRoomInfo roomInfo, MemberInfo memberInfo)
{
     //roomInfo,memberInfo can be assigned null. You must check for null. Otherwise, NullReferenceException will be thrown and the callback thread error occurs.
    if (loginStep == NIMChatRoom.NIMChatRoomLoginStep.kNIMChatRoomLoginStepRoomAuthOver 
      && errorCode == NIM.ResponseCode.kNIMResSuccess)
    {
         //Successfully entered the chat room
    }
    if (errorCode != NIM.ResponseCode.kNIMResSuccess)
    {
        //Error occurs when entering the chat rooms
    }
}
//Monitor login event
NIM.NIMChatRoom.ChatRoomApi.LoginHandler += OnLoginHandler;

//Cancel monitoring
NIM.NIMChatRoom.ChatRoomApi.LoginHandler -= OnLoginHandler;

ExitChatRoom Event

Notification for leaving chat room. Other than being kicked out by other client, host and manager, notification for exiting a chat room will also appear when the chat room is closed or dismissed. After receiving the notification, the chat participant won't automatically reconnect with the chat room. Logging in again requires [getting the token](/en/docs/TM5MzM5Njk/jE1NDM1MTA# Get the token) again.

NIMChatRoomExitReasonEnumeration parameter description

Enumeration Value Description
kNIMChatRoomExitReasonExit 0 In case of active logout, you must send a re-login request before you login again
kNIMChatRoomExitReasonRoomInvalid 1 The chat room has been dismissed, you must send a re-login request before you login again
kNIMChatRoomExitReasonKickByManager 2 Kicked out by the manager, you must send a re-login request before you login again
kNIMChatRoomExitReasonKickByMultiSpot 3 Kick-out during multi-terminal login
kNIMChatRoomExitReasonIllegalState 4 Status exception of current link
kNIMChatRoomExitReasonBeBlacklisted 5 Blacklisted by the manager
  • API prototype
public static event ExitChatRoomDelegate ExitHandler;

  • Example
void OnExitHandler(long roomId, ResponseCode errorCode, NIMChatRoomExitReason reason)
{
    ...
}
//Monitor event
NIM.NIMChatRoom.ChatRoomApi.ExitHandler += OnExitHandler;

//Cancel monitoring
NIM.NIMChatRoom.ChatRoomApi.ExitHandler -= OnExitHandler;

Chat Room Connection Status Change Notification

Notify the developer of the connection status of the chat room when the room is disconnected due to network fluctuations. SDK monitors network status and automatically reconnects when possible.

NIMChatRoomLinkConditionEnumeration parameter description

Enumeration Value Description
kNIMChatRoomLinkConditionAlive 0 Normal connection
kNIMChatRoomLinkConditionDeadAndRetry 1 Connection failed, reconnecting
kNIMChatRoomLinkConditionDead 2 Developer needs to re-apply for chat room login information
  • API prototype
 public static event LinkStateChangedDelegate LinkStateChanged;

  • Example
void OnLinkStateChanged(long roomId, NIMChatRoomLinkCondition state)
{
    ...
}
//Monitor event
NIM.NIMChatRoom.ChatRoomApi.LinkStateChanged += OnLinkStateChanged;

//Cancel monitoring
NIM.NIMChatRoom.ChatRoomApi.LinkStateChanged -= OnLinkStateChanged;

Receive Message Event

Received a chat room message, the content of which isMessage. This notification event covers messages from multiple chat room,roomIdcan be used to distinguish between chat rooms. Local storage is not available for all chat room messages

NIMChatRoomMsgTypeEnumeration description

Enumeration Value Description
kNIMChatRoomMsgTypeText 0 Text message
kNIMChatRoomMsgTypeImage 1 Image message
kNIMChatRoomMsgTypeAudio 2 Audio message
kNIMChatRoomMsgTypeVideo 3 Video message
kNIMChatRoomMsgTypeLocation 4 Location message
kNIMChatRoomMsgTypeNotification 5 Activity room notification
kNIMChatRoomMsgTypeFile 6 File message
kNIMChatRoomMsgTypeTips 10 Reminder message
kNIMChatRoomMsgTypeRobot 11 Baud robot message
kNIMChatRoomMsgTypeCustom 100 Custom message
kNIMChatRoomMsgTypeUnknown 1000 Unknown type of message, it is the default value

MessageDescription of key parameters

Type Parameter Description
long RoomId ID of the chat room the message belongs to (filled out by server)
string SenderId Message sender
long TimeStamp Timestamp of message sending (in milliseconds) (filled out by server)
NIMChatRoomClientType SenderClientType Sender's client type, filled out by server, no operation required for sender
string SenderNickName Sender's nickname (filled out by server)
string SenderAvator Sender's avatar (filled out by server)
string SenderExtension Sender's identity extension field (filled out by server)
NIMChatRoomMsgType MessageType Message type, see NIMChatRoomMsgTypefor details
string MessageAttachment Message content, with a length limit of 2048, if it is agreed to be a JSON string, it must be an unformatted string that can be parsed as JSON. In addition to text messages, images, audios, videos, geographic locations, and custom messages also need to be JSON strings of the currently agreed format. This content is for transparent transmission and essentially the attachment content of theIMmessage. Refer to the corresponding message type in "sending message".
string ClientMsgId Client message id, filled out by sender
bool resend_flag Whether resending message is needed, true: needed, false: not needed, the default is false (not yet supported)
string Extension Third-party extension field, with a length limited to 4096, must be an unformatted string that can be parsed as JSON
bool AntiSpamEnabled Whether to enable YiDun anti-spam filtration. "True" is to enable, and "false" is not to enable. The value is "false" by default.
string AntiSpamContent (Optional) Developer-defined anti-spam field, with a length limit of 5000 characters
string LocalResourcePath The local absolute path of the media file (client side) (not yet supported)
string LocalResourceId ID of local media file (client side) (not yet supported)
  • API prototype
public static event ReceiveMessageDelegate ReceiveMessageHandler;

  • Example
void OnRecvMessage(long roomId, Message message)
{
    ...
}
//Monitor event
NIM.NIMChatRoom.ChatRoomApi.ReceiveMessageHandler += OnRecvMessage;

//Cancel monitoring
NIM.NIMChatRoom.ChatRoomApi.ReceiveMessageHandler -= OnRecvMessage;

Notification of Message Sending Result

This event informs the user whether the message is sent.

  • API prototype
public static event SendMessageDelegate SendMessageHandler;

  • Example
void OnSendMessageResult(long roomId, ResponseCode code, Message message)
{
    ...
}
//Monitor event
NIM.NIMChatRoom.ChatRoomApi.SendMessageHandler += OnSendMessageResult;

//Cancel monitoring
NIM.NIMChatRoom.ChatRoomApi.SendMessageHandler -= OnSendMessageResult;

Event of Receiving Chat Room Notification

All chat room notification messages are received through this event. Including members entering/leaving chat room, mute/unmute, add to/remove from blacklist, etc. SeeNotificationfor details.

NotificationParameter description

Type Parameter Description
NIMChatRoomNotificationId Type For Notification type, see NIMChatRoomNotificationId.
Notification.Data InnerData Notification content

NIMChatRoomNotificationIdEnumeration description

Enumeration value Description
kNIMChatRoomNotificationIdMemberIn Members enter a chat room
kNIMChatRoomNotificationIdMemberExit Members exit from a chat room
kNIMChatRoomNotificationIdAddBlack Blacklist members
kNIMChatRoomNotificationIdRemoveBlack Unblacklist a member.
kNIMChatRoomNotificationIdAddMute Mute a member
kNIMChatRoomNotificationIdRemoveMute Unmute a member
kNIMChatRoomNotificationIdAddManager Designate a manager
kNIMChatRoomNotificationIdRemoveManager Undo the designation of a manager.
kNIMChatRoomNotificationIdAddFixed Set as fixed chat room member
kNIMChatRoomNotificationIdRemoveFixed Undo the designation of fixed chat room members
kNIMChatRoomNotificationIdClosed Disable a chat room
kNIMChatRoomNotificationIdInfoUpdated Update the information of a chat room
kNIMChatRoomNotificationIdMemberKicked Kick a member out of a chat room
kNIMChatRoomNotificationIdMemberTempMute Temporary mute
kNIMChatRoomNotificationIdMemberTempUnMute Terminate temporary muting
kNIMChatRoomNotificationIdMyRoleUpdated Chat room members update personal information in the chat room. The information only includes nick, avator, and ext.
kNIMChatRoomNotificationIdRoomMuted When a chat room is muted, only the manager can send messages.
kNIMChatRoomNotificationIdRoomDeMuted Unmute all chat room members.

Let’s see description for the parameter ``Notification.Data`

Type Parameter Description
string Extension Extension field of event notification customed by developer-defined, must be an unformatted string that can be parsed as JSON
string OperatorId The account ID of the operator
string OperatorNick The nickname of the operator
string[] TargetAccountsNick The nickname list of target members
string[] TargetIdCollection The account ID list of operators
long MuteDuration When the notification is related to temporary mute, the value can be found. If mute is executed, it means mute duration (s); if mute is canceled, it means remaining mute duration (s).
int Muted If according to notification type, this value is available upon member entry, then it indicates whether the member is muted, 1: muted, 0: not muted (default)
int TempMuted If according to notification type, this value is available upon member speaking, then it indicates temporary mute status
long TempMutedDuration When the notification type is member access, it means temporary mute duration (s), and other notifications exclude the data.
  • API prototype
 public static event ReceiveNotificationDelegate ReceiveNotificationHandler;

  • Example
void OnReceiveNotificationHandler(long roomId, Notification notification)
{
    ...
}
//Monitor event
NIM.NIMChatRoom.ChatRoomApi.ReceiveNotificationHandler += OnReceiveNotificationHandler;

//Cancel monitoring
NIM.NIMChatRoom.ChatRoomApi.ReceiveNotificationHandler -= OnReceiveNotificationHandler;

Enter A Chat Room

Get Token

The chat room relies on IM. Before entering a chat room, you must get authorization information required for entering the room by calling the IM module interface, and this information is input into the chat room login when it is called by the developer. You can log in to multiple chat rooms at the same time, but each chat room requires different authorization information, depending on itsroomId.

Note: The interface called here belongs to IM SDK module.

  • API prototype
public static void RequestLoginInfo(long roomId, RequestChatRoomLoginInfoDelegate cb,string json_ext="");
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
cb Result notification callback
json_ext Extension information, reserved
  • API example
//Take test room 3001 as an example
long roomId = 3001;
string _token = "";
NIM.Plugin.ChatRoom.RequestLoginInfo(roomId, (response, authResult) =>
{
    if (response == NIM.ResponseCode.kNIMResSuccess)
    {
		_token = result; //This token is the required authorization information
        //If NIMChatRoom.ChatRoomApi.Login is invoked directly, an asynchronous task shall be thrown as much as possible to execute the operation as follows:
        Loom.QueueOnMainThread (() => {
        	LoginData loginData = new LoginData();
            loginData.Nick = "nickName";
            loginData.Icon = "https://xxxx.png";//Image url
            loginData.Extension = "{\"myExt\:\"111\"}";
            loginData.NotifyExtension = "{\"myNotifyExt\:\"2222\"}";
			NIMChatRoom.ChatRoomApi.Login(roomId,_token,loginData);
		});
    }
});

Log in to Chat Room

When entering the chat room, you can useLoginDatato set your nickname, avatar in the chat room, and deliver notification information and extension information, etc. The developer is informed of the login process through the log-in chat room event.

LoginDataParameter description

Type Parameter Description
string Nick Nickname displayed after entering the chat room, optionals
string Icon Avatar in the chat room, filled out with the url of the avatar, optional
string Extension Extension field information, must be a json string, optional
string NotifyExtension Notification extension field for chat room entry, must be a json string, optional
  • API prototype
public static void Login(long roomId, string request, LoginData loginData = null);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
request Get the authorization information by the interface of [Get the token](/en/docs/TM5MzM5Njk/jE1NDM1MTA#Get the token). Required.
loginData Personal information attached upon chat room entry, optional
  • Example

[View sample code](/en/docs/TM5MzM5Njk/jE1NDM1MTA#Get the token)

Exit the Chat Room

When exiting from chat room, the user will disconnect with chat room and will not receive any message from the chat room. The user can leave a chat room by manually calling the exit chat room interface.

  • API prototype
public static void Exit(long roomId);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
  • Example
//Take test room 3001 as an example
long roomId = 3001;
NIMChatRoom.ChatRoomApi.Exit(roomId);

Send Message

First create the message content Message, then useNIMChatRoom.ChatRoomApi.SendMessageinterface to deliver the message sending result to the users. You can send various types of messages, including text, image, audio, video, geographic location and other custom messages. For specific message content, please refer to IM messaging. No local storage for message history record, you can query message history in the cloud.

  • API prototype
public static void SendMessage(long roomId, Message msg);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
msg For message content, see Message
  • Example
Message createMessage(long room_id)
{
    Message msg = new Message();
    msg.MessageType = NIMChatRoomMsgType.kNIMChatRoomMsgTypeText;
    msg.AntiSpamEnabled = false;
    msg.AntiSpamContent = "";
    msg.MessageAttachment = "This is a test message";
    msg.ClientMsgId = "nsgid"; //Generate the unique message id

    return msg;
}

//Take test room 3001 as an example
long roomId = 3001;
Message msg = createMessage(roomId);
NIMChatRoom.ChatRoomApi.SendMessage(roomId,msg);

Query Cloud-based Message History

SDK supports querying chat room message records stored in the cloud.

  • API prototype
public static void QueryMessageHistoryOnline(long roomId, long startTimeStamp, int count, QueryMessageHistoryResultDelegate cb);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
startTimeStamp Query start timestamp (ms)
count Query quantity. The value must be larger than 0.
cb Result callback notification
  • Example
//Take test room 3001 as an example
long roomId = 3001;
long startTimetag = 1520391909233;//13-digit timestamp (ms)
NIMChatRoom.ChatRoomApi.QueryMessageHistoryOnline(roomId,startTimetag,20,(roomId,code,messages)=>
{
	...
});

Chat Room Management

Get Chat Room Information

Chat room information is available through the event of entering chat room or separate interface. SDK doesn't provide local cache for chat room information. It only provide the interface for query from server, the use of which is subject to limitations on frequency of server interface usage.

ChatRoomInfoDescription of key parameters

Type Parameter Description
long RoomId Chat Room id, i.e. the room number
string RoomName Chat room name, can be updated by manager
string Announcement Chat room announcement
string BroadcastUrl Address of video live streaming
string CreatorId Account id of Chat room creator
int Valid Chat room validity tag, 1: valid, 0: invalid
string Extension Third-party extension field, must be an unformatted string that can be parsed as Json, with a length of 4000
int OnlineMembersCount Number of online members
bool IsMuted Tag for chat room mute, 1: muted 0: not muted
  • API prototype
public static void GetRoomInfo(long roomId, GetRoomInfoDelegate cb);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
cb Result callback notification
  • Example
//Take test room 3001 as an example
long roomId = 3001;
NIMChatRoom.ChatRoomApi.GetRoomInfo(roomId, (room_Id, errorCode, info) =>
{
	...
});

Update Chat Room Information

SDK supports updating chat room information, but it can only done by the manager. For now, only four attributes of ChatRoomInfo can be updated, namelyRoomName,Announcement,BroadcastUrl,Extension . You can determine whether chat room broadcast notification is needed for the update.

  • API prototype
public static void UpdateRoomInfo(long roomId, ChatRoomInfo info, UpdateRoomInfoDelegate cb, bool notify, string notify_ext);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
info Information of chat room update
cb Result callback notification
notify Whether to enable chat room broadcast notification, true: enable, if sonotify_extcan’t be null, false: disable
notify_ext Custom field in the notification, with a length not exceeding 2048
  • Example
//Take test room 3001 as an example
long roomId = 3001;
var ri = new ChatRoomInfo
{
    RoomId = roomId,
    Announcement ="Chat room announcement",
    RoomName = "newName",
    BroadcastUrl = "http://xxxxx",
    Extension = "{\"test"\:\"1111\"}", //Custom extension string
};

NIMChatRoom.ChatRoomApi.UpdateRoomInfo(roomId, ri,(room_Id, errorCode) =>
{
	...
},false,null);

Get List of Chat Room Members

The information of permanent members, information of online permanent members, and information of guests can be acquired via the interface MemberInfo, where extension field is filled in when the user enters a chat room. There are four types of fixed members: creator, manager, normal user, and restricted user. Muted and blacklisted users are all restricted users. The member list information is not cached locally, and can be directly obtained from the cloud.

MemberInfoDescription of key parameters

Type Parameter Description
long RoomId Chat Room id, i.e. the room number
string MemberId Member account
ChatRoomMemberType MemberType Member type, -1: restricted user; 0: normal user; 1: creator; 2: manager, see ChatRoomMemberType for details
int Level A member level that is greater than 0 indicates the level can be customized by user/developer
string CreatorId Account id of Chat room creator
string Nick Chat room nickname field, can be submitted by the user upon entering the chat room
string MemberIcon Chat room avatar, can be submitted by the user upon entering the chat room
string Extension Third-party extension field, must be an unformatted string that can be parsed as JSON, with a length of 4000
NIMChatRoomOnlineState OnlineState Whether the member is online, only special members can be offline, visitors/anonymous users can only be online, 0: offline 1: online
NIMChatRoomGuestFlag GuestFlag Whether the user is an ordinary visitor, 0: no, 1: yes; the identity of a visitor is not persisted in the chat room, and would only be in memory when the user is online
long JoinTimeStamp The timestamp of chat room entry (in milliseconds), this field is null for offline members
bool IsInBlacklist Blacklisted? 1: Yes 0: No
bool IsMuted Muted? 1: Yes 0: No
bool IsValid Valid? 1: Yes 0: No
bool TempMuted Temporarily muted? 1: Yes 0: No
long TempMuteRestDuration Remaining time of temporary mute, in seconds
long UpdateTimetag Timestamp of updating fixed member history, used for sorting and query of fixed member list

NIMChatRoomGetMemberTypeEnumeration description

Enumeration Value Description
kNIMChatRoomGetMemberTypeSolid 0 Fixed members, fixed members, including creators, managers, normal users, restricted users (muted + blacklisted), even if they are not online, they are still in the list, but there is a limit on the number of fixed members
kNIMChatRoomGetMemberTypeTemp 1 Non-fixed members, non-fixed members, also known as temporary members, can only be seen in the list when they are online, and there is no limit on the number of these members

Enumeration description for member typeChatRoomMemberType

Enumeration Value Description
Restricted -1 Restricted member
Normal 0 Normal members
Creator 1 Creator
Manager 2 Manager
  • API prototype
public static void QueryMembersOnline(long roomId, NIMChatRoomGetMemberType memberType, long timeOffset, int limit, QueryMembersResultDelegate cb);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
memberType Member type
timeOffset Timestamp from current time
limit Query quantity
cb Result callback notification
  • Example
//Take test room 3001 as an example
long roomId = 3001;
long timeOffset = 0;//Timestamp from current time
NIMChatRoom.ChatRoomApi.QueryMembersOnline(roomId,NIMChatRoomGetMemberType.kNIMChatRoomGetMemberTypeSolid,timeOffset,20, (room_Id, errorCode, members) =>
{
	...
});

Get Information of the Specified Chat Room Member

The information of multiple designated accounts can be acquired from cloud via the interface MemberInfo.

  • API prototype
public static void QueryMemberInfosByIdCollection(long roomId, string[] idCollection, QueryMembersResultDelegate cb);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
idCollection Collection of member ids
cb Result callback notification
  • Example
//For example, for chat room members test1, test2 in test room 3001
long roomId = 3001;
string[] ids = new string[] ();
ids.add("test1");
ids.add("test2");

NIMChatRoom.ChatRoomApi.QueryMemberInfosByIdCollection(roomId,ids, (room_Id, errorCode, members) =>
{
	...
});

Update Personal Chat Room Information

Currently, you can only update your own chat room member information. Only nickname, avatar and extension field can be updated now. You can enable or disable notification of the update, if it is enabled, the users will be notified of the update through the event of receiving chat room notification.

  • API prototype
public static void UpdateMyRoleInfo(long roomId, MemberInfo info, UpdateMyRoleDelegate cb, bool notify, string notify_ext,string jsonExt = null);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
MemberInfo Member information, only update the fields that need to be modified, currently you can only update three attributes of MemberInfo ,which are Nick, MemberIconandExtension . See MemberInfo.
cb Result callback notification
notify Whether to enable chat room broadcast notification, true: enable, if sonotify_extcan’t be null, false: disable
notify_ext Custom field in the notification, with a length not exceeding 2048
jsonExt Reserved field
  • Example
//For example, for chat room members test1, test2 in test room 3001
long roomId = 3001;
var ri = new MemberInfo
{
    RoomId = roomId,
    Nick = "newNick",
    MemberIcon = "http://xxxx/newIcon.png",
    Extension = null,
};

NIMChatRoom.ChatRoomApi.UpdateMyRoleInfo(roomId,ri, (room_Id, errorCode) =>
{
	...
},false,null);

Chat Room Permission Management

Set Member ID Tag

When setting as manger or removing a manager, the users will be notified of the event through the event of receiving chat room notification. See description of notification type. If a visitor is set as a manager and then removed from the manager role, he will become a normal member but not a visitor.

NIMChatRoomMemberAttributeEnumeration description

Enumeration Value Description
kNIMChatRoomMemberAttributeAdminister 1 Manager (fixed member), only the creator has the permission to increase operation level
kNIMChatRoomMemberAttributeNomalSold 2 Normal member, the operator must be a creator or manager
kNIMChatRoomMemberAttributeBlackList -1 Blacklist member, the operator must be a creator or manager
kNIMChatRoomMemberAttributeMuteList -2 Permanently muted member, the operator must be a creator or manager

MemberPropertyParameter description

Type Parameter Description
string MemberId Member account id
NIMChatRoomMemberAttribute Attribute Membership ID tag, see NIMChatRoomMemberAttribute for details
bool Optional Set the corresponding membership ID tag, 1: set 0: un-set
int Level User level. It is valid only when "Optional= 1 or 2" is true.
JsonExtension NotifyExtension Developer-customized extension field in the notification event generated by the operation, must be a JSON string
  • API prototype
public static void SetMemberPropertyOnline(long roomId, MemberProperty property, SetMemberPropertyDelegate cb);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
property For member attributes, see MemberProperty.
cb Operation result callback
  • Example
//For example, for chat room member test1 in test room 3001
long roomId = 3001;

// Confirm/Undo the designation of a manager.
var ri = new MemberProperty
{
    RoomId = roomId,
    MemberId = "test1",
    Attribute = NIMChatRoomMemberAttribute.kNIMChatRoomMemberAttributeAdminister,
	Optional = true,//If ri.Optional is set to false, it means to cancel the manager.
};

NIMChatRoom.ChatRoomApi.SetMemberPropertyOnline(roomId,ri, (room_Id, errorCodememberInfo) =>
{
	...
});

// Confirm/revoke "permanent mute"
var prop = new MemberProperty
{
    RoomId = roomId,
    MemberId = "test1",
    Attribute = NIMChatRoomMemberAttribute.kNIMChatRoomMemberAttributeMuteList,
	Optional = true,//If ri.Optional is set to false, it means to cancel mute.
};

NIMChatRoom.ChatRoomApi.SetMemberPropertyOnline(roomId,prop, (room_Id, errorCodememberInfo) =>
{
	...
});

Temporarily Mute Members

This interface provides the feature of temporarily muting members and revoking the mute. To permanently mute the user, set the user as a muted user by using the set member ID tag interface. The mute will be automatically revoked upon expiration of the mute duration. The duration in notification message after successfully setting temporary mute is remaining time of mute. If the mute duration is set to 0, it means 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.

  • API prototype
public static void TempMuteMember(long roomId, string accid, long duration, TempMuteMemberDelegate cb, bool notify, string notify_ext);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
accid Member account, required)
duration Temporary mute duration (in seconds), set to 0 if the mute is released
cb Operation result callback
notify Enable broadcast notification in the chat room?
notify_ext Custom field in the notification, with a length not exceeding 2048
  • Example
//For example, mute chat room member test1 in test room 3001 for 60s
long roomId = 3001;
NIMChatRoom.ChatRoomApi.TempMuteMember(roomId,"test1", 60,(room_Id, errorCodememberInfo) =>
{
	...
},false,null);

Kick Online Members Out

Kick out member Only the manager can kick out normal member, only the creator can kick out manager. The extension field of kickout notification can be added. This field will be covered in extension field of kickout notification. The notification of chat room kick-out is sent to the developer through the Chat room notification event.

  • API prototype
public static void RemoveMember(long roomId, string memberId, string notify, RemoveMemberDelegate cb);
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
memberId Member account
notify Extension field placed in the event notification
cb Operation result callback
  • Example
//For example, for chat room member test1 in test room 3001
long roomId = 3001;
NIMChatRoom.ChatRoomApi.RemoveMember(roomId,"test1","notify" ,(room_Id, errorCode) =>
{
	...
});

Chat Room Queue Service

Chat room provides a queue service for the scene of live streaming with mic link.

New (updated) Queue Element of Mic Queue

Chat room queue service: add or update queue elements (only for chat room manager).When element_key doesn’t exist , calling this interface means adding a new element. If element_key exists,calling this interface means updating element_key in elemnet_value.

  • API prototype
public static void QueueOfferAsync(long roomId, string element_key, string elemnet_value, ChatRoomQueueOfferDelegate cb, string json_extension = "");
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
element_key Unique key of new element, with max. length 128 bytes
elemnet_value Content of new element, with max. length 4096 bytes
cb Operation result callback
json_extension Extension parameter, reserved
  • Example
//Take test room 3001 as an example
long roomId = 3001;
NIMChatRoom.ChatRoomApi.QueueOfferAsync(roomId,"key1","value1", (room_Id, errorCode) =>
{
	...
},null);

Take out Mic Queue Elements

element_keyis the unique key,ifelement_key is null, it means to take out the head element. If it is not null, it means to take out a specified element. After the operation is successfully done, the key and value of the element can be obtained from the callback notificationresult.

  • API prototype
 public static void QueuePollAsync(long roomId, string element_key, ChatRoomQueuePollDelegate cb, string json_extension = "");
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
element_key Unique key of the element, with a length not exceeding 128 bytes
cb Operation result callback
json_extension Extension parameter, reserved
  • Example
//Take test room 3001 as an example
long roomId = 3001;
NIMChatRoom.ChatRoomApi.QueuePollAsync(roomId,"key1",(room_Id, errorCode,result) =>
{
    //result: json string of the queue element, as obtained, example {"key":"key1","value":"value1"}
	...
},null);

Get All Queue Elements

Lists all the queue elements in order, and returns the JSON array of the queue elements in result.

  • API prototype
public static void QueueListAsync(long roomId, ChatRoomQueueListDelegate cb, string json_extension = "");
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
cb Operation result callback
json_extension Extension parameter, reserved
  • Example
//Take test room 3001 as an example
long roomId = 3001;
NIMChatRoom.ChatRoomApi.QueueListAsync(roomId,(room_Id, errorCode,result) =>
{
    //result: json array of queue elements, as obtained, examples include [{"key":"key1","value":"value1"},{"key":"key2","value":"value2"}]
	...
},null);

Delete Mic Queue

Deletes the entire mic queue, manager rights required.

  • API prototype
public static void QueueDropAsync(long roomId, ChatRoomQueueDropDelegate cb, string json_extension = "");
  • Parameter Description
Parameter Description
roomId Chat room id, i.e. room number, required
cb Operation result callback
json_extension Extension parameter, reserved
  • Example
//Take test room 3001 as an example
long roomId = 3001;
NIMChatRoom.ChatRoomApi.QueueDropAsync(roomId,(room_Id, errorCode) =>
{
	...
},null);

Clean the chat room

Clean up the resources consumed by the chat room. Call the method once before calling NIM.ClientApi.Cleanup.

  • API prototype
public static void Cleanup();
  • Example
private void OnApplicationQuit()
{
    //You Must call logout and cleanup resources for IM SDK.
    //In this,you should call synchronous method.
    // `Cleanup` should be called once only 
    //Firstly,you should exit chat room.
    NIMChatRoom.ChatRoomApi.Exit(CHATROOM_ID);
    NIM.ClientAPI.Logout(NIMLogoutType.kNIMLogoutAppExit);

    //Cleanup chat room plugin and then cleanup IM resources.
    NIMChatRoom.ChatRoomApi.Cleanup();
    NIM.ClientAPI.Cleanup();
}
Was this page helpful?
Yes
No
  • Chat Room Features:
  • Initialization and Clearup
  • Notification of Chat Room Event
  • Chat Room Login Event
  • ExitChatRoom Event
  • Chat Room Connection Status Change Notification
  • Receive Message Event
  • Notification of Message Sending Result
  • Event of Receiving Chat Room Notification
  • Enter A Chat Room
  • Get Token
  • Log in to Chat Room
  • Exit the Chat Room
  • Send Message
  • Query Cloud-based Message History
  • Chat Room Management
  • Get Chat Room Information
  • Update Chat Room Information
  • Get List of Chat Room Members
  • Get Information of the Specified Chat Room Member
  • Update Personal Chat Room Information
  • Chat Room Permission Management
  • Set Member ID Tag
  • Temporarily Mute Members
  • Kick Online Members Out
  • Chat Room Queue Service
  • New (updated) Queue Element of Mic Queue
  • Take out Mic Queue Elements
  • Get All Queue Elements
  • Delete Mic Queue
  • Clean the chat room