Live Streaming Room Scenario Implementation
Prerequisites
Before getting started, ensure you have created an application and completed client SDK integration.
Live Streaming Room Status Management
Live streaming room status typically includes: pending start, live streaming, paused, ended, and replaying. The live streaming room status is maintained by the business side.
Guest Mode
Applicable scenario: Users who have not registered or logged in on the business side enter the live streaming room.
It is recommended to register users to obtain a Token for connecting to RC, and restrict whether guests can send messages on the business side.
Creating and Joining a Chatroom
- The application server creates a chatroom via Server API Create Chatroom. After obtaining the chatroom ID, the client can join the chatroom.
- By default, the same user cannot join multiple chatrooms simultaneously. You can enable the Single User Joins Multiple Chatrooms feature on the Service Configuration page of the RC Console IM service.
- When joining a chatroom, the client SDK can retrieve the latest historical messages (default 10, maximum 50). You cannot pull specific message types via the client SDK, but you can configure Join Chatroom to Retrieve Specified Messages on the Service Configuration page of the RC Console IM service. To pull more messages, enable the Cloud Storage for Chatroom Messages service. To enable this service, please [submit a ticket].
Sample Code:
- Server SDK in Java
- Server SDK in PHP
- Server SDK in Go
RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
//Custom API URL method
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
Chatroom chatroom = rongCloud.chatroom;
ChatroomDataModel chatroomDataModel = new ChatroomDataModel().setId("chatroomId3");
ResponseResult result2 = chatroom.createV2(chatroomDataModel);
System.out.println("createV2: " + result2.toString());
require "./../../RongCloud.php";
define("APPKEY", '');
define('APPSECRET','');
use RongCloud\RongCloud;
use RongCloud\Lib\Utils;
/**
* Create Chatroom
*/
function create()
{
$RongSDK = new RongCloud(APPKEY,APPSECRET);
$chatroom = [
['id'=> 'phpchatroom4',//Chatroom ID
'name'=> 'phpchatroom1']//Chatroom name
];
$result = $RongSDK->getChatroom()->create($chatroom);
Utils::dump("Create Chatroom",$result);
}
create();
func TestRongCloud_ChatRoomCreateNew(t *testing.T) {
rc := NewRongCloud(
os.Getenv("APP_KEY"),
os.Getenv("APP_SECRET"),
)
// Create Chatroom
whiteUserIds := []string{"111", "222", "333"}
err := rc.ChatRoomCreateNew(
"chatroom001",
WithChatroomDestroyType(1),
WithChatroomDestroyTime(120),
WithChatroomIsBan(true),
WithChatroomWhiteUserIds(whiteUserIds),
)
t.Log(err)
}
FAQs:
- Can clients directly create chatrooms? No, only the server can create chatrooms.
- Can users send messages without joining the chatroom? By default, yes. You can enable the SDK Users Cannot Send Messages Without Joining Chatroom feature on the Service Configuration page of the RC Console IM service. Once enabled, users must join the chatroom to send messages.
- Are other chatroom members notified when a user joins or exits? By default, no. However, you can enable the Chatroom Member Change Monitoring feature. Once enabled, callback notifications will be sent to other chatroom members when users join or exit. This feature can be freely enabled on the Service Configuration page of the RC Console IM service and takes effect after 15 minutes.
- When a user logs in on multiple devices, does exiting the chatroom on one device log out other devices? By default, no. If you want all devices to exit simultaneously, you can freely enable the Multi-End Simultaneous Online: One End Exits Chatroom, Others Sync Exit feature on the Service Configuration page of the RC Console IM service. It takes effect after 15 minutes.
Chatroom Destruction (Chatroom Keepalive)
- Chatrooms have an auto-destruction mechanism. By default, if no users join or send messages within 1 hour, all members are kicked out and the chatroom is destroyed. For details, see Chatroom Destruction Mechanism. You can modify the destruction time by setting the "Auto-Destruction Type," up to 7 days (for specific chatrooms). For details, see Set Chatroom Auto-Destruction Type.
- If you also use RTC services, you can bind chatrooms to RTC rooms. When a chatroom meets the preset auto-destruction conditions, the system first checks whether the bound RTC room (RTCRoomId) still exists: if it does, auto-destruction is prevented; if not, the chatroom is destroyed immediately. For details, see Bind to RTC Room.
Chatroom Announcements
Applicable scenario: This feature allows users to view announcements for each live streaming room on the room list page or within the room.
Implement announcements via Chatroom Attribute Management (KV):
- Join the chatroom.
- Set chatroom announcement information via Chatroom Attribute Management (KV).
- Clients retrieve current chatroom announcement information via Get Chatroom KV Attribute.
- Use the
onChatRoomKVUpdateevent inKVStatusListenerto synchronize updated chatroom KV attributes, notifying all chatroom members. For details, see Add Chatroom KV Listener.
Client Sample Code:
- Android
- iOS
- Web
// Set Chatroom Attribute (KV)
String chatRoomId = "Chatroom ID";
// Chatroom attribute name. Key supports uppercase/lowercase letters, numbers, and special symbols + = - _, with a maximum length of 128 characters.
String key = "Custom chatroom key";//Mic status can also be implemented using Chatroom Attribute (KV).
// Chatroom attribute value, with a maximum length of 4096 characters.
String value = "This is a chatroom announcement";
// true: send notification; false: do not send. If a notification is sent, the SDK will receive a chatroom attribute notification message (ChatRoomKVNotiMessage) with type identifier RC:chrmKVNotiMsg, containing K and V.
boolean sendNotification = false;
// Whether to delete upon exit
boolean isAutoDel = false;
// Custom notification field, valid when sendNotification is true
String notificationExtra = "Custom notification field";
RongChatRoomClient.getInstance().setChatRoomEntry(chatRoomId, key, value, sendNotification, isAutoDel, notificationExtra, new IRongCoreCallback.OperationCallback() {
@Override
public void onSuccess() {
}
@Override
public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {
}
});
//Receiver side:
//Set the chatroom attribute (KV) status listener before joining the chatroom.
RongChatRoomClient.getInstance().addKVStatusListener(new RongChatRoomClient.KVStatusListener() {
@Override
public void onChatRoomKVSync(String roomId) {
//Triggered when chatroom attribute (KV) list synchronization is complete.
}
@Override
public void onChatRoomKVUpdate(String roomId, Map<String, String> chatRoomKvMap) {
//Monitor KV updates via onChatRoomKVUpdate
//Triggered when chatroom attribute (KV) list updates are complete. Returns all KVs during initial sync; subsequent triggers return only added/modified KVs.
}
@Override
public void onChatRoomKVRemove(String roomId, Map<String, String> chatRoomKvMap) {
//Triggered when KVs are deleted.
}
});
//Sender setup:
//Chatroom ID is the targetId of the chatroom conversation.
NSString *chatRoomId = @"chatRoomId";
//Chatroom attribute name. Key supports uppercase/lowercase letters, numbers, and special symbols + = - _, with a maximum length of 128 characters.
NSString *chatRoomNoticeKey = @"chatRoomNotice";
//Chatroom attribute value, with a maximum length of 4096 characters.
NSString *chatRoomNoticeValue = @"This is a chatroom announcement";
//Whether to send a notification. When set to true, an RCChatroomKVNotificationMessage is sent while setting the Key and Value.
BOOL isSendNotification = false;
//Whether to automatically delete the Key and Value when the user goes offline or exits. No notification is sent for auto-deletion.
BOOL isAutoDel = false;
//Custom notification field, valid when sendNotification is true.
NSString *extra = @"Custom notification field";
[[RCChatRoomClient sharedChatRoomClient] setChatRoomEntry:chatRoomId
key:chatRoomNoticeKey
value:chatRoomNoticeValue
sendNotification:isSendNotification
autoDelete:isAutoDel
notificationExtra:extra
success:^{
// Chatroom announcement KV setup successful; proceed with business operations.
} error:^(RCErrorCode nErrorCode) {
}];
//Receiver side:
// Set the chatroom attribute (KV) delegate before joining the chatroom and implement the corresponding delegate methods.
[[RCChatRoomClient sharedChatRoomClient] addChatRoomKVStatusChangeDelegate:self];
/**
IMLib chatroom attribute (KV) change callback.
@param roomId Chatroom ID
@param entry KV dictionary. If KVs exist when first joining the chatroom, all KVs are returned via this callback. Subsequent callbacks return only added/modified KVs.
*/
- (void)chatRoomKVDidUpdate:(NSString *)roomId entry:(NSDictionary<NSString *, NSString *> *)entry {
// Use this method to monitor KV changes for the corresponding roomId.
}
// Set Chatroom Attribute (KV) Listener
const listener = (event) => {
if (event.rejoinedRoom) {
console.log('SDK internal chatroom reconnection info:', event.rejoinedRoom)
}
if (event.updatedEntries) {
console.log('Monitored chatroom attribute (KV) updates:', event.updatedEntries)
}
if (event.userChange) {
console.log('User join/exit notifications:', event.userChange)
}
if (event.chatroomDestroyed) {
console.log('Chatroom destruction:', event.chatroomDestroyed)
}
}
RongIMLib.addEventListener(Events.CHATROOM, listener)
// Set Single Attribute
const entry = {
key: 'key',
value: 'value',
notificationExtra: 'extra',
isAutoDelete: true,
isSendNotification: false
}
RongIMLib.setChatRoomEntry(chatRoomId, entry).then(res => {
// Chatroom single attribute setup successful
if(res.code === 0){
console.log(res.code)
} else {
console.log(res.code, res.msg)
}
}).catch(error => {
console.log(error)
})
Server Code Examples:
- Server SDK in Java
- Server SDK in PHP
- Server SDK in GO
RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
// Custom API URL configuration
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
ChatroomEntry entry = rongCloud.chatroom.entry;
ChatroomEntryModel model = new ChatroomEntryModel();
model.setChatroomId("chatroomId1");
model.setUserId("userId1");
model.setKey("key1");
model.setValue("value1");
model.setAutoDelete(0);// Optional
model.setObjectName("RC:TxtMsg");// Optional
model.setContent("{\"key1\":\"value1\"}");// Optional
ResponseResult result = entry.set(model);
System.out.println("chatroomEntrySet Result: " + result.toString());
/**
* Chatroom attribute configuration
*/
use RongCloud\Lib\Utils;
use RongCloud\RongCloud;
require "./../../RongCloud.php";
define("APPKEY", '');
define('APPSECRET', '');
/**
* Configure chatroom attributes (KV)
*/
function set() {
$RongSDK = new RongCloud(APPKEY, APPSECRET);
// Create chatroom
$RongSDK->getChatroom()->create(['id' => 'chatroom001', 'name' => 'RongCloud']);
$params = [
'id' => 'chatroom001',//Chatroom ID
'userId' => 'userId01',//Operator User ID
'key' => 'key01',//Chatroom attribute name
'value' => 'value01',//Chatroom attribute value
];
$Entry = $RongSDK->getChatroom()->Entry()->set($params);
Utils::dump("Configure chatroom attributes (KV)", $Entry);
}
func TestRongCloud_ChatRoomEntrySet(t *testing.T) {
rc := NewRongCloud(os.Getenv("APP_KEY"), os.Getenv("APP_SECRET"))
t.Logf("app key: %s; app secret: %s", os.Getenv("APP_KEY"), os.Getenv("APP_SECRET"))
if err := rc.ChatRoomEntrySet("chrm01", "abc", "aaa", "bbb", false); err != nil {
t.Errorf("failed to chatroom entry set. err: %v", err)
} else {
t.Log("success")
}
}
Chatroom Message Priority
When chatroom message volume is high, the system discards the latest messages exceeding the consumption limit in chronological order to ensure server stability. For details, see Discard Policy.
Chatroom messages are prioritized by importance. Recommended priority order (highest to lowest):
- Tipping and gift messages (typically expected to be visible to all users in the live stream)
- Text, voice, and image messages
- Like messages
You can configure up to 20 low-priority message types. When server load is high, the system preferentially discards low-priority messages. See Chatroom Low-Priority Message Feature.
To protect messages from specific users, use the Chatroom User Allowlist feature to prioritize their messages under all circumstances.
To protect important messages, use the Chatroom Message Allowlist feature.
Chatroom Gift and Like Messages
Use case: Sending gift or like messages in live streams. Implement these message types using Custom Messages.
General Handling Mechanism for Chatroom Gift Messages
-
Client-Business Server Interaction and Billing: When the client sends a request to the business server via short connection, billing is triggered first. After billing is completed, the gift sender sees "XXX sent XXX gift".
-
Message Sending After Billing: After billing, the system calls the server API to send custom gift messages.
-
Message Handling for Continuous Gifting: In scenarios where users send gifts rapidly, sending one message per click may cause server API rate limiting or excessive message volume.
For continuous gifting, we recommend the following consolidation approach:
- If users select a specific quantity (e.g., 10 gifts), send one message with the quantity parameter (10 in this case).
- For rapid consecutive clicks with uncertain final quantity:
- Consolidate every 20 clicks (adjustable) into one message.
- If the clicking duration exceeds 1 second, send one message. For example, if a user sends 99 gifts via rapid clicks or direct selection, only 5 messages need to be sent.
-
High-Frequency Small Gifts with Live Stream Rankings: Use Chatroom Attributes (KV). The app updates click counts to KV every 0.5 seconds, and other chatroom members view the gift leaderboard via KV.
General Handling Mechanism for Chatroom Like Messages
- Unlike gift messages, like messages typically don't involve billing and can be sent directly by the client.
- The client has a message rate limit (5 messages/second). We recommend consolidating multiple likes within one second into a single message. The application server can obtain like counts via Full Message Routing.
For message sending examples, see Send Messages. Below is sample client code for gift messages:
- Android
- iOS
- Web
// Register custom message type (after SDK initialization)
ArrayList<Class<? extends MessageContent>> myMessages = new ArrayList<>();
myMessages.add(CustomMessage.class);
RongCoreClient.registerMessageType(myMessages);
// Message receiving example: Set message listener (automatically triggered when messages arrive)
RongCoreClient.addOnReceiveMessageListener(
new io.rong.imlib.listener.OnReceiveMessageWrapperListener() {
@Override
public boolean onReceivedMessage(Message message, ReceivedProfile profile) {
int left = profile.getLeft();
boolean isOffline = profile.isOffline();
boolean hasPackage = profile.hasPackage();
}
});
// Message object reference (use objectName or content to distinguish message types)
{
conversationType = PRIVATE,
targetId = 'userid3453',
messageId = 70,
channelId = '',
messageDirection = RECEIVE,
senderUserId = 'userid3453',
receivedStatus = io.rong.imlib.model.Message$ReceivedStatus @560f848,
sentStatus = SENT,
receivedTime = 1739428279001,
sentTime = 1739428279158,
objectName = 'gift:CustomMsg',
content = CustomMessage {
giftName = 'Custom gift message', giftCount = 3
},
extra = '',
readReceiptInfo = io.rong.imlib.model.ReadReceiptInfo @b8d3c06,
messageConfig = io.rong.imlib.model.MessageConfig @61092c7,
messageConfig = MessagePushConfig {
disablePushTitle = false,
pushTitle = '',
pushContent = '',
pushData = 'null',
templateId = '',
forceShowDetailContent = false,
iOSConfig = null,
androidConfig = null,
harmonyConfig = null
},
canIncludeExpansion = false,
expansionDic = null,
expansionDicEx = null,
mayHasMoreMessagesBefore = false,
UId = 'CKVO-0J6T-GM26-D3E6',
disableUpdateLastMessage = 'false',
directedUsers = '0'
}
// Receiver sets message delegate and implements corresponding methods (use message.content or objectName to distinguish message types)
- (void)onReceived:(RCMessage *)message left:(int)nLeft object:(id)object offline:(BOOL)offline hasPackage:(BOOL)hasPackage {
if ([message.content isMemberOfClass:[CustomMessage class]]) {
CustomMessage *msg = (CustomMessage *)message.content;
NSString *giftName = msg.giftName;
int giftCount = msg.giftCount;
}
}
// Custom message content example
_isOffline = false
_canIncludeExpansion = false
_hasChanged = false
_disableUpdateLastMessage = false
_conversationType = 4
_targetId = @"123"
_channelId = @""
_messageId = 17
_messageDirection = 2
_senderUserId = @"123"
_receivedStatusInfo RCReceivedStatusInfo * 0x3025eb5c0
_sentStatus = 30
_receivedTime = 1740566955000
_sentTime = 1740566955056
_objectName = @"gift:CustomMsg"
_content CustomMessage * 0x300691b80
_RCMessageContent RCMessageContent
_senderUserInfo RCUserInfo * 0x303ccb6f0
_userId = @"RongCloud UserId"
_name = @"Anonymous"
_portraitUri = @"Avatar URL"
_alias
_extra = @"Level 9 Fan"
_mentionedInfo
_auditInfo
_destructDuration = 0
_extra
_rawJSONData
_contentBaseKeys
_giftCount = 9
_giftName = @"Flowers"
_extra = @""
_messageUId = @"CL87-G08C-6L85-E222"
_readReceiptInfo
_groupReadReceiptInfoV2
_messageConfig RCMessageConfig * 0x30279cee0
_messagePushConfig RCMessagePushConfig * 0x300693110
_directedUserIds
_destructTime = 0
_expansionDicEx
// Set message listener
const Events = RongIMLib.Events
RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
console.log(evt.messages)
})
// Register custom message
const PersonMessage = RongIMLib.registerMessageType('s:person', true, true, [], false)
// Send custom message
// Construct custom message
const message = new PersonMessage({ name: 'someone', age: 18 })
// Custom message receiving example
{
// Filter gift messages using messageType
"messageType": "gift:CustomMsg",
"channelId": "",
"content": {
"giftName": "someone",
"giftCount": 3
},
"senderUserId": "user01",
"targetId": "chart01",
"conversationType": 4,
"sentTime": 1743414376795,
"receivedTime": 0,
"messageUId": "Unique message ID",
"messageDirection": 1,
"isPersited": true,
"isCounted": true,
"isMentioned": false,
"disableNotification": false,
"isStatusMessage": false,
"canIncludeExpansion": false,
"expansion": null,
"receivedStatus": 0,
"receivedStatusInfo": {
"isRead": false,
"isListened": false,
"isDownload": false,
"isRetrieved": false
},
"messageId": 8488190336485840000,
"sentStatus": 30,
"isOffLineMessage": false
}
Server Example Code
- Server SDK in Java
- Server SDK in PHP
- Server SDK in GO
RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
//Custom API endpoint configuration
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
Chatroom chatroom = rongCloud.message.chatroom;
String[] chatroomIds = {"chatroom ID"};
GiftCustomTxtMessage ctm = new GiftCustomTxtMessage("Custom Gift",2);
ChatroomMessage chatroomMessage = new ChatroomMessage()
.setSenderId("1")
.setTargetId(chatroomIds)
.setContent(ctm)
.setObjectName(ctm.getType());
ResponseResult chatroomResult = chatroom.send(chatroomMessage);
System.out.println("send chatroom message: " + chatroomResult.toString());
require "./../../RongCloud.php";
define("APPKEY", '');
define('APPSECRET','');
use RongCloud\RongCloud;
use RongCloud\Lib\Utils;
function send()
{
$RongSDK = new RongCloud(APPKEY,APPSECRET);
$message = [
'senderId'=> 'aP9uvganV',//Sender ID
'targetId'=> ['OIBbeKlkx'],//Chatroom ID
"objectName"=>'gift:CustomMsg',//Message type (text)
'content'=>json_encode(['giftName'=>'Custom Gift', 'giftCount'=>2])//Message content
];
$Chartromm = $RongSDK->getMessage()->Chatroom()->send($message);
Utils::dump("Send chatroom message",$Chartromm);
}
send();
func TestRongCloud_ChatRoomSend(t *testing.T) {
rc := NewRongCloud(
os.Getenv("APP_KEY"),
os.Getenv("APP_SECRET"),
)
msg := TXTMsg{
giftName: "giftName",
giftCount:2
}
res, err := rc.ChatRoomSend(
"7Szq13MKRVortoknTAk7W8",
[]string{"4kIvGJmETlYqDoVFgWdYdM"},
"gift:CustomMsg",
&msg, 0, 0,
)
t.Log(err)
t.Log(res)
}
</TabItem>
</Tabs>
Reference custom message classes for each platform:
- [Android CustomMessage.java](/partials/im/assets/CustomMessage.java)
- [iOS CustomMessage.h](/partials/im/assets/CustomMessage.h)
- [iOS CustomMessage.m](/partials/im/assets/CustomMessage.m)
- [Server SDK GiftCustomTxtMessage.java](/partials/im/assets/GiftCustomTxtMessage.java)
## Live Room User Identity and Levels
Use case: Displaying user levels and identity information in live rooms.
Implementation: Carry user information through message bodies to display levels and identities. For calculating user levels based on metrics like online duration, likes, or gifts, use callback functions to obtain data sources.
For example:
- Use [Chatroom Status Sync](/platform-chat-api/chatroom/status) to track user online duration
- Use [Message Callback](/platform-chat-api/moderation/msgcb) to obtain like/gift counts
**Example Code**
<Tabs
defaultValue="android"
values={[
{label: 'Android', value: 'android'},
{label: 'iOS', value: 'ios'},
{label: 'Web', value: 'web'},
]}>
<TabItem value="android">
```java
// Reference gift message implementation for custom messages
CustomMessage content = CustomMessage.obtain("Message content");
UserInfo userInfo=new UserInfo("userId1","userName1", Uri.parse("Avatar URL"));
userInfo.setExtra("Level and identity info");
Message msg = Message.obtain(ROOM_ID, ConversationType.CHATROOM, content);
String pushContent = null;
String pushData = null;
RongCoreClient.getInstance().sendMessage(message, pushContent, pushData, new IRongCoreCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {
}
@Override
public void onSuccess(Message message) {
}
@Override
public void onError(Message message, IRongCoreEnum.CoreErrorCode coreErrorCode) {
}
});
// Create custom gift message
CustomMessage *giftMessage = [CustomMessage messageWithGiftName:@"Flowers" GiftCount:9];
// Set user information
RCUserInfo *userInfo = [[RCUserInfo alloc] initWithUserId:@"RC UserId" name:@"Anonymous" portrait:@"Avatar URL"];
userInfo.extra = @"Level 9 Fan";
giftMessage.senderUserInfo = userInfo;
// Send custom gift message
RCMessage *message = [[RCMessage alloc] initWithType:ConversationType_CHATROOM targetId:@"chatRoomId" direction:MessageDirection_SEND content:giftMessage];
[[RCCoreClient sharedCoreClient] sendMessage:message pushContent:nil pushData:nil attached:^(RCMessage * _Nullable message) {
// Message stored successfully
} successBlock:^(RCMessage * _Nonnull successMessage) {
// Message sent successfully
} errorBlock:^(RCErrorCode nErrorCode, RCMessage * _Nonnull errorMessage) {
}];
// Send text message with user info
const message= new RongIMLib.TextMessage({
content: 'Text message',
extra: 'Extension field',
// Include user info
user: {
id: '',
name: '',
portraitUri: '',
extra: ''
}
})
// Send message
RongIMLib.sendMessage({
conversationType: RongIMLib.ConversationType.CHATROOM,
targetId: '<targetId>'
}, message).then(res => {
if (res.code === 0) {
console.log(res.code, res.data)
} else {
console.log(res.code)
}
})
Online User Statistics and Display
To track cumulative view counts, you can use Chatroom Status Sync for statistics.
Live Room Member List and Contribution Ranking
-
Member List
You can query up to 20 chatroom members (including user IDs and join timestamps) using the client SDK's Get Chatroom Info feature. -
Contribution Ranking
Calculate contribution rankings based on your business logic on the server side, then notify chatroom members via Set/Update Chatroom KV Attributes.
Live Room Muting and Banning (Kicking)
Use cases: Restrict user behavior in live rooms according to business requirements.
Chatroom Muting Service
-
Global Chatroom Mute
Use Mute All Chatroom Members to prevent all members from sending messages via client SDK. To exempt specific users, add them to the Chatroom Mute Allowlist. Mute data is cleared when the chatroom is dissolved. This feature is free.tip- Chatroom mute allowlist takes precedence over Global Chatroom Mute.
- Chatroom mute allowlist is overridden by Global User Mute.
- Allowlist status persists after users leave the chatroom but becomes invalid if the chatroom is destroyed and recreated.
-
Global User Mute
Use Global User Mute to mute specified users across all chatrooms in your application for a set duration. Muted users cannot send messages via client SDK. The Global Chatroom Mute Service is enabled by default in the development environment (dev). In production environments, this feature is supported only for Chat Pro Plan and is not supported for Chat Starter Plan. -
Mute Specific Chatroom Users
Use Mute Chatroom Users to mute 1+ users in specific chatrooms. Muted users can view messages but cannot send them. Mute status persists after users leave the chatroom. This feature is free.
Note: Server API messages are not affected by chatroom mute restrictions.
Client-Side Mute Monitoring Code Samples:
- Android
- iOS
- Web
// Set mute listener
//Set mute listener
RongChatRoomClient.addChatRoomNotifyEventListener(
new RongChatRoomClient.ChatRoomNotifyEventListener() {
@Override
public void onChatRoomNotifyMultiLoginSync(ChatRoomSyncEvent event) {
//Multi-device login sync for chatroom join/exit
}
@Override
public void onChatRoomNotifyBlock(ChatRoomMemberBlockEvent event) {
//Chatroom mute/unmute events
}
@Override
public void onChatRoomNotifyBan(ChatRoomMemberBanEvent event) {
//Chatroom ban/unban events
}
});
// Remove
// Add chatroom event listener
// Add chatroom event listener
[[RCChatRoomClient sharedChatRoomClient] addChatRoomNotifyEventDelegate:self];
// Implement chatroom event callbacks
/**
Multi-device login event callback
Three notification cases:
1. Multi-device login: Notify other devices when one device joins chatroom
2. Multi-device login: Notify other devices when one device exits chatroom
3. Multi-chatroom scenario: When user joins new chatroom on another device,
automatically kicks user from previous chatroom and notifies all members
Note: Case 3 doesn't trigger if multi-chatroom joining is enabled
- Parameter event: RCChatRoomSyncEvent
*/
- (void)chatRoomNotifyMultiLoginSync:(RCChatRoomSyncEvent *)event {
}
/**
User ban event callback
Two notification cases:
1. Ban user: Notifies all chatroom members (including banned user)
Notes:
* Banned users are automatically kicked
* Banned users won't receive kick notification
* Notification depends on server API parameter needNotify (default: false)
2. Unban user: Notifies unban recipient
Notes:
* Offline users won't receive notification upon login
* Only active unbans trigger notifications (auto-expiry doesn't)
* Only notifies unban recipient (depends on server API parameter needNotify)
Max ban duration: 43200 mins (1 month), Min: 1 minute
- Parameter event: RCChatRoomMemberBlockEvent
*/
- (void)chatRoomNotifyBlock:(RCChatRoomMemberBlockEvent *)event {
}
/**
Mute event callback
Cases:
Notes:
* Mute exceptions: Allowlist users won't be muted
* Notification depends on server API parameter needNotify (default: false). Scope:
1. Mute specific chatroom user: Notifies all chatroom members
2. Unmute specific chatroom user: Notifies all chatroom members
Notes:
* Global mute also respects allowlist
* Notification depends on server API parameter needNotify (default: false). Scope:
3. Global chatroom mute: Notifies all members
4. Remove global chatroom mute: Notifies all members
Notes:
* Allowlist is chatroom-specific (cleared when chatroom is destroyed)
* Notification depends on server API parameter needNotify (default: false). Scope:
5. Add mute allowlist: Notifies all members
6. Remove mute allowlist: Notifies all members
Notes:
* Global mute takes highest priority (overrides allowlist)
* Only globally muted/unmuted users receive notifications (depends on needNotify)
7. Global user mute: Notifies muted user
8. Global user unmute: Notifies unmuted user
Max mute duration: 43200 mins (1 month), Min: 1 minute
- Parameter event: ```RCChatRoomMemberBanEvent```
*/
- (void)chatRoomNotifyBan:(RCChatRoomMemberBanEvent *)event {
}
// Monitor chatroom events
const listener = (event) => {
if (event.rejoinedRoom) {
console.log('SDK chatroom reconnection info:', event.rejoinedRoom)
}
if (event.updatedEntries) {
console.log('Chatroom KV attribute updates:', event.updatedEntries)
}
if (event.userChange) {
console.log('User join/exit notifications:', event.userChange)
}
if (event.chatroomDestroyed) {
console.log('Chatroom destruction:', event.chatroomDestroyed)
}
/* since 5.7.9 */
if (event.chatroomNotifyMultiLoginSync) {
console.log('Multi-device sync notifications:', event.chatroomNotifyMultiLoginSync)
}
/* since 5.7.9 */
if (event.chatroomNotifyBlock) {
console.log('User ban notifications:', event.chatroomNotifyBlock)
}
/* since 5.7.9 */
if (event.chatroomNotifyBan) {
console.log('User mute notifications:', event.chatroomNotifyBan)
}
}
RongIMLib.addEventListener(Events.CHATROOM, listener)
FAQs:
- How to prevent specific users from speaking in any chatroom?
Use Global User Mute to restrict specified users from sending messages in all chatrooms.
Muted users can still receive and view messages in chatrooms but cannot send messages. The Global Chatroom Mute Service is enabled by default in the development environment (dev). In production environments, this feature is supported only for Chat Pro Plan and is not supported for Chat Starter Plan.
Chatroom Ban (Kick) Functionality
Using the Ban Chatroom User feature, you can ban one or more users in a specified chatroom (with a maximum of 20 users at a time).
-
If a user is in the chatroom when banned, they will be immediately kicked out.
-
Banned users cannot rejoin the chatroom during the ban period.
-
The ban duration is measured in minutes, with a maximum of 43,200 minutes. For details, see Ban Chatroom User.
FAQs:
-
How to prevent certain users from being automatically kicked out of a chatroom? You can add users to the allowlist to achieve this. A single chatroom supports up to 5 allowlisted users. The Chatroom User Allowlist Service is enabled by default in the development environment (dev). In production environments, this feature is enabled by default for Chat Pro Plan and is not supported for Chat Starter Plan.
-
Why isn't an offline user being kicked out of the chatroom? Chatrooms have an automatic kick mechanism for offline members. The RC server will automatically kick out offline users only if the following default conditions are met:
- When the 31st message is sent in the chatroom within 30 seconds after the user goes offline.
- When a new message is sent in the chatroom more than 30 seconds after the user goes offline.
- If the above conditions are not met but you still want the user to be kicked out, you can submit a ticket to enable the Real-time Kick for Abnormal Chatroom Member Disconnections feature. Once enabled, the server will determine abnormal user status based on SDK behavior and kick out such users within 5 minutes at the latest. This feature is free.
Chatroom Ban User Code Examples:
- Server SDK in Java
- Server SDK in PHP
- Server SDK in GO
RongCloud rongCloud = RongCloud.getInstance("appKey", "appSecret");
Block block = rongCloud.chatroom.block;
ChatroomMember[] members = {
new ChatroomMember().setId("user1"),
new ChatroomMember().setId("user2")
};
ChatroomModel chatroom = new ChatroomModel()
.setId("chatroomid")
.setMembers(members)
.setMinute(5);
ResponseResult result = block.add(chatroom);
System.out.println("addBlockUser: " + result.toString());
require "./../../RongCloud.php";
define("APPKEY", '');
define('APPSECRET','');
use RongCloud\RongCloud;
use RongCloud\Lib\Utils;
function add()
{
$RongSDK = new RongCloud(APPKEY,APPSECRET);
$chatroom = [
'id' => 'OIBbeKlkx',//Chatroom ID
'members' => [
['id' => 'aP9uvganV']//Banned member ID
],
'minute' => 500//Ban duration
];
$Block = $RongSDK->getChatroom()->Block()->add($chatroom);
Utils::dump("Add Ban", $Block);
}
add();
func TestRongCloud_ChatRoomBlockAddOptions(t *testing.T) {
rc := NewRongCloud(
os.Getenv("APP_KEY"),
os.Getenv("APP_SECRET"),
)
err := rc.ChatRoomBlockAdd(
"chrm01",
[]string{"u01"},
30,
WithChatroomNeedNotify(true),
WithChatroomExtra("block u01"),
)
t.Log(err)
}
</TabItem>
</Tabs>
## Sensitive Content Filtering
Use case: Review and filter sensitive information to ensure message content compliance.
You can use the built-in sensitive word filtering mechanism to review sensitive content. To notify clients, you must enable the **Blocked Message Status Callback to Sender** feature in the [RC Console](https://console.rongcloud.io/agile/im/service/config) under **Chat** > **Chat settings** > **Security & Moderation**.
When the client SDK detects a message containing sensitive words, it actively retrieves the original message and sets the sending status to failed or handles business logic.
**Client-Side Sensitive Word Interception Handling Example**:
<Tabs
defaultValue="android"
values={[
{label: 'Android', value: 'android'},
{label: 'iOS', value: 'ios'},
{label: 'Web', value: 'web'},
{label: 'Harmony', value: 'harmony'},
]}>
<TabItem value="android">
```java
RongCoreClient.getInstance().setMessageBlockListener(new IRongCoreListener.MessageBlockListener() {
@Override
public void onMessageBlock(BlockedMessageInfo info) {
RongCoreClient.getInstance().getMessageByUid(info.getBlockMsgUId(), new IRongCoreCallback.ResultCallback<Message>() {
@Override
public void onSuccess(Message message) {
//Successfully retrieved local message
//Set message sending status to failed
message.setSentStatus(Message.SentStatus.FAILED);
RongCoreClient.getInstance().setMessageSentStatus(message, new IRongCoreCallback.ResultCallback<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
//Successfully called the method to set message sending status
}
@Override
public void onError(IRongCoreEnum.CoreErrorCode e) {
//Failed to call the method to set message sending status
}
});
}
@Override
public void onError(IRongCoreEnum.CoreErrorCode e) {
//Failed to retrieve local message
}
});
}
});
</TabItem>
<TabItem value="ios">
```objectivec
#pragma mark - RCMessageBlockDelegate
- (void)messageDidBlock:(RCBlockedMessageInfo *)blockedMessageInfo {
// Retrieve corresponding message information via messageUID
RCMessage *blockMessage = [[RCCoreClient sharedCoreClient] getMessageByUId:blockedMessageInfo.blockedMsgUId completion:^(RCMessage * _Nullable message) {
if (message != nil) {
// Call IMLibCore interface to modify message sending status
[[RCCoreClient sharedCoreClient] setMessageSentStatus:blockMessage.messageId sentStatus:SentStatus_FAILED completion:^(BOOL ret) {
// Refresh corresponding UI
}];
}
}];
}
```typescript
// Set up sensitive word monitoring
const listener = (message: IBlockedMessageInfo) => {
console.log(message);
};
RongIMLib.addEventListener(Events.MESSAGE_BLOCKED, listener);
// Set up sensitive word monitoring
IMEngine.getInstance().setMessageBlockedListener((blockInfo: MessageBlockInfo) => {
// Process sensitive word interception information blockInfo
});
Chatroom Broadcast Announcements
Use cases: Celebrity login notifications, full-screen gift notifications for all users, prize-winning announcements, emergency notifications, etc.
You can implement chatroom broadcast announcements through the Send Chatroom Broadcast Message feature. These messages are only received by users currently in the chatroom, and users who join later cannot receive them. The Chatroom Broadcast Message service is enabled by default in the development environment (dev). In production environments, this feature is supported only for Chat Pro Plan and is not supported for Chat Starter Plan.
Chatroom Event Update Scenarios
Use cases: Recording user PK status, mic on/off states, match scores, and other chatroom event updates.
-
Set custom attributes in specified chatrooms. For example, in voice live streaming chatrooms, use this feature to record attributes of each mic position; Or in card games like Werewolf, record user roles and game states. You can maintain these using Chatroom Attribute Management. Chatroom attributes are stored as Key-Value pairs, supporting set, delete, and query operations, with batch and forced operation capabilities. Client-side configuration is available for Chatroom Attributes. Each chatroom supports up to 100 KVs. This feature is free. For client sample code, see Chatroom Announcements.
-
To receive real-time attribute changes, configure the Chatroom Custom Attribute Callback URL in the Service Configuration page of RC's IM service Console. This free feature takes effect 15 minutes after activation.