new SDK(options)
Basic concepts of IM SDK:
Term | Description |
---|---|
Message | Message indicates the content to be sent and carries multiple attributes which specify whether you are the sender, the sender account, the message generation time, and so on. |
Conversation | Two types of Conversation are available: |
Profile | Profile describes the basic information of a user, including the nickname, gender, personal signature, and profile photo address. |
Friend | Friend describes the basic information of a friend, including the remarks and friend list. |
FriendApplication | FriendApplication describes the basic information of a friend request, including the source and remarks. |
FriendGroup | FriendGroup describes the basic information of a friend list, including the friend list name and members. |
Group | Group indicates a communication system for group chatting, including Work, Public, Meeting, and AVChatRoom. |
GroupMember (group member) | GroupMember indicates the basic information of each group member, such as the ID, nickname, role, and the time of joining the group. |
Group notification | A group notification is generated when an event such as group member addition or deletion occurs. The access side can configure whether to display group notifications to group members. For more information about group notification types, see Message.GroupTipPayload. |
Group system message | For example, when a user requests to join a group, the group admin receives a system message. After the admin accepts or rejects the request, the IM SDK returns the result to the access side, which then displays the result to the user. For more information about group system message types, see Message.GroupSystemNoticePayload. |
Message display on screen | The sent messages, including text segments and images, are displayed on the computer or phone screen. |
Supported platforms:
- IM SDK supports Internet Explorer 9+, Chrome, WeChat, Mobile QQ, QQ Browser, Firefox, Opera, and Safari.
SDK integration (web project)
Integration Method | Example |
---|---|
Integration via npm | // IM Web SDK npm install tim-js-sdk --save // Upload plugin required to send messages such as image and file messages npm install tim-upload-plugin --save |
Integrating via script | Import the SDK to your project by using the script tag and initialize the SDK. Download link: IM Web SDK |
SDK integration (WeChat Mini Program project)
Integration Method | Example |
---|---|
Integration via npm | // IM Mini Program SDK npm install tim-wx-sdk --save // Upload plugin required to send messages such as image and file messages npm install tim-upload-plugin --save |
Example
import TIM from 'tim-js-sdk';
// import TIM from 'tim-wx-sdk'; // For WeChat Mini Program, uncomment this line and comment out the following: import TIM from 'tim-js-sdk';
import TIMUploadPlugin from 'tim-upload-plugin'; // Before using the API, upgrade your IM SDK to v2.9.2 or later.
// Create an SDK instance. The TIM.create() method returns the same instance for the same SDKAppID.
let options = {
SDKAppID: 0 // Replace 0 with the SDKAppID of your IM app when connecting.
};
let tim = TIM.create(options); // The SDK instance is usually represented by tim.
// Set the SDK log output level. For details on each level, see **setLogLevel API description**.
tim.setLogLevel(0); // Common level. You are advised to use this level during access as it covers more logs.
// tim.setLogLevel(1); // Release level, at which the SDK outputs important information. You are advised to use this log level in a production environment.
// Register the Tencent Cloud IM upload plugin. Before sending messages, such as image, audio, video, and file messages, the IM SDK needs to use the upload plugin to upload files to Tencent COS.
tim.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
// Listened-for events, for example:
tim.on(TIM.EVENT.SDK_READY, function(event) {
// A notification is received, indicating that the offline message and conversation lists are synchronized successfully. The access side can call APIs that require authentication, such as sendMessage.
// event.name - TIM.EVENT.SDK_READY
});
tim.on(TIM.EVENT.MESSAGE_RECEIVED, function(event) {
// A newly pushed one-to-one message, group message, group tip, or group system notification is received. You can traverse event.data to obtain the message list and render it to the UI.
// event.name - TIM.EVENT.MESSAGE_RECEIVED
// event.data - An array that stores Message objects - [Message]
});
tim.on(TIM.EVENT.MESSAGE_MODIFIED, function(event)) {
// This event is triggered when the SDK receives a notification for message modifications by a third-party callback. When this event occurs, the message sender can traverse event.data to obtain the message list and update the content of the message with the same ID on the UI. (Supported from v2.12.1)
// event.name - TIM.EVENT.MESSAGE_MODIFIED
// event.data - An array that stores the Message objects modified by a third-party callback - [Message]
});
tim.on(TIM.EVENT.MESSAGE_REVOKED, function(event) {
// A message recall notification is received. Before using this event, upgrade your SDK to v2.4.0 or later.
// event.name - TIM.EVENT.MESSAGE_REVOKED
// event.data - An array that stores Message objects - [Message] - The isRevoked value of each Message object is true.
});
tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, function(event) {
// The SDK receives a notification (read receipt) indicating that the peer end has read the message. Before using this event, you need to upgrade your SDK to V2.7.0 or later. This event is supported only for one-to-one conversations.
// event.name - TIM.EVENT.MESSAGE_READ_BY_PEER
// event.data - event.data - An array that stores the Message objects - [Message] - The isPeerRead value of each Message object is true.
});
tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, function(event) {
// A conversation list update notification is received. You can traverse event.data to obtain the conversation list and render it to the UI.
// event.name - TIM.EVENT.CONVERSATION_LIST_UPDATED
// event.data - An array that stores the Conversation objects - [Conversation]
});
tim.on(TIM.EVENT.GROUP_LIST_UPDATED, function(event) {
// A group list update notification is received. You can traverse event.data to obtain the group list and render it to the UI.
// event.name - TIM.EVENT.GROUP_LIST_UPDATED
// event.data - An array that stores the Group objects - [Group]
});
tim.on(TIM.EVENT.PROFILE_UPDATED, function(event) {
// A notification is received, indicating that your own profile or your friend's profile is updated.
// event.name - TIM.EVENT.PROFILE_UPDATED
// event.data - An array that stores the Profile objects - [Profile]
});
tim.on(TIM.EVENT.BLACKLIST_UPDATED, function(event) {
// A blocklist update notification is received.
// event.name - TIM.EVENT.BLACKLIST_UPDATED
// event.data - An array that stores userIDs - [userID]
});
tim.on(TIM.EVENT.ERROR, function(event) {
// An SDK error notification is received. The error code and error message can be obtained from this notification.
// event.name - TIM.EVENT.ERROR
// event.data.code - Error code
// event.data.message - Error message
});
tim.on(TIM.EVENT.SDK_NOT_READY, function(event) {
// An SDK not ready notification is received. At this time, the SDK cannot function normally.
// event.name - TIM.EVENT.SDK_NOT_READY
});
tim.on(TIM.EVENT.KICKED_OUT, function(event) {
// A kicked offline notification is received.
// event.name - TIM.EVENT.KICKED_OUT
// event.data.type - Reason for being kicked offline, such as:
// - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT: kicked offline due to multi-instance login.
// - TIM.TYPES.KICKED_OUT_MULT_DEVICE: kicked offline due to multi-device login.
// - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED: kicked offline due to UserSig expiration (supported from v2.4.0).
});
tim.on(TIM.EVENT.NET_STATE_CHANGE, function(event) {
// The network status changes (supported from v2.5.0).
// event.name - TIM.EVENT.NET_STATE_CHANGE
// event.data.state indicates the current network status. The enumerated values are described as follows:
// - TIM.TYPES.NET_STATE_CONNECTED: already connected to the network
// - TIM.TYPES.NET_STATE_CONNECTING: connecting. This often occurs when the SDK must reconnect due to network jitter. The message "The current network is unstable" or "Connecting..." can be displayed at the access side based on this status.
// - TIM.TYPES.NET_STATE_DISCONNECTED: disconnected. The message "The current network is unavailable" can be displayed at the access side based on this status. The SDK will continue to try to reconnect. If the user network recovers, the SDK will automatically synchronize messages.
});
tim.on(TIM.EVENT.FRIEND_LIST_UPDATED, function(event) {
// A friend list update notification is received. (Supported from v2.13.0)
// event.name - TIM.EVENT.FRIEND_LIST_UPDATED
// event.data - An array that stores the Friend objects - [Friend]
});
tim.on(TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED, function(event) {
// A friend request list update notification is received. (Supported from v2.13.0)
// event.name - TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED
// friendApplicationList - Friend request list - [FriendApplication]
// unreadCount - Unread friend request count
// const { friendApplicationList, unreadCount } = event.data;
// Friend requests received by me (friend requests that are sent to you by others)
// const applicationSentToMe = friendApplicationList.filter((friendApplication) => friendApplication.type === TIM.TYPES.SNS_APPLICATION_SENT_TO_ME);
// Friend requests sent by me (friend requests that you send to others)
// const applicationSentByMe = friendApplicationList.filter((friendApplication) => friendApplication.type === TIM.TYPES.SNS_APPLICATION_SENT_BY_ME);
});
tim.on(TIM.EVENT.FRIEND_GROUP_LIST_UPDATED, function(event) {
// Received a notification on the update of the list of friend lists. (Supported from v2.13.0)
// event.name - TIM.EVENT.FRIEND_GROUP_LIST_UPDATED
// event.data - An array that stores the FriendGroup objects - [FriendGroup]
});
// Start to log in to the SDK.
tim.login({userID: 'your userID', userSig: 'your userSig'});
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Application configuration Properties
|
Methods
login(options) → {Promise}
Log in to the IM SDK using userID and userSig. The login process contains several steps that are executed asynchronously, and the returned Promise object is used to process login success or failure.
Note 1: After successful login, to call APIs that require authentication, such as sendMessage, you must wait until the SDK enters the ready state (you can obtain the status of the SDK by listening to the TIM.EVENT.SDK_READY event).
Note 2: By default, multi-instance login is not supported. If you use an account that has been logged in on another page to log in on the current page, the account may be forcibly logged out on the other page, which will trigger theTIM.EVENT.KICKED_OUT
event. You can proceed accordingly after detecting the event through listening.
To support multi-instance login (allowing the use of the same account to log in concurrently on multiple pages), log in to the IM console, locate the corresponding SDKAppID, and go to App Configuration > Feature Configuration > Online Web Instances to configure the number of instances. The configuration will take effect within 50 minutes.
Example
let promise = tim.login({userID: 'your userID', userSig: 'your userSig'});
promise.then(function(imResponse) {
console.log(imResponse.data); // Login successful
if (imResponse.data.repeatLogin === true) {
// Indicates that the account has logged in and that the current login will be a repeated login. This feature is supported from v2.5.1.
console.log(imResponse.data.errorInfo);
}
}).catch(function(imError) {
console.warn('login error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Login configuration Properties
|
Returns:
- Type
- Promise
logout() → {Promise}
This API is used to log out of the IM console. It is usually called when you switch between accounts. This API clears the login status of the current account and all the data in the memory.
Notes:
- When calling this API, the instance publishes the
SDK_NOT_READY
event. In this case, the instance is automatically logged out and cannot receive or send messages. - Assume that the value of the Online Web Instances configured in the IM console is greater than 1, and the same account has been used to log in to instances
a1
anda2
(including a Mini Program instance). Aftera1.logout()
is executed,a1
is automatically logged out and cannot receive or send messages, whereasa2
is not affected. - Assume that the Online Web Instances is set to 2, and your account has been used to log in to instances
a1
anda2
. When you use this account to log in to instancea3
, eithera1
ora2
will be forcibly logged out. In most cases, the instance that first entered the login state is forcibly logged out. This is called kicked offline due to multi-instance login. Ifa1
is forcibly logged out, a logout process is executed withina1
and theKICKED_OUT
event is triggered. The access side can listen for this event and redirect it to the login page when the event is triggered. At this time,a1
is forcibly logged out, whereas instancesa2
anda3
can continue to run properly.
Example
let promise = tim.logout();
promise.then(function(imResponse) {
console.log(imResponse.data); // Logout successful
}).catch(function(imError) {
console.warn('logout error:', imError);
});
Returns:
- Type
- Promise
destroy() → {Promise}
Terminate the SDK instance. The SDK will log out, disconnect the WebSocket persistent connection, and then release resources.
Example
tim.destroy();
Returns:
- Type
- Promise
on(eventName, handler, contextopt)
Listen for events.
Note: Please call the API to listen for events before calling the login API to avoid missing events distributed by the SDK.
Example
let onMessageReceived = function(event) {
// A newly pushed one-to-one message, group message, group tip, or group system notification is received. You can traverse event.data to obtain the message list and render it to the UI.
// event.name - TIM.EVENT.MESSAGE_RECEIVED
// event.data - An array that stores Message objects - [Message]
};
tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
eventName |
String |
Event name. All event names are stored in the |
|
handler |
function |
Event processing method. When an event is triggered, this handler is called to process the event. |
|
context |
* |
<optional> |
Context in which the handler is expected to execute. |
off(eventName, handler, contextopt, onceopt)
Cancel event listening.
Example
let onMessageReceived = function(event) {
// A newly pushed one-to-one message, group message, group tip, or group system notification is received. You can traverse event.data to obtain the message list and render it to the UI.
// event.name - TIM.EVENT.MESSAGE_RECEIVED
// event.data - An array that stores Message objects - [Message]
};
tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
eventName |
String |
Event name. All event names are stored in the |
|
handler |
function |
Event processing method. When an event is triggered, this handler is called to process the event. |
|
context |
* |
<optional> |
Context in which the handler is expected to execute. |
once |
Boolean |
<optional> |
Whether to unbind only once |
registerPlugin(options)
Register a plugin.
Before sending messages, such as image, audio, video, and file messages, the IM SDK needs to use the upload plugin to upload files to Tencent COS.
Example
// Before using tim-js-sdk or tim-wx-sdk, please upgrade your SDK to v2.9.2 or later.
// To use tim-upload-plugin in Mini Programs, you need to configure the valid domain name https://cos.ap-shanghai.myqcloud.com for uploadFile and downloadFile on the Mini Program backend.
tim.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Plugin configuration Properties
|
setLogLevel(level)
Set the log level. Logs below this level will not be printed.
Example
tim.setLogLevel(0);
Parameters:
Name | Type | Description |
---|---|---|
level |
Number |
Log level
|
createTextMessage(options) → {Message}
Create a text message. This API returns a message instance. If you need to send a text message, call the sendMessage API to send this message instance.
Example
// Send a text message. The text message sending process in web apps is the same as that in Mini Programs.
// 1. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createTextMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
text: 'Hello world!'
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createTextAtMessage(options) → {Message}
Create a text message with the @ notification feature. This API returns a message instance. If you need to send a text message, call the sendMessage API to send this message instance.
Note 1: Before using this API, upgrade your SDK to v2.9.0 or later.
Note 2: This API applies only to group chats.
Example
// Send a text message. The text message sending process in web apps is the same as that in Mini Programs.
// 1. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createTextAtMessage({
to: 'group1',
conversationType: TIM.TYPES.CONV_GROUP,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
text: '@denny @lucy @all Dinner tonight. Please reply 1 if you receive this message',
atUserList: ['denny', 'lucy', TIM.TYPES.MSG_AT_ALL] // 'denny' and 'lucy' are userIDs, not nicknames
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createImageMessage(options) → {Message}
Create an image message. This API returns a message instance. If you need to send an image message, call the sendMessage API to send this message instance.
Note 1: File objects are supported from v2.3.1. If you need to use file objects, upgrade your SDK to v2.3.1 or later.
Note 2: Sending file messages such as image messages via uni-app is supported from v2.11.2. If you need to use the feature, upgrade your SDK to v2.11.2 or later and upgrade tim-upload-plugin to v1.0.2 or later.
Examples
// Example 1 for sending an image message in a web app - Passing in a DOM node
// 1. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createImageMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
file: document.getElementById('imagePicker'),
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
// Example 2 for sending an image message in a web app - Passing in a file object
// Add a message input box with the ID set to "testPasteInput", for example, <input type="text" id="testPasteInput" placeholder="Take a screenshot and paste it in the input box" size="30" />
document.getElementById('testPasteInput').addEventListener('paste', function(e) {
let clipboardData = e.clipboardData;
let file;
let fileCopy;
if (clipboardData && clipboardData.files && clipboardData.files.length > 0) {
file = clipboardData.files[0];
// After the image message is successfully sent, the content pointed by "file" may be cleared by the browser. If you have extra rendering requirements, copy the data in advance.
fileCopy = file.slice();
}
if (typeof file === 'undefined') {
console.warn('file is undefined. Check compatibility of the code or browser.');
return;
}
// 1. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createImageMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: {
file: file
},
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
});
// Send an image message in a Mini Program.
// 1. Select an image.
wx.chooseImage({
sourceType: ['album'], // Select an image from the album.
count: 1, // You can only select one image. The SDK does not support sending multiple images at a time.
success: function (res) {
// 2. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createImageMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: { file: res },
onProgress: function(event) { console.log('file uploading:', event) }
});
// 3. Send the image.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
}
})
// Send an image message via uni-app. Before using this API, upgrade your SDK to v2.11.2 or later and upgrade tim-upload-plugin to v1.0.2 or later.
// 1. Select an image.
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // You can specify whether to use the original or compressed image. Both are included by default.
sourceType: ['album'], // Select an image from the album.
success: function(res) {
let message = tim.createImageMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: { file: res },
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
}
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createAudioMessage(options) → {Message}
Create an audio message. This API returns a message instance. If you need to send an audio message, call the sendMessage API. Currently, createAudioMessage is applicable only to WeChat Mini Programs.
Example
//Example: Record an audio message by using the official WeChat RecorderManager. For more information, see https://developers.weixin.qq.com/minigame/dev/api/media/recorder/RecorderManager.start.html.
// 1. Get the globally unique RecorderManager.
const recorderManager = wx.getRecorderManager();
// Recording parameters
const recordOptions = {
duration: 60000, // Length of the audio message, in ms. Max. value: 600000 ms (10 minutes).
sampleRate: 44100, // Sample rate
numberOfChannels: 1, // Number of recording channels
encodeBitRate: 192000, // Encoding bitrate
format: 'aac' // Format of the audio message. This audio format is compatible with all IM platforms (Android, iOS, WeChat Mini Programs, and web apps).
};
// 2.1 Listen for recording errors.
recorderManager.onError(function(errMsg) {
console.warn('recorder error:', errMsg);
});
// 2.2 Listen for recording end event. After recording ends, call createAudioMessage to create an audio message instance.
recorderManager.onStop(function(res) {
console.log('recorder stop', res);
// 4. Create a message instance. The returned instance can be displayed on the screen.
const message = tim.createAudioMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
file: res
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
});
// 5. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
});
3. Start recording.
recorderManager.start(recordOptions);
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createVideoMessage(options) → {Message}
Create a video message. This API returns a message instance. If you need to send a video message, call the sendMessage API to send this message instance.
Note 1: Before using this API, upgrade your SDK to v2.2.0 or later.
Note 2: createVideoMessage is applicable to WeChat Mini Programs, and can be used in web apps if the SDK version is v2.6.0 or later.
Note 3: You can use WeChat Mini Programs to record a video message, or select a video from your album. However, Mini Programs do not return a thumbnail of the video. To improve user experience, the SDK creates a thumbnail for each video message by default. If you do not wish to display the default thumbnail, skip the information related to the thumbnail when rendering.
Note 4: For video messages that require interconnection across various platforms, upgrade to the latest TUIKit or SDK on your mobile client.
Note 5: Sending file messages such as video messages via uni-app is supported from v2.11.2. If you need to use the feature, upgrade your SDK to v2.11.2 or later and upgrade tim-upload-plugin to v1.0.2 or later.
Examples
// Example of sending a video message in a Mini Program
// 1. Call the Mini Program API to select a video. For more information, see https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseVideo.html.
wx.chooseVideo({
sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera. Both are included by default.
maxDuration: 60, // Maximum duration, which is 60s
camera: 'back', // Rear camera
success (res) {
// 2. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createVideoMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
file: res
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
// Starting from v2.12.2, video upload progress callback is supported on mini programs.
onProgress: function(event) { console.log('file uploading:', event) }
})
// 3. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
}
})
// Example of sending a video message in a web app (supported from v2.6.0):
// 1. Obtain the video file, and pass in the DOM node.
// 2. Create a message instance.
const message = tim.createVideoMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: {
file: document.getElementById('videoPicker') // Alternatively, use event.target
},
onProgress: function(event) { console.log('file uploading:', event) }
});
// 3. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
// Send a video message via uni-app. Before using this API, upgrade your SDK to v2.11.2 or later and upgrade tim-upload-plugin to v1.0.2 or later.
// 1. Select a video.
uni.chooseVideo({
count: 1,
sourceType: ['camera', 'album'], // You can specify whether the source is an album or a camera. Both are included by default.
maxDuration: 60, // Maximum duration, which is 60s
camera: 'back', // Rear camera
success: function(res) {
let message = tim.createVideoMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: { file: res },
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
}
})
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createCustomMessage(options) → {Message}
Create a custom message. This API returns a message instance. If you need to send a custom message, call the sendMessage API to send this message instance. If the SDK does not provide the capability you need, use custom messages to customize features, for example, the dice rolling feature.
Example
// Example: use custom messages to implement dice rolling
// 1. Define the random function.
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// 2. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createCustomMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_HIGH,
payload: {
data: 'dice', // Identify that this message is a dice message.
description: String(random(1,6)), // Get the outcome.
extension: ''
}
});
// 3. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createFaceMessage(options) → {Message}
Create an emoji message. This API returns a message instance. If you need to send an emoji message, call the sendMessage API to send this message instance.
Note: Before using this API, upgrade your SDK to v2.3.1 or later.
Example
// Send an emoji message. The emoji message sending process in web apps is the same as that in Mini Programs.
// 1. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createFaceMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
index: 1, // Number. Emoji index, which is customized by the user.
data: 'tt00' // String. Additional data.
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createFileMessage(options) → {Message}
Create a file message. This API returns a message instance. If you need to send a file message, call the sendMessage API to send this message instance.
Note 1: File objects are supported from v2.3.1. If you need to use file objects, upgrade your SDK to v2.3.1 or later.
Note 2: Since v2.4.0, the maximum size of a file that can be uploaded is 100 MB.
Note 3: WeChat Mini Programs currently do not support selection of files. Therefore, this API is not applicable to WeChat Mini Programs.
Note 4: Sending file messages via uni-app is supported from v2.11.2. If you need to use the feature, upgrade your SDK to v2.11.2 or later and upgrade tim-upload-plugin to v1.0.2 or later.
Examples
// Example 1 for sending a file message in a web app - Passing in a DOM node
// 1. Create a file message instance. The returned instance can be displayed on the screen.
let message = tim.createFileMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats (supported from v2.4.2). If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
file: document.getElementById('filePicker'),
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
// Example 2 for sending a file message in a web app - Passing in a file object
// Add a message input box with the ID set to "testPasteInput", for example, <input type="text" id="testPasteInput" placeholder="Take a screenshot and paste it in the input box" size="30" />
document.getElementById('testPasteInput').addEventListener('paste', function(e) {
let clipboardData = e.clipboardData;
let file;
let fileCopy;
if (clipboardData && clipboardData.files && clipboardData.files.length > 0) {
file = clipboardData.files[0];
// After the image message is successfully sent, the content pointed by "file" may be cleared by the browser. If you have extra rendering requirements, copy the data in advance.
fileCopy = file.slice();
}
if (typeof file === 'undefined') {
console.warn('file is undefined. Check compatibility of the code or browser.');
return;
}
// 1. Create a message instance. The returned instance can be displayed on the screen.
let message = tim.createFileMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: {
file: file
},
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
});
// Send a file message via uni-app. Before using this API, upgrade your SDK to v2.11.2 or later and upgrade tim-upload-plugin to v1.0.2 or later.
// 1. Select a file.
uni.chooseFile({
count: 1,
extension:['.zip','.doc'],
success: function(res) {
let message = tim.createFileMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: { file: res },
onProgress: function(event) { console.log('file uploading:', event) }
});
// 2. Send the message.
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
}
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
createMergerMessage(options) → {Message}
Create a combined message. This API returns a message instance. If you need to send a combined message, call the sendMessage API to send this message instance.
Note 1: Before using this API, you need to upgrade your SDK to v2.10.1 or later.
Note 2: This API does not support combining messages that failed to be sent. If the message list contains a message that failed to be sent, the API reports an error.
Example
// 1. Forward group messages to a C2C conversation.
// message1, message2, and message3 are group messages.
let mergerMessage = tim.createMergerMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
payload: {
messageList: [message1, message2, message3],
title: 'Chat Records of the Talent Center in the Greater Bay Area',
abstractList: ['allen: 666', 'iris: [Image]', 'linda: [File]'],
compatibleText: 'Please upgrade your IM SDK to v2.10.1 or later to view this message.'
},
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
});
// 2. Send the message.
let promise = tim.sendMessage(mergerMessage);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
downloadMergerMessage(message) → {Promise}
Download a combined message. If the combined message sent by the sender is large in size, the SDK will store it on the cloud, and the message recipient needs to download it from the cloud to the local host before viewing the message.
Note 1: Before using this API, you need to upgrade your SDK to v2.10.1 or later.
Example
// If downloadKey exists, the combined message received is stored on the cloud, and you need to download it first.
if (message.type === TIM.TYPES.MSG_MERGER && message.payload.downloadKey !== '') {
let promise = tim.downloadMergerMessage(message);
promise.then(function(imResponse) {
// After the download is successful, the SDK updates information such as message.payload.messageList.
console.log(imResponse.data);
}).catch(function(imError) {
// Download failed
console.warn('downloadMergerMessage error:', imError);
});
}
Parameters:
Name | Type | Description |
---|---|---|
message |
Message |
Message instance |
Returns:
- Type
- Promise
createForwardMessage(options) → {Message}
Create a forward message. This API returns a message instance. If you need to send a forward message, call the sendMessage API to send this message instance.
Note 1: Before using this API, you need to upgrade your SDK to v2.10.1 or later.
Note 2: Messages can be forwarded individually or one by one.
Example
let forwardMessage = tim.createForwardMessage({
to: 'user1',
conversationType: TIM.TYPES.CONV_C2C,
// Message priority, applicable to group chats. If messages in a group exceed the frequency limit, the backend delivers high-priority messages first. For more information, see https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6.
// Enumerated values supported: TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL (default), TIM.TYPES.MSG_PRIORITY_LOW, and TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: message, // Message instances, including messages received and sent by yourself
// Message custom data (saved in the cloud, will be sent to the peer end, and can still be pulled after the app is uninstalled and reinstalled; supported from v2.10.2)
// cloudCustomData: 'your cloud custom data'
});
// 2. Send the message.
let promise = tim.sendMessage(forwardMessage);
promise.then(function(imResponse) {
// The message is sent successfully.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be sent.
console.warn('sendMessage error:', imError);
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
Message instance
- Type
- Message
sendMessage(message, optionsopt) → {Promise}
Send a message. Before sending a message, call any of the following APIs to create a message instance and then use this API to send the message instance.
- Creating a text message
- Creating an image message
- Creating an audio message
- Creating a video message
- Creating a custom message
- Creating an emoji message
- Creating a file message
- Creating a forward message
- Creating a combined message
Note 1: The SDK must be in the ready state to call this API to send message instances successfully. The SDK status can be obtained by listening for the following events:
- TIM.EVENT.SDK_READY: triggered when the SDK is in the ready state
- TIM.EVENT.SDK_NOT_READY: triggered when the SDK is in the not ready state
Note 2: To receive a newly pushed one-to-one message, group message, group notification, or group system message, you need to listen for the TIM.EVENT.MESSAGE_RECEIVED event.
Note 3: Messages sent by this API do not trigger the TIM.EVENT.MESSAGE_RECEIVED event. Messages sent by the same account from other clients (or through the RESTful API) trigger the TIM.EVENT.MESSAGE_RECEIVED event. Note 4: Offline push is applicable only to Android or iOS terminals, and is not supported by web apps or WeChat Mini Programs.
Examples
// If the recipient is offline, the message will be stored in the roaming server and pushed offline on the precondition that the recipient's app switches to the background or the process is killed. The default title and content of offline push are kept.
// For more information on offline push, see https://cloud.tencent.com/document/product/269/3604.
tim.sendMessage(message);
// The message sending option is supported from v2.6.4.
tim.sendMessage(message, {
onlineUserOnly: true // If the recipient is offline, the message is neither stored in the roaming server nor pushed offline.
});
// The message sending option is supported from v2.6.4.
tim.sendMessage(message, {
offlinePushInfo: {
disablePush: true // If the recipient is offline, the message is stored in the roaming server, but is not pushed offline.
}
});
// The message sending option is supported from v2.6.4.
tim.sendMessage(message, {
// If the recipient is offline, the message will be stored in the roaming server and pushed offline on the precondition that the recipient's app switches to the backend or the process is killed. The title and content of offline push can be customized at the access side.
offlinePushInfo: {
title: '', // Offline push title
description: '', // Offline push content
androidOPPOChannelID: '' // Offline push channel ID for OPPO phones that run Android 8.0 or later
}
});
Parameters:
Name | Type | Attributes | Description | |||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
message |
Message |
Message instance |
||||||||||||||||||||||||||||||||||||||||||||
options |
Object |
<optional> |
Message sending option Properties
|
Returns:
- Type
- Promise
revokeMessage(message) → {Promise}
Recall a one-to-one message or a group message. If the recall is successful, the value of isRevoked for the recalled message is set to true.
Note 1: Before using this API, upgrade your SDK to v2.4.0 or later.
Note 2: The time limit for message recall is 2 minutes by default. You can log in to IM console to change this limit.
Note 3: You can call the getMessageList API to pull recalled messages from the one-to-one or group message roaming list. Recalled messages are displayed based on isRevoked of the message object. For example, "The peer party has recalled a message" can be displayed if a message is recalled during a one-to-one conversation, or "XXX has recalled a message" can be displayed if a message is recalled during a group conversation.
Note 4: You also use the RESTful API to recall one-to-one messages or recall group messages.
Examples
// Proactively recall a message.
let promise = tim.revokeMessage(message);
promise.then(function(imResponse) {
// The message is successfully recalled.
}).catch(function(imError) {
// The message fails to be recalled.
console.warn('revokeMessage error:', imError);
});
// The message recall notification is received.
tim.on(TIM.EVENT.MESSAGE_REVOKED, function(event) {
// event.name - TIM.EVENT.MESSAGE_REVOKED
// event.data - An array that stores Message objects - [Message] - The isRevoked value of each Message object is true.
});
// Obtain a message list which contains recalled messages.
let promise = tim.getMessageList({conversationID: 'C2Ctest', count: 15});
promise.then(function(imResponse) {
const messageList = imResponse.data.messageList; // Message list
messageList.forEach(function(message) {
if (message.isRevoked) {
// Handle the recalled messages.
} else {
// Handle common messages.
}
});
});
Parameters:
Name | Type | Description |
---|---|---|
message |
Message |
Message instance |
Returns:
- Type
- Promise
resendMessage(message) → {Promise}
Resend a message. When a message fails to be sent, call this API to resend it.
Example
// Resend a message.
let promise = tim.resendMessage(message); // Pass in the message instance that needs to be resent.
promise.then(function(imResponse) {
// The message is successfully resent.
console.log(imResponse);
}).catch(function(imError) {
// The message fails to be resent.
console.warn('resendMessage error:', imError);
});
Parameters:
Name | Type | Description |
---|---|---|
message |
Message |
Message instance to be resent |
Returns:
- Type
- Promise
deleteMessage(messageList) → {Promise}
Delete messages. After successful deletion, the isDeleted property value of a deleted message is true.
For a C2C conversation, deleted messages cannot be pulled upon the next login of the current user, but the message pulling on the peer end is not affected.
For a group conversation, deleted messages cannot be pulled upon the next login of the current user, but the message pulling of other members in the group is not affected.
Note 1: Before using this API, upgrade your SDK to v2.12.0 or later.
Note 2: Up to 30 messages can be deleted at a time. If more than 30 messages need to be deleted at a time, only the first 30 messages are deleted.
Note 3: The messages to be deleted at a time must belong to the same conversation. The conversation of the first message in the message list prevails.
Note 4: This API can be called only once per second.
Note 5: The operation of message deletion cannot be synchronized across multiple devices.
Note 6: Audio-video groups (AVChatRoom) do not support message deletion. If you call this API for an audio-video group, error code 10035 will be returned.
Example
// Delete message. Supported from v2.12.0.
let promise = tim.deleteMessage([message1, message2, message3, ...]);
promise.then(function(imResponse) {
// Messages are deleted successfully.
}).catch(function(imError) {
// Messages fail to be deleted.
console.warn('deleteMessage error:', imError);
});
Parameters:
Name | Type | Description |
---|---|---|
messageList |
Array |
List of messages belonging to the same conversation. Up to 30 messages are supported. |
Returns:
- Type
- Promise
getMessageList(options) → {Promise}
Pull by page the message list of a specified conversation. This API is called when the message list is rendered for the first time after the user enters the conversation, or when the user pulls down the list to see more messages.
Note: This API can be used to "pull historical messages".
Examples
/ Pull the message list for the first time when a conversation is opened.
let promise = tim.getMessageList({conversationID: 'C2Ctest', count: 15});
promise.then(function(imResponse) {
const messageList = imResponse.data.messageList; // Message list.
const nextReqMessageID = imResponse.data.nextReqMessageID; // This parameter must be passed in for the next pulling by page.
const isCompleted = imResponse.data.isCompleted; // It indicates whether all messages have been pulled.
});
// Pull down to see more messages.
let promise = tim.getMessageList({conversationID: 'C2Ctest', nextReqMessageID, count: 15});
promise.then(function(imResponse) {
const messageList = imResponse.data.messageList; // Message list.
const nextReqMessageID = imResponse.data.nextReqMessageID; // This parameter must be passed in for the next pulling by page.
const isCompleted = imResponse.data.isCompleted; // It indicates whether all messages have been pulled.
});
Parameters:
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setMessageRead(options) → {Promise}
Set the unread messages of a conversation to the read state. Messages set to the read state are not counted as unread messages. This API is called when you open or switch a conversation. If this API is not called when you open or switch a conversation, the corresponding messages remain in the unread state.
Example
// Set all unread messages of a conversation to the read state
let promise = tim.setMessageRead({conversationID: 'C2Cexample'});
promise.then(function(imResponse) {
// Unread messages are set to the read state successfully. The value of the unreadCount property of the corresponding conversation with the specified ID is set to 0.
}).catch(function(imError) {
// Failed to set unread messages to the read state.
console.warn('setMessageRead error:', imError);
});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getConversationList() → {Promise}
Get the conversation list. This API will pull the latest 100 conversations and return the conversation list maintained inside the SDK after synchronization. You can call this API when you want to refresh the conversation list.
Note 1: The profile in the conversation list obtained by this API is incomplete. It contains only the information, such as profile photo and nickname, which is sufficient to meet the rendering requirements of the conversation list. To query the detailed conversation profile, call getConversationProfile.
Note 2: The conversation retention time is consistent with the storage time of the last message, which is 7 days by default. That is, the conversations will be stored for 7 days by default.
- See:
Example
// Pull the conversation list
let promise = tim.getConversationList();
promise.then(function(imResponse) {
const conversationList = imResponse.data.conversationList; // This conversation list will overwrite the original conversation list.
}).catch(function(imError) {
console.warn('getConversationList error:', imError); // Error information
});
Returns:
- Type
- Promise
getConversationProfile(conversationID) → {Promise}
Get a conversation profile. When you click a conversation in the conversation list, this API is called to get the detailed information of the conversation.
- See:
-
- Conversation Structure Description
Example
let promise = tim.getConversationProfile(conversationID);
promise.then(function(imResponse) {
// The conversation profile is successfully obtained.
console.log(imResponse.data.conversation); // Conversation profile
}).catch(function(imError) {
console.warn('getConversationProfile error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
conversationID |
String |
Conversation ID. Supported formats are as follows:
|
Returns:
- Type
- Promise
deleteConversation(conversationID) → {Promise}
Delete a conversation based on the conversation ID. This API deletes only the conversation, without deleting messages. For example, if the conversation with user A is deleted, the previous chat messages will still be available next time when you initiate a conversation with user A.
- See:
-
- Conversation Structure Description
Example
let promise = tim.deleteConversation('C2CExample');
promise.then(function(imResponse) {
// The conversation is deleted successfully.
const { conversationID } = imResponse.data;// ID of the deleted conversation
}).catch(function(imError) {
console.warn('deleteConversation error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
conversationID |
String |
Conversation ID. Supported formats are as follows:
|
Returns:
- Type
- Promise
pinConversation(options) → {Promise}
Pin/Unpin a conversation to/from top. After this API is called successfully, the conversation list will be sorted again, and the SDK will distribute the TIM.EVENT.CONVERSATION_LIST_UPDATED event.
Note: This API is supported from v2.14.0.
Examples
// Pin a conversation to top. Supported from v2.14.0.
let promise = tim.pinConversation({ conversationID: 'C2CExample', isPinned: true });
promise.then(function(imResponse) {
// The conversation is pinned to top successfully.
const { conversationID } = imResponse.data; // ID of the conversation pinned to top
}).catch(function(imError) {
console.warn('pinConversation error:', imError); // Error information
});
// Unpin a conversation from top. Supported from v2.14.0.
let promise = tim.pinConversation({ conversationID: 'C2CExample', isPinned: false });
promise.then(function(imResponse) {
// The conversation is unpinned from top successfully.
const { conversationID } = imResponse.data; // ID of the conversation unpinned from top
}).catch(function(imError) {
console.warn('pinConversation error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getMyProfile() → {Promise}
Get your personal profile.
Note: Custom profile fields are supported from SDK v2.3.2. Before using this API, upgrade your SDK to v2.3.2 or later.
- See:
-
- Profile Structure Description
Example
let promise = tim.getMyProfile();
promise.then(function(imResponse) {
console.log(imResponse.data); // Personal profile - profile instance
}).catch(function(imError) {
console.warn('getMyProfile error:', imError); // Error information
});
Returns:
- Type
- Promise
getUserProfile(options) → {Promise}
Get other users' profiles. This API will get both standard profile fields and custom profile fields at the same time. For more information, please see https://cloud.tencent.com/document/product/269/1500#.E8.B5.84.E6.96.99.E7.B3.BB.E7.BB.9F.E7.AE.80.E4.BB.8B.
Note 1: Custom profile fields are supported from SDK v2.3.2. Before using this API, upgrade your SDK to v2.3.2 or later.
Note 2: If you have not configured any custom profile fields or you have configured custom profile fields but have not set the values, this API will not return custom profile information.
Note 3: Profiles of no more than 100 users are pulled each time to prevent a response packet failure due to excessive data. If the array passed in contains more than 100 users, only the first 100 users will be used for profile query and the rest will be discarded.
Example
let promise = tim.getUserProfile({
userIDList: ['user1', 'user2'] // Note: even if you retrieve the profile of only one user, the value must be of array type, for example, userIDList: ['user1'].
});
promise.then(function(imResponse) {
console.log(imResponse.data); // Array that stores other users' profiles - [Profile]
}).catch(function(imError) {
console.warn('getUserProfile error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Search parameters Properties
|
Returns:
- Type
- Promise
updateMyProfile(options) → {Promise}
Update your personal profile.
Note: Custom profile fields are supported from SDK v2.3.2. Before using this API, upgrade your SDK to v2.3.2 or later.
Examples
// Modify your personal standard profile.
let promise = tim.updateMyProfile({
nick: 'My nickname',
avatar: 'http(s)://url/to/image.jpg',
gender: TIM.TYPES.GENDER_MALE,
selfSignature: 'My status',
allowType: TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
});
promise.then(function(imResponse) {
console.log(imResponse.data); // The profile is updated.
}).catch(function(imError) {
console.warn('updateMyProfile error:', imError); // Error information
});
// Modify personal custom profile fields
// Custom profile fields must be configured in the IM console in advance. For more information, see https://cloud.tencent.com/document/product/269/1500#.E8.87.AA.E5.AE.9A.E4.B9.89.E8.B5.84.E6.96.99.E5.AD.97.E6.AE.B5.
let promise = tim.updateMyProfile({
// Ensure that you have applied for the custom profile field Tag_Profile_Custom_Test1 in the IM console by clicking the desired app card and choosing Feature Configuration > User Custom Field.
// Note: even if only this one custom data field exists, the format of profileCustomField must be of array type.
profileCustomField: [
{
key: 'Tag_Profile_Custom_Test1',
value: 'My custom profile 1'
}
]
});
promise.then(function(imResponse) {
console.log(imResponse.data); // The profile is updated.
}).catch(function(imError) {
console.warn('updateMyProfile error:', imError); // Error information
});
// Modify personal standard and custom profile fields
let promise = tim.updateMyProfile({
nick: 'My nickname',
// Ensure that you have applied for the custom profile fields Tag_Profile_Custom_Test1 and Tag_Profile_Custom_Test2 in the IM console by clicking the desired app card and choosing Feature Configuration > User Custom Field.
profileCustomField: [
{
key: 'Tag_Profile_Custom_Test1',
value: 'My custom profile 1'
},
{
key: 'Tag_Profile_Custom_Test2',
value: 'My custom profile 2'
},
]
});
promise.then(function(imResponse) {
console.log(imResponse.data); // The profile is updated.
}).catch(function(imError) {
console.warn('updateMyProfile error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Profile parameters Properties
|
Returns:
- Type
- Promise
getBlacklist() → {Promise}
Get your blocklist.
Example
let promise = tim.getBlacklist();
promise.then(function(imResponse) {
console.log(imResponse.data); // Your blocklist. The value is an array that contains userIDs - [userID].
}).catch(function(imError) {
console.warn('getBlacklist error:', imError); // Error information
});
Returns:
- Type
- Promise
addToBlacklist(options) → {Promise}
Add a user to the blocklist. By adding a user to the blocklist, you can block all the messages sent by the user. Therefore, this API can be used to block the messages of a specified user.
- If users A and B are friends, either one adding the other to the blocklist removes them from each other's friend list.
- If users A and B are in a blocklist relationship, neither user A nor user B can initiate a conversation with the other user.
- If users A and B are in a blocklist relationship, neither user A nor user B can send a friend request to the other user.
Example
let promise = tim.addToBlacklist({userIDList: ['user1', 'user2']}); // Note: even if you add only one userID to the blocklist, the value must be of array type, for example, userIDList: ['user1'].
promise.then(function(imResponse) {
console.log(imResponse.data); // Information on the userIDs that are added to the blocklist. The value must be an array that contains userIDs - [userID].
}).catch(function(imError) {
console.warn('addToBlacklist error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
removeFromBlacklist(options) → {Promise}
Remove users from the blocklist.
Example
let promise = tim.removeFromBlacklist({userIDList: ['user1', 'user2']}); // Note: even if you remove only one userID from the blocklist, the value must be of array type, for example, userIDList: ['user1'].
promise.then(function(imResponse) {
console.log(imResponse.data); // List of userIDs that are successfully removed from the blocklist. The value is an array that contains the userIDs - [userID].
}).catch(function(imError) {
console.warn('removeFromBlacklist error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
options |
Object |
Parameter options |
option.userIDList |
Array.<String> |
List of the userIDs to be removed from the blocklist. The number of userIDs in a single request cannot exceed 1,000. |
Returns:
Notes for using checkType:
- Type
- Promise
getFriendList() → {Promise}
Get the friend list in the SDK cache. When a friend list is updated, the SDK distributes the TIM.EVENT.FRIEND_LIST_UPDATED event.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.getFriendList();
promise.then(function(imResponse) {
const friendList = event.data; // Friend list
}).catch(function(imError) {
console.warn('getFriendList error:', imError); // Error information
});
Returns:
- Type
- Promise
addFriend(options) → {Promise}
Add a friend.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
// Add a friend
let promise = tim.addFriend({
to: 'user1',
source: 'AddSource_Type_Web',
remark: 'Jane',
groupName: 'Friend',
wording: 'I'm user0',
type: TIM.TYPES.SNS_ADD_TYPE_BOTH,
});
promise.then(function(imResponse) {
// The friend request is sent successfully.
const { code } = imResponse.data;
if (code === 30539) {
// 30539 indicates that user1 has set the friend request processing method to manually accept friend requests received. The SDK will trigger the TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED event.
} else if (code === 0) {
// 0 indicates that user1 has set the friend request processing method to automatically accept all friend requests received. The SDK will trigger the TIM.EVENT.FRIEND_LIST_UPDATED event.
}
}).catch(function(imError) {
console.warn('addFriend error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
deleteFriend(options) → {Promise}
Delete friends. Both one-way deletion and two-way deletion are supported.
Note 1: This API is supported from v2.13.0. For more information, see Upgrade Guide. Note 2: You are advised to specify no more than 100 user IDs at a time. A larger number may cause the request to be rejected by the backend due to an excessively large data packet. The maximum size of a data packet supported by the backend is 1 MB.
Example
let promise = tim.deleteFriend({
userIDList: ['user1','user2'],
type: TIM.TYPES.SNS_DELETE_TYPE_BOTH
});
promise.then(function(imResponse) {
const { successUserIDList, failureUserIDList } = imResponse.data;
// List of friend userIDs that are successfully deleted
successUserIDList.forEach((item) => {
const { userID } = item;
});
// List of friend userIDs that fail to be deleted
failureUserIDList.forEach((item) => {
const { userID, code, message } = item;
});
// If the friend list is updated, the SDK triggers the TIM.EVENT.FRIEND_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('removeFromFriendList error:', imError);
});
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
checkFriend(options) → {Promise}
Verify friends.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.checkFriend({
userIDList: ['user0','user1'],
type: TIM.TYPES.SNS_CHECK_TYPE_BOTH,
});
promise.then(function(imResponse) {
const { successUserIDList, failureUserIDList } = imResponse.data;
// List of friend userIDs that pass the verification
successUserIDList.forEach((item) => {
const { userID, code, relation } = item; // The value of code is always 0.
// Possible results of one-way friend verification are:
// - relation: TIM.TYPES.SNS_TYPE_NO_RELATION: B is not on A's friend list, but it cannot determine whether A is on B's friend list.
// - relation: TIM.TYPES.SNS_TYPE_A_WITH_B: B is on A's friend list, but it cannot determine whether A is on B's friend list.
// Possible results of two-way friend verification are:
// - relation: TIM.TYPES.SNS_TYPE_NO_RELATION: A and B are not on each other's friend list
// - relation: TIM.TYPES.SNS_TYPE_A_WITH_B: B is on A's friend list, but A is not on B's friend list
// - relation: TIM.TYPES.SNS_TYPE_B_WITH_A: B is not on A's friend list, but A is on B's friend list
// - relation: TIM.TYPES.SNS_TYPE_BOTH_WAY: A and B are on each other's friend list
});
// List of friend userIDs that fail the verification
failureUserIDList.forEach((item) => {
const { userID, code, message } = item;
});
}).catch(function(imError) {
console.warn('checkFriend error:', imError);
});
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getFriendProfile(options) → {Promise}
Get the standard and custom friend and profile data of a specified user.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.getFriendProfile({
userIDList: ['user0','user1']
});
promise.then(function(imResponse) {
const { friendList, failureUserIDList } = imResponse.data;
friendList.forEach((friend) => {
// Friend object
});
// List of failed userIDs
failureUserIDList.forEach((item) => {
const { userID, code, message } = item;
});
}).catch(function(imError) {
console.warn('getFriendProfile error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
updateFriend(options) → {Promise}
Update the relationship chain data of friends. This API can update only friend remarks and custom relationship chain fields.
Notes:
- This API is supported from v2.13.0. Upgrade Guide.
- To update friend lists, use the addToFriendGroup and removeFromFriendGroup APIs.
Examples
// Update friend remarks
let promise = tim.updateFriend({
userID: 'user1',
remark: 'helloworld'
});
promise.then(function(imResponse) {
console.log(imResponse.data); // Friend instance
}).catch(function(imError) {
console.warn('getFriendProfile error:', imError); // Update failure
});
// Update custom friend fields
let promise = tim.updateFriend({
userID: 'user1',
friendCustomField: [
// Custom friend fields must use the prefix Tag_SNS_Custom.
{ key: 'Tag_SNS_Custom_test1', value: 'hello' },
{ key: 'Tag_SNS_Custom_test2', value: 'world' },
]
});
promise.then(function(imResponse) {
console.log(imResponse.data); // Friend instance
}).catch(function(imError) {
console.warn('getFriendProfile error:', imError); // Update failure
});
Parameters:
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getFriendApplicationList() → {Promise}
Get the friend request list in the SDK cache. When a friend request list is updated, the SDK distributes the TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED event.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.getFriendApplicationList();
promise.then(function(imResponse) {
// friendApplicationList - Friend request list - [FriendApplication]
// unreadCount - Unread friend request count
// const { friendApplicationList, unreadCount } = imResponse.data;
}).catch(function(imError) {
console.warn('getFriendApplicationList error:', imError); // Error information
});
Returns:
- Type
- Promise
acceptFriendApplication(options) → {Promise}
Accept a friend request.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.acceptFriendApplication({
userID: 'user1',
remark: 'Customer service Jack',
type: TIM.TYPES.SNS_APPLICATION_AGREE_AND_ADD
});
promise.then(function(imResponse) {
// When the friend request is successfully accepted, the SDK triggers the TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('acceptFriendApplication error:', imError);
});
Parameters:
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
refuseFriendApplication(options) → {Promise}
Reject a friend request.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.refuseFriendApplication({
userID: 'user1',
});
promise.then(function(imResponse) {
// When the friend request is successfully rejected, the SDK triggers the TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('refuseFriendApplication error:', imError);
});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
deleteFriendApplication(options) → {Promise}
Delete a friend request.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.deleteFriendApplication({
userID: 'user1',
type: TIM.TYPES.SNS_APPLICATION_SENT_TO_ME
});
promise.then(function(imResponse) {
// When the friend request is successfully deleted, the SDK triggers the TIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('deleteFriendApplication error:', imError);
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setFriendApplicationRead() → {Promise}
Set a friend request as read.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
// Set a friend request as read
let promise = tim.setFriendApplicationRead();
promise.then(function(imResponse) {
// Successfully set a friend request as read
}).catch(function(imError) {
console.warn('setFriendApplicationRead error:', imError);
});
Returns:
- Type
- Promise
getFriendGroupList() → {Promise}
Get the list of friend lists in the SDK cache. When the list of friend lists is updated, the SDK distributes the TIM.EVENT.FRIEND_GROUP_LIST_UPDATED event.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.getFriendGroupList();
promise.then(function(imResponse) {
const friendGroupList = event.data; // List of friend lists
}).catch(function(imError) {
console.warn('getFriendGroupList error:', imError); // Error information
});
Returns:
- Type
- Promise
createFriendGroup(options) → {Promise}
Create a friend list.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.createFriendGroup({
name: 'My friend list 1',
userIDList: ['user0','user1']
});
promise.then(function(imResponse) {
const { friendGroup,failureUserIDList } = imResponse;
// friendGroup - Friend list instance
// failureUserIDList - List of failed userIDs
// When the friend list is successfully created, the SDK triggers the TIM.EVENT.FRIEND_GROUP_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('getFriendGroupInfo error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
deleteFriendGroup(options) → {Promise}
Delete a friend list.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.deleteFriendGroup({
name: 'My friend list 1',
});
promise.then(function(imResponse) {
console.log(imResponse.data); // Friend list instance
// When the friend list is successfully deleted, the SDK triggers the TIM.EVENT.FRIEND_GROUP_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('deleteFriendGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
addToFriendGroup(options) → {Promise}
Add friends to a friend list.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.addToFriendGroup({
name: 'My friend list 1',
userIDList: ['user1','user2'],
});
promise.then(function(imResponse) {
const { friendGroup, failureUserIDList } = imResponse.data;
// friendGroup - Friend list instance
// failureUserIDList - List of failed userIDs
// When the friends are successfully added to the friend list, the SDK triggers the TIM.EVENT.FRIEND_GROUP_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('addToFriendGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
removeFromFriendGroup(options) → {Promise}
Remove friends from a friend list.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.removeFromFriendGroup({
name: 'My friend list 1',
userIDList: ['user1','user2'],
});
promise.then(function(imResponse) {
const { friendGroup, failureUserIDList } = imResponse.data;
// friendGroup - Friend list instance
// failureUserIDList - List of failed userIDs
// When the friends are successfully removed from the friend list, the SDK triggers the TIM.EVENT.FRIEND_GROUP_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('addToFriendGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
renameFriendGroup(options) → {Promise}
Modify the name of a friend list.
Note: This API is supported from v2.13.0. Upgrade Guide.
Example
let promise = tim.renameFriendGroup({
oldName: 'Friends',
newName: 'Besties'
});
promise.then(function(imResponse) {
console.log(imResponse.data); // Friend list instance
// When the name of a friend list is changed successfully, the SDK triggers the TIM.EVENT.FRIEND_GROUP_LIST_UPDATED event.
}).catch(function(imError) {
console.warn('updateMyProfile error:', imError);
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getGroupList(options) → {Promise}
Get your group list when you need to render or refresh **My Groups**. For more information, see Group.
Note: The group list returned by this API does not include TIM.TYPES.GRP_AVCHATROOM groups (audio-video groups).
- See:
Examples
// This API pulls only the following information by default: group type, group name, group profile photo, and the time of the last message.
let promise = tim.getGroupList();
promise.then(function(imResponse) {
console.log(imResponse.data.groupList); // Group list
}).catch(function(imError) {
console.warn('getGroupList error:', imError); // Error information
});
// If the profile fields that are pulled by default fail to meet your requirements, you can pull additional profile fields by referring to the following code.
let promise = tim.getGroupList({
groupProfileFilter: [TIM.TYPES.GRP_PROFILE_OWNER_ID],
});
promise.then(function(imResponse) {
console.log(imResponse.data.groupList); // Group list
}).catch(function(imError) {
console.warn('getGroupList error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Request parameters Properties
|
Returns:
- Type
- Promise
getGroupProfile(options) → {Promise}
Get a group profile.
- See:
Example
let promise = tim.getGroupProfile({ groupID: 'group1', groupCustomFieldFilter: ['key1','key2'] });
promise.then(function(imResponse) {
console.log(imResponse.data.group);
}).catch(function(imError) {
console.warn('getGroupProfile error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
createGroup(options) → {Promise}
Create a group.
Note: After creating an audio-video group (TIM.TYPES.GRP_AVCHATROOM) via this API, you need to call the joinGroup API to join the group to enable the messaging process.
- See:
Example
// Create a work group
let promise = tim.createGroup({
type: TIM.TYPES.GRP_WORK,
name: 'WebSDK',
memberList: [{
userID: 'user1',
// Group member custom field. By default, this parameter is not available and needs to be enabled. For details, see Custom Fields.
memberCustomField: [{key: 'group_member_test', value: 'test'}]
}, {
userID: 'user2'
}] // If memberList is specified, userID must also be specified.
});
promise.then(function(imResponse) { // Created successfully
console.log(imResponse.data.group); // Profile of the created group
// A member list is specified during group creation, but a certain user has exceeded the limit on the number of groups a single user can join.
// If you specify userX, who has joined N groups (maximum number of groups userX can join), as a member of the group during group creation, userX cannot join the group properly.
// The SDK places the information of userX in overLimitUserIDList for the access side to process.
console.log(imResponse.data.overLimitUserIDList); // List of users who have exceeded the limit on the number of groups a single user can join. (Supported from v2.10.2)
}).catch(function(imError) {
console.warn('createGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter set Properties
|
Returns:
- Type
- Promise
dismissGroup(groupID) → {Promise}
This API is used by a group owner to delete a group.
Note: A group owner cannot delete a work group.
- See:
Example
let promise = tim.dismissGroup('group1');
promise.then(function(imResponse) { // Deleted successfully
console.log(imResponse.data.groupID); // ID of the deleted group
}).catch(function(imError) {
console.warn('dismissGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
groupID |
String |
Group ID |
Returns:
- Type
- Promise
updateGroupProfile(options) → {Promise}
Modify a group profile.
- See:
Examples
let promise = tim.updateGroupProfile({
groupID: 'group1',
name: 'new name', // Modify the group name
introduction: 'this is introduction.', // Modify the group introduction
// Starting from v2.6.0, group members can receive group messages about group custom field modifications and obtain related content. For more information, see Message.payload.newGroupProfile.groupCustomField.
groupCustomField: [{ key: 'group_level', value: 'high'}] // Modify the group custom field
});
promise.then(function(imResponse) {
console.log(imResponse.data.group) // Detailed group profile after modification
}).catch(function(imError) {
console.warn('updateGroupProfile error:', imError); // Error information
});
// Starting from v2.6.2, the SDK supports muting and unmuting all. Currently, when all users are muted in a group, group notifications cannot be delivered.
let promise = tim.updateGroupProfile({
groupID: 'group1',
muteAllMembers: true, // true: mute all; false: unmute all
});
promise.then(function(imResponse) {
console.log(imResponse.data.group) // Detailed group profile after modification
}).catch(function(imError) {
console.warn('updateGroupProfile error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Request parameters Properties
|
Returns:
- Type
- Promise
joinGroup(options) → {Promise}
Request to join a specific group.
Notes:
- Users cannot request to join a work group. They can only be added to a work group via addGroupMember.
- You can join an audio-video group (TIM.TYPES.GRP_AVCHATROOM) in two ways:
2.1. Normal group joining, that is, group joining after login. In that case, all APIs in the SDK can be called properly.
2.2. Anonymous group joining, that is, group joining without login. In that case, only messages can be received, and other APIs that require authentication cannot be called. - Only audio-video groups (TIM.TYPES.GRP_AVCHATROOM) support anonymous group joining.
- A user can only join one audio-video group at a time. For example, if a user is already in audio-video group A and attempts to join audio-video group B, the SDK will remove the user from audio-video group A first and then add the user to audio-video group B.
- See:
Example
let promise = tim.joinGroup({ groupID: 'group1', type: TIM.TYPES.GRP_AVCHATROOM });
promise.then(function(imResponse) {
switch (imResponse.data.status) {
case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // Waiting to be approved by the admin
break;
case TIM.TYPES.JOIN_STATUS_SUCCESS: // Joined the group successfully
console.log(imResponse.data.group); // Profile of the group
break;
case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // The user is already in the group
break;
default:
break;
}
}).catch(function(imError){
console.warn('joinGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
quitGroup(groupID) → {Promise}
Leave a group.
Note: A group owner can only leave work groups. After the group owner leaves a work group, the work group has no group owner.
- See:
Example
let promise = tim.quitGroup('group1');
promise.then(function(imResponse) {
console.log(imResponse.data.groupID); // ID of the group that the user leaves
}).catch(function(imError){
console.warn('quitGroup error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
groupID |
String |
Group ID |
Returns:
When the group leaving operation is successful, the return parameter contains the ID of the group that the user leaves.
- Type
- Promise
searchGroupByID(groupID) → {Promise}
Search for a group by groupID.
Note: Work groups (TIM.TYPES.GRP_WORK) cannot be searched.
- See:
Example
let promise = tim.searchGroupByID('group1');
promise.then(function(imResponse) {
const group = imResponse.data.group; // Group information
}).catch(function(imError) {
console.warn('searchGroupByID error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
groupID |
String |
Group ID |
Returns:
- Type
- Promise
getGroupOnlineMemberCount(groupID) → {Promise}
Get the number of online users. This API applies only to audio-video groups.
Note: If this API is called to get the number of online users in a group other than an audio-video group, memberCount returned by the SDK is 0. It's recommended that you call this API for no more than one time per 5-10 seconds.
- See:
Example
// Get the number of online users in an audio-video group (supported from v2.8.0)
let promise = tim.getGroupOnlineMemberCount('group1');
promise.then(function(imResponse) {
console.log(imResponse.data.memberCount);
}).catch(function(imError) {
console.warn('getGroupOnlineMemberCount error:', imError); // Error information
});
Parameters:
Name | Type | Description |
---|---|---|
groupID |
String |
Group ID |
Returns:
- Type
- Promise
changeGroupOwner(options) → {Promise}
Transfer a group. Only group owners have the permission to transfer groups.
Note: Only group owners have the permission to transfer groups. Audio-video groups (TIM.TYPES.GRP_AVCHATROOM) cannot be transferred.
- See:
Example
let promise = tim.changeGroupOwner({
groupID: 'group1',
newOwnerID: 'user2'
});
promise.then(function(imResponse) { // Transferred successfully
console.log(imResponse.data.group); // Group profile
}).catch(function(imError) { // Failed to transfer the group
console.warn('changeGroupOwner error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
handleGroupApplication(options) → {Promise}
Process (approve or reject) a group joining request.
Note: If a group has more than one admin, all online admins will receive a group system message about the group joining request when someone requests to join the group. If one admin processes the request (accepts or rejects it), the other admins cannot process the request again (that is, cannot modify the processing result).
- See:
Example
let promise = tim.handleGroupApplication({
handleAction: 'Agree',
handleMessage: 'Welcome',
message: message // The message instance of the group system notification for an application to join a group.
});
promise.then(function(imResponse) {
console.log(imResponse.data.group); // Group profile
}).catch(function(imError){
console.warn('handleGroupApplication error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
initGroupAttributes(options) → {Promise}
Initialize group attributes. The business side needs to control the operation permission of this API based on application scenarios.
Note 1: This API is supported from v2.14.0.
Note 2: This API applies only to audio-video groups. If you call this API for other types of groups, this API returns the 2641 error code.
Note 3: Before using this API, you must call the joinGroup API to join an audio-video group. Otherwise, this API returns the 2642 error code.
Note 4: Up to 16 group attribute keys are supported, with a length limit of 32 bytes. The size of each group attribute value can be up to 4 KB, and the total size of all group attributes (including keys and values) can be up to 16 KB.
Example
let promise = tim.initGroupAttributes({
groupID: 'group1',
groupAttributes: { key1: 'value1', key2: 'value2' }
});
promise.then(function(imResponse) { // Initialized successfully
console.log(imResponse.data.groupAttributes); // Group attributes initialized successfully
}).catch(function(imError) { // Initialization failed
console.warn('initGroupAttributes error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setGroupAttributes(options) → {Promise}
Set group attributes.
Note 1: This API is supported from v2.14.0.
Note 2: This API applies only to audio-video groups. If you call this API for other types of groups, this API returns the 2641 error code.
Note 3: Before using this API, you must call the joinGroup API to join an audio-video group. Otherwise, this API returns the 2642 error code.
Example
let promise = tim.setGroupAttributes({
groupID: 'group1',
groupAttributes: { key1: 'value1', key2: 'value2' }
});
promise.then(function(imResponse) { // Set successfully
console.log(imResponse.data.groupAttributes); // Group attributes set successfully
}).catch(function(imError) { // Setting failed
console.warn('setGroupAttributes error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
deleteGroupAttributes(options) → {Promise}
Delete group attributes.
Note 1: This API is supported from v2.14.0.
Note 2: This API applies only to audio-video groups. If you call this API for other types of groups, this API returns the 2641 error code.
Note 3: Before using this API, you must call the joinGroup API to join an audio-video group. Otherwise, this API returns the 2642 error code.
Note 4: To delete specified group attributes (key-value pairs), pass in a non-empty array for keyList. To delete all group attributes, pass in an empty array for keyList.
Examples
// Delete specified group attributes
let promise = tim.deleteGroupAttributes({
groupID: 'group1',
keyList: ['key1', 'key2']
});
promise.then(function(imResponse) { // Deleted successfully
console.log(imResponse.data.keyList); // List of group attributes deleted successfully
}).catch(function(imError) { // Deletion failed
console.warn('deleteGroupAttributes error:', imError); // Error information
});
// Delet all group attributes
let promise = tim.deleteGroupAttributes({
groupID: 'group1',
keyList: []
});
promise.then(function(imResponse) { // Deleted successfully
console.log(imResponse.data.keyList); // List of group attributes deleted successfully
}).catch(function(imError) { // Deletion failed
console.warn('deleteGroupAttributes error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getGroupAttributes(options) → {Promise}
Get group attributes.
Note 1: This API is supported from v2.14.0.
Note 2: This API applies only to audio-video groups. If you call this API for other types of groups, this API returns the 2641 error code.
Note 3: Before using this API, you must call the joinGroup API to join an audio-video group. Otherwise, this API returns the 2642 error code.
Note 4: To get specified group attributes, pass in a non-empty array for keyList. To get all group attributes, pass in an empty array for keyList.
Examples
// Get specified group attributes
let promise = tim.getGroupAttributes({
groupID: 'group1',
keyList: ['key1', 'key2']
});
promise.then(function(imResponse) { // Got successfully
console.log(imResponse.data.groupAttributes); // Specified group attributes
}).catch(function(imError) { // Getting failed
console.warn('getGroupAttributes error:', imError); // Error information
});
// Get all group attributes
let promise = tim.getGroupAttributes({
groupID: 'group1',
keyList: []
});
promise.then(function(imResponse) { // Got successfully
console.log(imResponse.data.groupAttributes); // All group attributes
}).catch(function(imError) { // Getting failed
console.warn('getGroupAttributes error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
getGroupMemberList(options) → {Promise}
Get the group member list.
Note 1: Starting from v2.6.2, this API can be used to pull the muting stop timestamps of group members (muteUntil). Based on its value, the access side can find out whether the member is muted and the remaining muting time.
In versions earlier than v2.6.2, this API can be used to get profile information including profile photo and nickname, which is sufficient to meet the rendering requirements of the group member list. To get detailed information such as member muting stop timestamp (muteUntil), use getGroupMemberProfile.
Noe 2: This API is used to pull paginated list of group members and not the complete list. To get the complete list of group members (memberNum), use getGroupProfile.
- See:
Examples
let promise = tim.getGroupMemberList({ groupID: 'group1', count: 30, offset:0 }); // Pull 30 group members starting from 0
promise.then(function(imResponse) {
console.log(imResponse.data.memberList); // Group member list
}).catch(function(imError) {
console.warn('getGroupMemberList error:', imError);
});
// Starting from v2.6.2, this API can be used to pull the muting stop timestamps of group members.
let promise = tim.getGroupMemberList({ groupID: 'group1', count: 30, offset:0 }); // Pull 30 group members starting from 0.
promise.then(function(imResponse) {
console.log(imResponse.data.memberList); // Group member list
for (let groupMember of imResponse.data.memberList) {
if (groupMember.muteUntil * 1000 > Date.now()) {
console.log(`${groupMember.userID} muted`);
} else {
console.log(`${groupMember.userID} not muted`);
}
}
}).catch(function(imError) {
console.warn('getGroupMemberProfile error:', imError);
});
Parameters:
Name | Type | Description | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Request parameters Properties
|
Returns:
- Type
- Promise
getGroupMemberProfile(options) → {Promise}
Get group member profiles, including muting durations.
Note 1: Before using this API, upgrade your SDK to v2.2.0 or later.
Note 2: The maximum number of users in each query is 50. If the length of the array passed in is greater than 50, only the first 50 users will be queried and the rest will be discarded.
- See:
Example
let promise = tim.getGroupMemberProfile({
groupID: 'group1',
userIDList: ['user1', 'user2'], // Note: even if you retrieve the profile of only one group member, the value must be of array type, for example, userIDList: ['user1'].
memberCustomFieldFilter: ['group_member_custom'], // Group member custom field to query: group_member_custom
});
promise.then(function(imResponse) {
console.log(imResponse.data.memberList); // Group member list
}).catch(function(imError) {
console.warn('getGroupMemberProfile error:', imError);
});
Parameters:
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Request parameters Properties
|
Returns:
Promise objects
- Type
- Promise
addGroupMember(options) → {Promise}
Add group members. Detailed rules are as follows:
- TIM.TYPES.GRP_PRIVATE (work group): any group member can invite users to the group and approval by the invitee is not required.
- TIM.TYPES.GRP_PUBLIC (public group)/TIM.TYPES.GRP_MEETING (meeting group): only the app admin can invite users to the group and approval by the invitee is not required.
- TIM.TYPES.GRP_AVCHATROOM (audio-video chat room): no member (including the app admin) is allowed to invite any user to the group.
Example
let promise = tim.addGroupMember({groupID: 'group1', userIDList: ['user1','user2','user3']});
promise.then(function(imResponse) {
console.log(imResponse.data.successUserIDList); // userIDList of group members that were added successfully
console.log(imResponse.data.failureUserIDList); // userIDList of group members that failed to be added
console.log(imResponse.data.existedUserIDList); // userIDList of group members that were already in the group
// If you specify userX, who has joined N groups (maximum number of groups userX can join), as a member of the group, userX cannot join the group properly.
// The SDK places the information of userX in overLimitUserIDList for the access side to process.
console.log(imResponse.data.overLimitUserIDList); // List of users who have exceeded the limit on the number of groups a single user can join. (Supported from v2.10.2)
console.log(imResponse.data.group); // Group profile displayed after group members addition
}).catch(function(imError) {
console.warn('addGroupMember error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
deleteGroupMember(options) → {Promise}
Delete group members. Only the group owner can delete group members.
- See:
Example
let promise = tim.deleteGroupMember({groupID: 'group1', userIDList:['user1'], reason: 'You are deleted from the group because you have violated the group rules.'});
promise.then(function(imResponse) {
console.log(imResponse.data.group); // Group profile displayed after group member deletion
console.log(imResponse.data.userIDList); // List of userIDs of the deleted group members
}).catch(function(imError) {
console.warn('deleteGroupMember error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setGroupMemberMuteTime(options) → {Promise}
Set the muting duration for a group member. You can mute or unmute a group member. The muting and unmuting features are unavailable for work groups (TIM.TYPES.GRP_WORK).
Note: Only the group owner and the group admin have the permission to perform this operation.
- The group owner can mute and unmute the admin and common group members.
- The admin can mute and unmute only common group members.
Example
let promise = tim.setGroupMemberMuteTime({
groupID: 'group1',
userID: 'user1',
muteTime: 600 // The user is muted for 10 minutes. If the value is set to 0, the user is unmuted.
});
promise.then(function(imResponse) {
console.log(imResponse.data.group); // New group profile
console.log(imResponse.data.member); // New group member profile
}).catch(function(imError) {
console.warn('setGroupMemberMuteTime error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setGroupMemberRole(options) → {Promise}
Change the role of a group member. Only the group owner has the permission to perform this operation.
- See:
Example
let promise = tim.setGroupMemberRole({
groupID: 'group1',
userID: 'user1',
role: TIM.TYPES.GRP_MBR_ROLE_ADMIN // Set user1 as the admin of group1.
});
promise.then(function(imResponse) {
console.log(imResponse.data.group); // New group profile
console.log(imResponse.data.member); // New group member profile
}).catch(function(imError) {
console.warn('setGroupMemberRole error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setGroupMemberNameCard(options) → {Promise}
Set a group member's name card.
- The group owner can set the name cards of all members.
- The group admin can set its own name card and the name cards of common group members.
- Common group members can only set their own name cards.
- See:
Example
let promise = tim.setGroupMemberNameCard({ groupID: 'group1', userID: 'user1', nameCard: 'Name card' });
promise.then(function(imResponse) {
console.log(imResponse.data.group); // New group profile
console.log(imResponse.data.member); // New group member profile
}).catch(function(imError) {
console.warn('setGroupMemberNameCard error:', imError); // Error information
});
Parameters:
Name | Type | Description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setGroupMemberCustomField(options) → {Promise}
Set a group member custom field.
Note: Common group members can only modify their own custom fields.
- See:
Example
let promise = tim.setGroupMemberCustomField({ groupID: 'group1', memberCustomField: [{key: 'group_member_test', value: 'test'}]});
promise.then(function(imResponse) {
console.log(imResponse.data.group); // New group profile
console.log(imResponse.data.member); // New group member profile
}).catch(function(imError) {
console.warn('setGroupMemberCustomField error:', imError); // Error information
});
Parameters:
Name | Type | Description | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise
setMessageRemindType(options) → {Promise}
As a group member, set the message notification type for your group. You can use this API to mute notifications or enable new message alerts.
- See:
Examples
// Mute notifications
let promise = tim.setMessageRemindType({ groupID: 'group1', messageRemindType: TIM.TYPES.MSG_REMIND_DISCARD });
promise.then(function(imResponse) {
console.log(imResponse.data.group.selfInfo); // Information of the current user in the group
}).catch(function(imError) {
console.warn('setMessageRemindType error:', imError);
});
// Enable new message alert after muting notifications
let promise = tim.setMessageRemindType({ groupID: 'group1', messageRemindType: TIM.TYPES.MSG_REMIND_ACPT_AND_NOTE });
promise.then(function(imResponse) {
console.log(imResponse.data.group.selfInfo); // Information of the current user in the group
}).catch(function(imError) {
console.warn('setMessageRemindType error:', imError);
});
Parameters:
Name | Type | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
Object |
Parameter options Properties
|
Returns:
- Type
- Promise