Managing friends
This document guides developers on how to use the RC Instant Messaging Web IMLib SDK to implement friend-related functions such as adding friends, deleting friends, viewing friend lists, and managing friends.
This feature is supported starting from version 5.12.0.
Enabling the Service
The user profile hosting service is enabled by default, and you can use this feature directly.
Friend Event Listening
The friend event listener is used to receive friend-related event notifications, including: adding, deleting, application status changes, clearing friends, and friend profile changes.
The data types returned by the listener are as follows:
- Adding a friend: [IFriendAdd].
- Deleting a friend: [IFriendDelete].
- Clearing friends:
numbertimestamp representing the time when friends were cleared. - Friend application status: [IFriendApplicationStatusChange].
- Multi-device synchronization of friend information changes: [IFriendInfoChangedSync].
// Add friend event listener
RongIMLib.addEventListener(RongIMLib.Events.FRIEND_ADDED, (data) => {
// data type is IFriendAdd
console.info('Friend added listener', data);
});
// Delete friend event listener
RongIMLib.addEventListener(RongIMLib.Events.FRIEND_DELETE, (data) => {
// data type is IFriendDelete
console.info('Friend deleted listener', data);
});
// Clear friends listener
RongIMLib.addEventListener(RongIMLib.Events.FRIEND_CLEARED, (data) => {
// data type is number, timestamp representing the time when friends were cleared
console.info('Clear all friends listener', data);
});
// Friend application listener
RongIMLib.addEventListener(RongIMLib.Events.FRIEND_APPLICATION_STATUS_CHANGED, (data) => {
// data type is IFriendApplicationStatusChange
console.info('Friend application listener', data);
});
// Multi-device synchronization of friend information changes listener
RongIMLib.addEventListener(RongIMLib.Events.FRIEND_INFO_CHANGED_SYNC, (data) => {
// data type is IFriendInfoChangedSync
console.info('[Multi-device Sync] Friend information listener', data);
});
Friend Online Status and Profile Change Listening
For friend online status and user profile changes, there is no need to actively subscribe using the subscribeEvent interface. Simply set up the subscription listener before the SDK establishes a connection.
The event type is distinguished in the listener callback via [SubscribeType]:
SubscribeType.FRIEND_ONLINE_STATUSindicates friend online status changesSubscribeType.FRIEND_PROFILE_CHANGEDindicates friend profile changes
// Friend online status and friend information synchronization completion
RongIMLib.addEventListener(RongIMLib.Events.SUBSCRIBED_USER_STATUS_CHANGE, (data) => {
// Friend online status change
if (data.subscribeType === RongIMLib.SubscribeType.FRIEND_ONLINE_STATUS) {
console.info('Friend online status change', data);
} else if (data.subscribeType === RongIMLib.SubscribeType.FRIEND_USER_PROFILE) {
// Friend user profile change
console.info('Friend user profile change', data);
}
});
Friend Operations
Adding Friends
Users can search for target users by username, user ID, phone number, etc., choose whether to include an application note, and submit a friend request by calling addFriend.
A single user can add up to 3000 friends.
Friend Addition Permission Description
The default user information permission for AppKey is Requires user consent to add friends.
The following table describes the combined effect of AppKey-level permissions and user-level permissions:
| AppKey Permission | User-Level Permission | Result |
|---|---|---|
| Invisible to all, visible to friends only, visible to all | Not set | Follows AppKey permission settings |
| Invisible to all, visible to friends only, visible to all | Set to (invisible to all, visible to all, visible to friends only) | Follows user permission settings |
Different Permission Process Descriptions
Scenario 1: Direct Addition Without Verification
- Both parties call setFriendListener to register friend event listeners.
- User B sets friend addition permission to: Anyone can add directly (see [FriendAddPermission])
- User A calls
addFriend, the interface returnsprocessCodeas 0, indicating they have directly become friends. Both parties receive theEvents.FRIEND_ADDEDevent.
Scenario 2: Verification Required
- Both parties call
setFriendListenerto register friend event listeners. - User B sets friend addition permission to: Requires verification (see [FriendAddPermission]).
- User A calls
addFriend, the interface returnsprocessCodeas25461, indicating pending verification. Both parties receive theEvents.FRIEND_APPLICATION_STATUS_CHANGEDevent. - User B receives the application via the listener and can call:
acceptFriendApplicationto agree, both parties receiveEvents.FRIEND_ADDEDrefuseFriendApplicationto refuse, both parties receiveEvents.FRIEND_APPLICATION_STATUS_CHANGEDwith statusREFUSED
Interface
RongIMLib.addFriend(userId, directionType, extra)
Parameter Description
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| userId | string | Yes | Target user ID, the user ID to be added as a friend. |
| directionType | [DirectionType] | Yes | Friend type |
| extra | string | No | Additional information, extra information when sending a friend request, with a maximum length of 128 characters. |
Example Code
const userId = 'UserId';
const directionType = DirectionType.BOTH
const extra = 'Hello, I would like to add you as a friend.';
const res = await RongIMLib.addFriend(userId, directionType, extra);
console.info('Friend addition request result:', res);
The friend addition request result includes code and processCode, where code represents the request operation status, and processCode is the business status code requiring subsequent processing.
Removing Friends
Call deleteFriends to batch remove friend relationships. Upon success, both parties receive the Events.FRIEND_DELETE event.
Interface
RongIMLib.deleteFriends(userIds, directionType);
Parameter Description
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| userIds | string[] | Yes | Target user ID array, the user IDs to remove friend relationships with, with a maximum of 100 users per batch. |
| directionType | [DirectionType] | Yes | Friend type |
Example Code
const userIds = ['UserId1', 'UserId2'];
const directionType = DirectionType.BOTH;
const res = await RongIMLib.deleteFriends(userIds, directionType);
console.info('Friend removal request result:', res);
Setting Friend Information
Call setFriendInfo to set a friend's remark name and extended information.
- The extended information key must be set via the developer console or API before it can be used; otherwise, the setting will fail. A maximum of 10 extended information keys can be set.
- After successfully modifying friend information, other terminals logged in by the same user will receive the multi-device synchronization listener for friend information changes
Events.FRIEND_INFO_CHANGED_SYNC.
Interface
RongIMLib.setFriendInfo(userId, remark)
Parameter Description
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| userId | string | Yes | Friend user ID |
| remark | string | No | Friend remark name, with a maximum of 64 characters. If not provided or empty, the remark name will be cleared. |
| extProfile | {[key: string]: string} | No | Extended information. Developers can add custom extended attributes based on business needs, with a default maximum of 10 extended information items. Custom attributes must be set via the developer console or API before they can be used; otherwise, the setting will fail. |
Example Code
const userId = 'UserId';
const remark = 'Best Friend';
RongIMLib.setFriendInfo(userId, remark);
### Check Friend Relationship \{#checkFriends}
Call [checkFriends](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#checkFriends) to verify friend relationships. Currently, only bidirectional friend checks are supported.
#### Interface
```javascript
RongIMLib.checkFriends(userId, directionType);
#### Parameter Description
| Parameter Name | Type | Required | Description |
|------------|----------- |---|----|
| userIds | string[] | Yes | List of user IDs to check friend relationships (max **20** users per request) |
| directionType | [DirectionType]| Yes | Type of friend relationship to check |
#### Example Code
```javascript
const userIds = ['UserId1', 'UserId2'];
const directionType = DirectionType.BOTH;
const res = await RongIMLib.checkFriends(userIds, directionType);
console.info('Friend relationship check result:', res);
### Set Friend Request Permission \{#setFriendAddPermission}
Call [setFriendAddPermission](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#setFriendAddPermission) to configure the current user's friend request permission. If not set, the default permission at AppKey level will apply.
#### Interface
```js
RongIMLib.setFriendAddPermission(permission)
#### Parameter Description
| Parameter Name | Type | Required | Description |
|------------|----------- |---|----|
| permission | [FriendAddPermission]| Yes | Friend request permission (refer to [FriendAddPermission]) |
#### Example Code
```javascript
const permission = FriendAddPermission.Free;
const res = await RongIMLib.setFriendAddPermission(permission);
console.info('Friend request permission setting result:', res);
### Get Friend Request Permission \{#getPermission}
Call [getFriendAddPermission](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#getFriendAddPermission) to retrieve the current user's friend request permission.
#### Interface
```javascript
RongIMLib.getFriendAddPermission();
#### Parameter Description
None
#### Example Code
```javascript
const res = await RongIMLib.getFriendAddPermission();
console.info('Friend request permission retrieval result:', res);
## Friend Requests
### Accept Friend Request \{#agree}
After receiving a friend request, users can establish a friend relationship by accepting it.
Call [acceptFriendApplication](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#acceptFriendApplication) to accept a friend request. Both parties will receive the `Events.FRIEND_ADDED` callback indicating successful friend addition.
The request status in the friend application list will change to "Accepted".
#### Interface
```javascript
RongIMLib.acceptFriendApplication(userId)
#### Parameter Description
| Parameter Name | Type | Required | Description |
|------------|----------- |---|----|
| userId | string | Yes | Target user ID |
#### Example Code
```javascript
const userId = 'UserId';
const res = await RongIMLib.acceptFriendApplication(userId);
console.info('Friend request acceptance result:', res);
### Reject Friend Request \{#refuse}
After receiving a friend request, users can call [refuseFriendApplication](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#refuseFriendApplication) to reject it and send a rejection system message. The request status will change to "Rejected" in the application list, and both parties will receive a status change callback.
Upon successful rejection, both parties will receive the `Events.FRIEND_APPLICATION_STATUS_CHANGED` callback with a "Rejected" status.
#### Interface
```javascript
RongIMLib.refuseFriendApplication(userId, reason);
#### Parameter Description
| Parameter Name | Type | Required | Description |
|----|----- |---|----|
| userId | string | Yes | User ID to reject |
| reason | string | No | Rejection reason (max 128 characters) |
#### Example Code
```javascript
const userId = 'UserId';
const res = await RongIMLib.refuseFriendApplication(userId, reason);
console.info('Friend request rejection result:', res);
### Paginated Friend Request List \{#getFriendRequestList}
Call [getFriendApplications](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#getFriendApplications) to view all received friend requests and sent friend applications.
:::tip
- Friend requests expire after 7 days. RC servers store request data for up to 7 days; expired requests must be resent.
- This interface doesn't return total request count.
- Electron supports conditional filtering by request type (types) and status (status), which is unavailable on Web.
:::
#### Interface
```js
RongIMLib.getFriendApplications(option, types, status)
#### Parameter Description
| Parameter Name | Type | Required | Description |
|----|------------------- |---|----|
| option | [IPagingQueryOption] | No | Pagination parameters (default 50 items, max 100) |
| types | [FriendApplicationType][] | No | Electron only: Request types (1: Sent requests, 2: Received requests) |
| status | [FriendApplicationStatus][] | No | Electron only: Request status |
#### Example Code
```javascript
// Invalid on Web
const types = [FriendApplicationType.SENT, FriendApplicationType.RECEIVED];
// Invalid on Web
const status = [FriendApplicationStatus.ACCEPTED];
const option = {
count: 50,
pageToken: '',
order: false,
};
const res = await RongIMLib.getFriendApplications(option, types, status);
console.info('Friend request list:', res);
## Friend List Management
### Get Friend List \{#getFriends}
Call [getFriends](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#getFriends) to retrieve the current user's friend list.
#### Interface
```javascript
RongIMLib.getFriends(directionType, option)
#### Parameter Description
:::tip
On Web platform, omitting pageToken defaults to first page. For pagination, use the pageToken returned in previous results.
:::
| Parameter Name | Type | Required | Description |
|------------|----------- |---|----|
| directionType | [QueryFriendsDirectionType] | Yes | Friend relationship type |
| option | [IPagingQueryOption] | No | Web only: Pagination parameters (default 50 items, max 100). Electron retrieves full list - implement pagination logic at business layer if needed. |
#### Example Code
```javascript
const directionType = QueryFriendsDirectionType.BOTH;
const option = {
count: 50,
pageToken: '',
order: false,
};
const friendsList = await RongIMLib.getFriends(directionType, option);
console.info('Friend list:', friendsList);
### Get Friend Information by User ID \{#getFriendInfoByUserId}
Call [getFriendsInfo](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#getFriendsInfo) to retrieve friend information.
#### Interface
```javascript
RongIMLib.getFriendsInfo(userIds)
#### Parameter Description
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| userIds | `string[]` | Yes | List of user IDs, with a maximum of 100 friend information retrievable at once. |
#### Example Code
```javascript
const userIds = ['user1', 'user2', 'user3'];
const friendsInfo = await RongIMLib.getFriendsInfo(userIds);
console.info('Friend information list:', friendsInfo);
### Search Friend Information by Nickname \{#searchFriendInfo}
Call [searchFriendsInfo](https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/modules.html#searchFriendsInfo) to search for friend information.
:::warning
- This interface is only supported on the Electron platform.
- The search prioritizes the friend's remark name `remark` first, then the friend's name `name`. A match in either field will return the search result.
:::
#### Interface
```javascript
RongIMLib.searchFriendsInfo(name)
#### Parameter Description
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| name | `string` | Yes | Nickname keyword, cannot be empty. Maximum length is 64 characters. Supports fuzzy search but does not support pure whitespace searches. |
#### Example Code
```javascript
const name = 'userName';
const searchResults = await RongIMLib.searchFriendsInfo(name);
console.info('Search friend list results:', searchResults);
<!-- api links -->
[SubscribeType]: https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/enums/SubscribeType.html
[DirectionType]:https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/enums/DirectionType.html
[FriendAddPermission]:https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/enums/FriendAddPermission.html
[IPagingQueryOption]:https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/interfaces/IPagingQueryOption.html
[FriendApplicationType]:https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/enums/FriendApplicationType.html
[FriendApplicationStatus]:https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/enums/FriendApplicationStatus.html
[QueryFriendsDirectionType]:https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/enums/QueryFriendsDirectionType.html
[IFriendAdd]: https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/interfaces/IFriendAdd.html
[IFriendDelete]: https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/interfaces/IFriendDelete.html
[IFriendApplicationStatusChange]: https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/interfaces/IFriendApplicationStatusChange.html
[IFriendInfoChangedSync]: https://doc.rongcloud.cn/apidoc/im-web/latest/zh_CN/interfaces/IFriendInfoChangedSync.html