聊天室标签管理
更新时间: 2025/04/29 10:53:07
网易云信 IM 支持聊天室标签功能,通过在登录时聊天室时设置标签信息,来达到个性化的聊天室效果。利用这一功能,您可以打造个性化、分层次的聊天体验,满足直播互动、社区运营等多种场景需求。
支持平台
本文内容适用的开发平台或框架如下表所示,涉及的接口请参考下文 相关接口 章节:
安卓 | iOS | macOS/Windows | Web/uni-app/小程序 | Node.js/Electron | 鸿蒙 | Flutter |
---|---|---|---|---|---|---|
✔️️️️️️ | ✔️️️️️️ | ✔️️️️️️ | ✔️️️️️️ | ✔️️️️️️ | ✔️️️️️️ | ✔️️ |
功能概述
网易云信 IM 的聊天室标签功能,允许开发者根据用户信息对聊天室用户进行分类管理,实现消息精准投递和用户分群,从而打造个性化的聊天体验。通过标签,您可以:
- 为用户分配特定标签(单用户最多 10 个标签)
- 精准控制消息投递范围
- 按标签管理成员禁言状态
- 查询特定标签下的在线用户
- 实现聊天室内的分组互动
- 通过标准的正则表达式匹配用户账号
核心概念
标签表达式 是标签功能的核心机制,用于精确描述目标用户群体。标签表达式有两个关键字段 tags
和 notifyTargetTags
。
tags
:识别用户所属的标签集合。notifyTargetTags
:指定需要通知或消息的目标标签用户。
tags
和 notifyTargetTags
必须设置其一,否则返回参数错误。
单个表达式限制最多 128 个字符。标签表达式支持以下高级特性:
表达式特性 | 示例 |
---|---|
指定匹配:使用普通赋值匹配指定的标签值 | 匹配标签 abc:{"tag": "abc"} |
正则匹配:使用正则表达式模糊匹配 | 匹配带 abc 的标签:{"tag": "abc.*", "matchType": "regex"} 匹配所有标签: {"tag": ".*", "matchType": "regex"} |
逻辑运算:使用与(and)、或(or)操作匹配多项结果 | 匹配标签 abc 和 def:{"tag": "abc"} and {"tag": "def"} 匹配标签 abc 或 def: {"tag": "abc"} or {"tag": "def"} |
控制优先级:通过半角括号(() )设置逻辑运算优先级 |
匹配标签 abc 或者 def,并且,使用正则匹配带 123 或 456 的标签: ({"tag": "abc"} or {"tag": "def"}) and ({"tag": ".*123", "matchType": "regex"} or {"tag": "456.*", "matchType": "regex"}) |
准备工作
根据本文操作前,请确保您已经完成了以下设置:
- 已 实现聊天室登录。
- 在使用聊天室服务中的 API 前,需要先调用
getChatroomService
方法获取聊天室服务类。
监听聊天室标签变更
在设置聊天室标签信息前,您可以先注册监听 onChatroomTagsUpdated
聊天室标签信息变更事件。监听后,在更新聊天室标签后,聊天室内所有成员会收到对应的通知。
JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
V2NIMChatroomListener listener = new V2NIMChatroomListener() {
@Override
public void onChatroomTagsUpdated(List<String> tags) {
}
};
v2ChatroomService.addChatroomListener(listener);
Objective-C@interface Listener: NSObject<V2NIMChatroomListener>
- (void)addToService;
@end
@implementation Listener
- (void)addToService
{
id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
[service addChatroomListener:self];
}
- (void)onChatroomTagsUpdated:(NSArray<NSString *> *)tags
{
}
@end
C++V2NIMChatroomListener listener;
listener.onChatroomTagsUpdated = [](nstd::vector<nstd::string> tags) {
// handle chatroom tags updated
};
chatroomService.addChatroomListener(listener);
TypeScriptchatroom.V2NIMChatroomService.on('onChatroomTagsUpdated', function (tags: Array<string>){})
TypeScriptchatroom.chatroomService.on('chatroomTagsUpdated', function (tags: Array<string>){})
TypeScriptchatroom.chatroomService.on('onChatroomTagsUpdated', (tags: Array<string>) => {})
Dart//首先添加监听
await chatroomClient?.getChatroomService().addChatroomListener();
//然后设置监听
chatroomClient!.getChatroomService().onChatroomTagsUpdated.listen((event) {
//todo something
});
设置聊天室标签信息
您可以通过以下两种方式设置标签信息。
-
登录时设置标签信息
调用
enter
方法登录聊天室时,通过配置tagConfig
来设置标签相关参数。 -
更新已有的标签信息
调用
updateChatroomTags
方法批量更新已有的聊天室标签信息。
登录时设置标签信息
调用 enter
方法登录聊天室时,通过配置 tagConfig
来设置以下标签相关参数:
tags
:用于标识本次登录所属标签,同一个长连接最多支持设置 10 个标签,每个标签最多 32 个字符,例如["abc", "def"]
。notifyTargetTags
:指定登录/登出聊天室通知广播的标签用户,具体请参考 标签表达式。若缺省则服务器会根据tags
自动自动生成一个标签表达式。
登录聊天室具体实现请参考 聊天室登录文档。
更新聊天室标签信息
调用 updateChatroomTags
方法批量更新聊天室标签信息。
更新后,聊天室内所有成员会收到聊天室标签信息变更回调 onChatroomTagsUpdated
,以及类型为 TAGS_UPDATE
的通知消息。
修改聊天室用户的标签后会通知被修改人的所有在线端,并广播通知聊天室内所有用户。
示例代码如下:
JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
V2NIMChatroomTagsUpdateParams updateParams = new V2NIMChatroomTagsUpdateParams();
// tag 列表
List<String> tags = getTags();
updateParams.setTags(tags);
updateParams.setNotifyTargetTags("xxx");
// 以上两个字段至少需要设置一个,否则会返回参数错误
v2ChatroomService.updateChatroomTags(updateParams, new V2NIMSuccessCallback<Void>() {
@Override
public void onSuccess(Void unused) {
// 更新成功
}
}, new V2NIMFailureCallback() {
@Override
public void onFailure(V2NIMError error) {
// 更新失败
}
});
Objective-C// 通过实例 ID 获取聊天室实例
id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
V2NIMChatroomTagsUpdateParams *updateParams = [[V2NIMChatroomTagsUpdateParams alloc] init];
// tag 列表
NSArray<NSString *> *tags = @[ @"tag0", @"tag1" ]];
updateParams.tags = tags;
updateParams.notifyTargetTags = @"xxx";
// 以上两个字段至少需要设置一个,否则会返回参数错误
[service updateChatroomTags:updateParams
success:^()
{
// 更新成功
}
failure:^(V2NIMError *error)
{
// 更新失败
}];
C++V2NIMChatroomTagsUpdateParams updateParams;
updateParams.tags = {"tag1", "tag2"};
updateParams.notifyTargetTags = R"({"tag": "tag1"})";
chatroomService.updateChatroomTags(
updateParams,
[]() {
// update chatroom tags succeeded
},
[](V2NIMError error) {
// update chatroom tags failed, handle error
});
TypeScriptawait chatroomV2.V2NIMChatroomService.updateChatroomTags(
{
"tags": [
"tag1",
"tag2"
],
"notifyTargetTags": "{tag: \"tag1\"}",
"notificationEnabled": true,
"notificationExtension": "notificationExtension"
}
)
TypeScriptawait chatroomService.updateChatroomTags({
tags: ['tag1', 'tag2']
})
TypeScriptawait this.chatroomClient.chatroomService.updateChatroomTags(
{
"tags": [
"tag1",
"tag2"
],
"notifyTargetTags": "{tag: \"tag1\"}",
"notificationEnabled": true,
"notificationExtension": "notificationExtension"
}
)
Dartfinal chatroomService = chatroomClient?.getChatroomService();
final params = V2NIMChatroomTagsUpdateParams();
var result = await chatroomService?.updateChatroomTags(params);
聊天室标签消息管理
发送聊天室标签消息
调用 sendMessage
方法发送聊天室消息时,设置 notifyTargetTags
参数指定聊天室消息投递的标签对象,实现消息的精准投递。具体请参考 标签表达式。若缺省则服务器会使用登录时设置的 notifyTargetTags
。
消息发送具体实现请参考 聊天室消息管理。
根据标签获取聊天室消息
通过调用 getMessageListByTag
方法按照标签信息分页获取所有聊天室历史消息,包含聊天室通知消息。
该方法用于分页获取聊天室消息数据,直到获取聊天室全量消息,获取到的消息不包括已删除消息。
示例代码如下:
JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
V2NIMChatroomTagMessageOption messageOption = new V2NIMChatroomTagMessageOption();
// tag 列表
List<String> tags = getTags();
// 设置查询的 tag 列表,必传字段,传 null 或者 size 为 0,会返回参数错误
messageOption.setTags(tags);
// 设置查询数量
messageOption.setLimit(100);
List<V2NIMMessageType> messageTypes = getMessageTypes();
// 设置查询的消息类型,如果列表为空,表示查询所有类型的消息
messageOption.setMessageTypes(messageTypes);
messageOption.setDirection(V2NIMMessageQueryDirection.V2NIM_QUERY_DIRECTION_DESC);
// 设置查询开始时间,首次传 0,单位毫秒
messageOption.setBeginTime(0L);
// 设置查询结束时间,默认 0 表示当前时间,单位毫秒
messageOption.setEndTime(0L);
v2ChatroomService.getMessageListByTag(messageOption, new V2NIMSuccessCallback<List<V2NIMChatroomMessage>>() {
@Override
public void onSuccess(List<V2NIMChatroomMessage> v2NIMChatroomMessages) {
// 查询成功
}
}, new V2NIMFailureCallback() {
@Override
public void onFailure(V2NIMError error) {
// 查询失败
}
});
Objective-C// 通过实例 ID 获取聊天室实例
id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
V2NIMChatroomTagMessageOption *messageOption = [[V2NIMChatroomTagMessageOption alloc] init];
// 设置查询的 tag 列表,必传字段,传 null 或者 size 为 0,会返回参数错误
messageOption.tags = @[@"tag1", @"tag2"];
// 设置查询数量
messageOption.limit = 100;
// 设置查询的消息类型,如果列表为空,表示查询所有类型的消息
messageOption.messageTypes = @[@(V2NIM_MESSAGE_TYPE_TEXT), @(V2NIM_MESSAGE_TYPE_FILE)];
// 设置查询方向
messageOption.direction = V2NIM_QUERY_DIRECTION_DESC;
// 设置查询开始时间,单位秒
messageOption.beginTime = 0;
// 设置查询结束时间,默认 0 表示当前时间,单位秒
messageOption.endTime = 0;
[service getMessageListByTag:messageOption
success:^(NSArray<V2NIMChatroomMessage *> *messages)
{
// 查询成功
}
failure:^(V2NIMError *error)
{
// 查询失败
}];
C++V2NIMChatroomTagMessageOption messageOption;
messageOption.tags = {"tag1", "tag2"};
messageOption.limit = 10;
chatroomService.getMessageListByTag(
messageOption,
[](nstd::vector<V2NIMChatroomMessage> messages) {
// get message list by tag succeeded
},
[](V2NIMError error) {
// get message list by tag failed, handle error
});
TypeScriptconst messages = await chatroom.V2NIMChatroomService.getMessageListByTag({
tags: ['tag1', 'tag2'], // 查询的 tags
limit: 100,
direction: V2NIMQueryDirection.V2NIM_QUERY_DIRECTION_DESC
})
TypeScriptconst result = await chatroomService.getMessageListByTag({
tags: ['tag1', 'tag2'],
limit: 10
})
TypeScriptconst messages = await this.chatroomClient.chatroomService.getMessageListByTag({
tags: ['tag1', 'tag2'], //查询的 tags
limit: 100,
direction: V2NIMQueryDirection.V2NIM_QUERY_DIRECTION_DESC
})
Dartfinal option = V2NIMChatroomTagMessageOption();
final messageList = (await chatroomService.getMessageListByTag(option));
聊天室标签成员管理
根据标签获取聊天室成员
通过调用 getMemberListByTag
方法根据标签分页获取聊天室成员列表。
查询某个标签下的在线成员列表,对于多端登录的用户,会返回多条记录。
该方法该操作从服务器同步数据,耗时可能较长。SDK 不缓存数据,您需要根据需要自行做好缓存。
示例代码如下:
JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
V2NIMChatroomTagMemberOption option = new V2NIMChatroomTagMemberOption();
// 设置查询 Tag,必传字段,如果不传,会返回参数错误
option.setTag("xxx");
// 设置查询数量
option.setLimit(100);
// 设置分页标识,首页传"",下一页传上次返回的 pageToken
option.setPageToken("");
v2ChatroomService.getMemberListByTag(option, new V2NIMSuccessCallback<V2NIMChatroomMemberListResult>() {
@Override
public void onSuccess(V2NIMChatroomMemberListResult v2NIMChatroomMemberListResult) {
// 查询成功
String pageToken = v2NIMChatroomMemberListResult.getPageToken();
List<V2NIMChatroomMember> memberList = v2NIMChatroomMemberListResult.getMemberList();
}
}, new V2NIMFailureCallback() {
@Override
public void onFailure(V2NIMError error) {
// 查询失败
}
});
Objective-C// 通过实例 ID 获取聊天室实例
id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
V2NIMChatroomTagMemberOption *option = [[V2NIMChatroomTagMemberOption alloc] init];
// 设置查询 Tag,必传字段,如果不传,会返回参数错误
option.tag = @"xxx";
// 设置查询数量
option.limit = 100;
// 设置分页标识,首页传"",下一页传上次返回的 pageToken
option.pageToken = @"";
[service getMemberListByTag:option
success:^(V2NIMChatroomMemberListResult *result)
{
// 获取成功
}
failure:^(V2NIMError *error)
{
// 获取失败
}];
C++V2NIMChatroomTagMemberOption option;
option.tag = "tag1";
option.pageToken = "";
option.limit = 10;
chatroomService.getMemberListByTag(
option,
[](V2NIMChatroomMemberListResult result) {
// get member list by tag succeeded
},
[](V2NIMError error) {
// get member list by tag failed, handle error
});
TypeScriptconst result = await chatroom.V2NIMChatroom.getMemberListByTag({
tag: 'abc', // 查询的 tag
limit: 100
})
TypeScriptconst result = await chatroomService.getMemberListByTag({
tag: 'tag',
limit: 10
})
TypeScriptconst result: V2NIMChatroomMemberListResult = await this.chatroomClient.chatroomService.getMemberListByTag({
tag: 'abc', // 查询的 tag
limit: 100
})
Dartfinal chatroomService = chatroomClient?.getChatroomService();
var option = V2NIMChatroomTagMemberOption();
var result = await chatroomService?.getMemberListByTag(option);
根据标签获取聊天室成员数量
通过调用 getMemberCountByTag
方法获取指定标签下的聊天室成员人数。
查询某个标签下的在线用户数,相同账号登录多端的情况下,在线用户数算 1 个。
JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
// 查询的 tag,必传字段,传 null 或者 "",会返回参数错误
String tag = "xxx";
v2ChatroomService.getMemberCountByTag(tag, new V2NIMSuccessCallback<Long>() {
@Override
public void onSuccess(Long count) {
// 查询成功
}
}, new V2NIMFailureCallback() {
@Override
public void onFailure(V2NIMError error) {
// 查询失败
}
});
Objective-C// 通过实例 ID 获取聊天室实例
id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
// 查询的 tag,必传字段,传 null 或者 "",会返回参数错误
NSString *tag = @"xxx";
[service getMemberCountByTag:tag
success:^(NSInteger memberCount)
{
// 获取成功
}
failure:^(V2NIMError *error)
{
// 获取失败
}];
C++chatroomService.getMemberCountByTag(
"tag1",
[](uint64_t count) {
// get member count by tag succeeded
},
[](V2NIMError error) {
// get member count by tag failed, handle error
});
TypeScriptconst count = await chatroom.V2NIMChatroomService.getMemberCountByTag('tagName')
TypeScriptconst count = await chatroomService.getMemberCountByTag('tag')
TypeScriptconst count = await this.chatroomClient.chatroomService.getMemberCountByTag('tagName')
Dartfinal chatroomService = chatroomClient?.getChatroomService();
var result = await chatroomService?.getMemberCountByTag('tag');
设置聊天室标签成员临时禁言
调用 setTempChatBannedByTag
方法设置聊天室标签临时禁言。设置后,被临时禁言的聊天室标签中的所有成员,无法在聊天室发送消息。临时禁言结束后,恢复发送消息权限。
仅允许聊天室创建者和管理员调用该接口,否则返回错误码 109432。
本地端或多端同步设置聊天室标签临时禁言成功后:
只有在配置参数 V2NIMChatroomTagTempChatBannedParams
中传入 notifyTargetTags
(需要通知的聊天室标签),临时禁言成功后,设置的聊天室标签下的成员才会收到以下回调和通知,若不传入 notifyTargetTags
,则不会触发。
- 被临时禁言的聊天室标签成员:收到临时禁言状态变更回调
onSelfTempChatBannedUpdated
。 - 聊天室内所有成员:
- 收到被临时禁言的标签成员信息变更回调
onChatroomMemberInfoUpdated
。 - 收到聊天室通知消息,通知消息类型为
TAG_TEMP_CHAT_BANNED_ADDED(14)
。解除聊天室标签临时禁言后,所有聊天室成员收到聊天室通知消息类型为TAG_TEMP_CHAT_BANNED_REMOVED(15)
。
- 收到被临时禁言的标签成员信息变更回调
JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
V2NIMChatroomTagTempChatBannedParams params = new V2NIMChatroomTagTempChatBannedParams();
//设置禁言的 tag,必传字段,如果不传,会返回参数错误
params.setTargetTag("xxx");
//设置禁言时长,单位:秒,单次最大:30 天,取消则设置为:0
params.setDuration(1000);
//是否需要通知,true:通知,false:不通知
params.setNotificationEnabled(true);
//设置通知扩展字段,可不传
params.setNotificationExtension("xxx");
v2ChatroomService.setTempChatBannedByTag(params, new V2NIMSuccessCallback<Void>() {
@Override
public void onSuccess(Void unused) {
//设置成功
}
}, new V2NIMFailureCallback() {
@Override
public void onFailure(V2NIMError error) {
//设置失败
}
});
Objective-C// 通过实例 ID 获取聊天室实例
id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
V2NIMChatroomTagTempChatBannedParams *params = [[V2NIMChatroomTagTempChatBannedParams alloc] init];
//设置禁言的 tag,必传字段,如果不传,会返回参数错误
params.targetTag = @"xxx";
//设置禁言时长,单位:秒,单次最大:30 天,取消则设置为:0
params.duration = 1000;
//是否需要通知,true:通知,false:不通知
params.notificationEnabled = YES;
//设置通知扩展字段,可不传
params.notificationExtension = @"xxx";
[service setTempChatBannedByTag:params
success:^()
{
// 设置成功
}
failure:^(V2NIMError *error)
{
// 设置失败
}];
C++V2NIMChatroomTagTempChatBannedParams params;
params.tags = "tag1";
params.duration = 60;
params.notificationEnabled = true;
params.notificationExtension = "notificationExtension";
chatroomService.setTempChatBannedByTag(
params,
[]() {
// set temp chat banned by tag succeeded
},
[](V2NIMError error) {
// set temp chat banned by tag failed, handle error
});
TypeScriptawait chatroomV2.V2NIMChatroomService.setTempChatBannedByTag(
{
"targetTag": "ccc", // 被禁言 tag
"notifyTargetTags": "{tag: \"ccc\"}", // 接收通知的目标表达式
"duration": 1000, // 禁言时长
"notificationEnabled": true // 是否通知
}
)
TypeScriptawait chatroomService.setTempChatBannedByTag({
"targetTag": "ccc", // 被禁言 tag
"notifyTargetTags": "{tag: \"ccc\"}", // 接收通知的目标表达式
"duration": 1000, // 禁言时长
"notificationEnabled": true // 是否通知
})
TypeScriptawait this.chatroomClient.chatroomService.setTempChatBannedByTag(
{
"targetTag": "ccc", // 被禁言 tag
"notifyTargetTags": "{tag: \"ccc\"}", // 接收通知的目标表达式
"duration": 1000, // 禁言时长
"notificationEnabled": true // 是否通知
}
)
Dartfinal chatroomService = chatroomClient?.getChatroomService();
final params = V2NIMChatroomTagTempChatBannedParams();
var result = await chatroomService?.setTempChatBannedByTag(params);
最佳实践
标签使用策略
有效的标签设计可提高聊天室管理效率和用户体验。例如:
- 用户角色标签:admin、vip、guest、new_user
- 设备标签:ios、android、web、pc
- 地域标签:north、south、overseas
- 兴趣标签:game、music、sports、tech
- 活动标签:event_2023、campaign_summer
性能与容量优化
- 控制标签数量:单用户标签不宜过多,建议控制在 10 个以内。
- 缓存标签数据:SDK 不缓存标签相关数据,请自行实现缓存逻辑。
- 分批处理大规模标签操作:对于大型聊天室,考虑分批设置或更新标签。
参考文档
相关接口
API | 说明 |
---|---|
V2NIMChatroomClient.getChatroomService |
获取聊天室服务类 |
V2NIMChatroomService.addChatroomListener |
注册聊天室监听器 |
V2NIMChatroomService.removeChatroomListener |
取消注册聊天室监听器 |
enter |
进入聊天室 |
V2NIMChatroomEnterParams.tagConfig |
聊天室标签相关配置 |
sendMessage |
发送聊天室消息 |
V2NIMSendChatroomMessageParams |
发送消息的配置参数 |
updateChatroomTags |
更新聊天室标签 |
API | 说明 |
---|---|
V2NIMChatroomClient.getChatroomService |
获取聊天室服务类 |
on("EventName") |
注册聊天室监听器 |
off("EventName") |
取消注册聊天室监听器 |
enter |
进入聊天室 |
V2NIMChatroomEnterParams.tagConfig |
聊天室标签相关配置 |
sendMessage |
发送聊天室消息 |
V2NIMSendChatroomMessageParams |
发送消息的配置参数 |
updateChatroomTags |
更新聊天室标签 |
API | 说明 |
---|---|
V2NIMChatroomClient.getChatroomService |
获取聊天室服务类 |
V2NIMChatroomService.addChatroomListener |
注册聊天室监听器 |
V2NIMChatroomService.removeChatroomListener |
取消注册聊天室监听器 |
enter |
进入聊天室 |
V2NIMChatroomEnterParams.tagConfig |
聊天室标签相关配置 |
sendMessage |
发送聊天室消息 |
V2NIMSendChatroomMessageParams |
发送消息的配置参数 |
updateChatroomTags |
更新聊天室标签 |