React Native

Updated

API reference for the Agora Signaling React Native SDK.

The Signaling SDK API reference is divided into the following sections:

Setup

The RTM SDK API reference introduces the API definitions, methods, basic usage examples, and return values related to real-time messaging.

RtmConfig

Description

RtmConfig is used to configure additional properties during RTM initialization. These configuration properties take effect for the entire lifecycle of the RTM client and affect its behavior.

Method

You can create an RtmConfig instance as follows:

new RtmConfig({
    userId: uid,
    appId: appId,
})
ParameterTypeRequiredDefaultDescription
appIdstringRequired-The App ID obtained when you create a project in the Agora Console.
userIdstringRequired-User ID used to identify a user or device. To distinguish users and devices, ensure that userId is globally unique and remains unchanged during the user or device lifecycle.
areaCodeRtmAreaCodeOptionalglobService area code. You can select based on your business deployment region. See RtmAreaCode.
protocolTypeRtmProtocolTypeOptionaltcpUdpMessage transport protocol type. RTM uses both TCP and UDP by default. You can change the protocol type as needed. See RtmProtocolType.
presenceTimeoutnumberOptional300Presence timeout in seconds. Range: [5, 300]. After the RTM server determines the client is offline, it waits for this duration before sending a remoteTimeout event to other users. If the client reconnects and rejoins the channel within this time, the server does not notify others or delete temporary user data.
heartbeatIntervalnumberOptional5SDK heartbeat interval in seconds. Range: [5, 1800]. The interval at which the client sends heartbeat packets to the RTM server. If no heartbeat is sent within this time, the server considers the client timed out.

Info: This parameter affects PCU counting and billing.
useStringUserIdbooleanOptionaltrueWhether to use String type for user ID:
- true: Use String type user ID.
- false: Use Uint type user ID. The SDK converts a String-type userId to Uint. In this case, you must pass a numeric string (e.g., "1234567"); otherwise, the method call fails.When using both Agora RTC and RTM, ensure userId is the same.
eventHandlerIRtmEventHandlerRequired-RTM event notification handler. See Event Listener.
logConfigRtmLogConfigOptional-Configuration for local log storage such as size, location, and log level.
proxyConfigRtmProxyConfigOptional-Required when using RTM Proxy functionality.
encryptionConfigRtmEncryptionConfigOptional-Required when using RTM client-side encryption.
privateConfigRtmPrivateConfigOptional-Required when using RTM private deployment.
RtmLogConfig

An RtmLogConfig instance is used to configure and store the local log file agora.log. During debugging, logs help track app status and significantly improve efficiency. If complex issues occur, Agora support may ask for these logs. RtmLogConfig includes the following properties:

ParameterTypeRequiredDefaultDescription
filePathstringOptional-Log file storage path.
fileSizeInKBnumberOptional1024Log file size in KB. Range: [128, 1024].
- If the value is less than 128, SDK sets it to 128.
- If the value is greater than 1024, SDK sets it to 1024.
levelRtmLogLevelOptionalinfoLog output level. See RtmLogLevel.
RtmProxyConfig

An RtmProxyConfig instance configures proxy-related properties for the client. You may need this in restricted network environments.

Info

Keep your proxy username and password secure. RTM does not parse, store, or forward your credentials. If you change proxy settings during app runtime, you must restart the RTM client for changes to take effect.

RtmProxyConfig includes the following properties:

PropertyTypeRequiredDefaultDescription
proxyTypeRtmProxyTypeOptionalnoneProxy protocol type. See RtmProxyType.
serverstringOptional-Proxy server domain or IP address.
portnumberOptional-Proxy server port.
accountstringOptional-Proxy login username.
passwordstringOptional-Proxy login password.
RtmEncryptionConfig

An RtmEncryptionConfig instance configures encryption properties for the client. Once encryption mode and key are properly set, all messages and states are automatically encrypted and decrypted by the client.

Info

Once encryption is enabled, all users must use the same encryption mode and key. Otherwise, data cannot be exchanged.

RtmEncryptionConfig includes the following properties:

PropertyTypeRequiredDefaultDescription
encryptionModeRtmEncryptionModeOptionalnoneEncryption mode. See RtmEncryptionMode.
encryptionKeystringOptional-Custom encryption key. No length limit. Agora recommends using a 32-byte key.
encryptionSaltnumber[]OptionalnullCustom encryption salt. Must be 32 bytes. Agora recommends generating it with OpenSSL on the server.
RtmPrivateConfig

An RtmPrivateConfig instance configures properties required for private deployment.

PropertyTypeRequiredDefaultDescription
serviceTypeRtmServiceTypeOptionalnoneService type. See RtmServiceType.
accessPointHostsstring[]Optional-Array of server addresses. Supports domain names or IP addresses.
accessPointHostsCountnumberOptional0Number of server addresses.

Basic usage

const rtmConfig = new RtmConfig({
    encryptionMode : EncryptionMode.AES_256_GCM,
    salt : yourSalt,
    cipherKey : "yourCipherKey",
    presenceTimeout : 300,
    logUpload : true,
    logLevel : "debug",
    cloudProxy : false,
    useStringUserId : false,
    privateConfig: {
        serviceType: ["MESSAGE", "STREAM"]
    },
    heartbeatInterval: 5
});

createAgoraRtmClient

Description

Call the createAgoraRtmClient method to create and initialize an RTM client instance.

Info

  • You must create and initialize the client instance before calling any other RTM APIs.
  • To distinguish users and devices, ensure that userId is globally unique and remains unchanged during the user or device lifecycle.

Method

You can create and initialize an instance as follows:

createAgoraRtmClient(config: RtmConfig): RTMClient
ParameterTypeRequiredDefaultDescription
configRtmConfigYes-RTM client configuration. See RtmConfig.

Basic usage

const rtm = createAgoraRtmClient(
    new RtmConfig({
        userId: uid,
        appId: appId,
    })
);

Return value

Returns an RTM client instance for calling other RTM APIs.

Event Listener

Description

RTM supports seven types of event notifications, as shown in the table below:

Event TypeDescription
messageReceives all message event notifications from the subscribed Message Channels and Topics.
presenceReceives all Presence event notifications from the subscribed Message Channels and joined Stream Channels.
topicReceives all Topic change event notifications from joined Stream Channels.
storateReceives all Channel Metadata event notifications from subscribed Message Channels and joined Stream Channels, and User Metadata event notifications from subscribed users.
lockReceives all Lock event notifications from subscribed Message Channels and joined Stream Channels.
linkstateReceives event notifications about client network connection state changes.
tokenPrivilegeWillExpireReceives event notifications when the client token is about to expire.

Add Listener

You can add an event listener object during initialization or call the addEventListener method at any point during the app lifecycle to add one or more event listeners.

Add Listener

You can call the addEventListener method to listen for specific event notifications. See the sample code below:

 // Add the message event listener

 // Message
rtm.addEventListener("message", event => {
    const channelType = event.channelType; // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName; // The channel from which this message originates
    const topic = event.topicName; // The Topic from which this message originates, valid when channelType is "STREAM"
    const messageType = event.messageType; // Message type: "STRING" or "BINARY"
    const customType = event.customType; // User-defined type
    const publisher = event.publisher; // Message publisher
    const message = event.message; // Message payload
    const timestamp = event.timestamp; // Event timestamp
});

 // Presence
rtm.addEventListener("presence", event => {
    const action = event.eventType; // Action type: 'SNAPSHOT', 'INTERVAL', 'JOIN', 'LEAVE', 'TIMEOUT', 'STATE_CHANGED', 'OUT_OF_SERVICE'
    const channelType = event.channelType; // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName; // The channel from which this event originates
    const publisher = event.publisher; // The user who triggered this event
    const states = event.stateChanged; // User state payload, only for stateChanged event
    const interval = event.interval; // Interval payload, only for interval event
    const snapshot = event.snapshot; // Snapshot payload, only for snapshot event
    const timestamp = event.timestamp; // Event timestamp
});

 // Topic
rtm.addEventListener("topic", event => {
    const action = event.evenType; // Action type: 'SNAPSHOT', 'JOIN', 'LEAVE'
    const channelName = event.channelName; // The channel from which this event originates
    const publisher = event.userId; // The user who triggered this event
    const topicInfos = event.topicInfos; // Topic information payload
    const totalTopics = event.totalTopics; // Total number of topics
    const timestamp = event.timestamp; // Event timestamp
});

 // Storage
rtm.addEventListener("storage", event => {
    const channelType = event.channelType; // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName; // The channel from which this event originates
    const publisher = event.publisher; // The user who triggered this event
    const storageType = event.storageType; // Storage category: 'USER' or 'CHANNEL'
    const action = event.eventType; // Action type: "SNAPSHOT", "SET", "REMOVE", "UPDATE", or "NONE"
    const data = event.data; // Payload: 'USER_METADATA' or 'CHANNEL_METADATA'
    const timestamp = event.timestamp; // Event timestamp
});

 // Lock
rtm.addEventListener("lock", event => {
    const channelType = event.channelType; // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName; // The channel from which this event originates
    const publisher = event.publisher; // The user who triggered this event
    const action = event.evenType; // Action type: 'SET', 'REMOVED', 'ACQUIRED', 'RELEASED', 'EXPIRED', 'SNAPSHOT'
    const lockName = event.lockName; // The lock affected
    const ttl = event.ttl; // Time-to-live of this lock
    const snapshot = event.snapshot; // Snapshot payload
    const owner = event.owner; // Owner of this lock
    const timestamp = event.timestamp; // Event timestamp
});

 // Link State Change
rtm.addEventListener('linkState', event => {
    const currentState = event.currentState;
    const previousState = event.previousState;
    const serviceType = event.serviceType;
    const operation = event.operation;
    const reason = event.reason;
    const reasonCode = event.reasonCode;
    const affectedChannels = event.affectedChannels;
    const unrestoredChannels = event.unrestoredChannels;
    const timestamp = event.timestamp;
    const isResumed = event.isResumed;
});

 // Token Privilege Will Expire
rtm.addEventListener("tokenPrivilegeWillExpire", (channelName) => {
    const channelName = channelName; // The channel whose token will expire
});

Remove Listener

If you no longer need to listen for a specific event but still want to keep other event listeners, you can call the removeEventListener method to remove the specified event listener.

rtm.removeEventListener("tokenPrivilegeWillExpire", yourhandler);

RtmClient

login

Description

After creating and initializing an RTM instance, you need to call the login operation to log in to the RTM service. A successful login establishes a persistent connection between the client and the RTM server, allowing the client to access RTM resources properly.

Info

Once a user successfully logs in to the RTM service, the application's PCU (Peak Concurrent Users) will increase, which affects your billing.

Method

You can log in to the RTM system using the following method:

login(options?: LoginOptions): Promise<LoginResponse>;
ParameterTypeRequiredDefaultDescription
optionsobjectRequired-Login options.

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
tokenstringOptional-The Token used to initialize the RTM client.
- If your project has enabled Token authentication, you can provide a Temporary Token or a server-generated RTM Token. See Client Authentication and Deploying an RTM Token Server for details.
- If your project has not enabled Token authentication, you may leave this field empty or provide the App ID of a project with RTM service enabled.

Basic usage

try {
    const result = await rtm.login({ token: "your_token" });
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a LoginResponse type:

type LoginResponse {
    timestamp: number; // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

logout

Description

When you no longer need to use the service, you can log out by calling the logout method. This operation affects the PCU metric in your billing.

Method

You can log out using the following method:

logout(): Promise<LogoutResponse>;

Basic usage

try {
    const result = await rtm.logout();
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a LogoutResponse type:

type LogoutResponse {
    timestamp: number; // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

User authentication

Authentication refers to the process of verifying a user's identity before they access your system. When users use Agora services, such as joining an audio/video call or logging into the signaling system, Agora uses a Token for authentication.

RTM provides three types of channels: Message Channel, User Channel, and Stream Channel. Each channel type requires a different kind of Token:

  • For Message Channel or User Channel: You only need to pass an RTM Token (Token with RTM service enabled) when calling the login method to log in to the RTM system.
  • For Stream Channel: In addition to using an RTM Token for authentication, you must also pass an RTC Token (Token with RTC service enabled) when calling the join method to join a Stream Channel.

The maximum validity period of a Token is 24 hours. Agora recommends that you renew the Token before it expires. This document describes how to renew a Token.

renewToken

Description

Calls the renewToken method to renew a Token.

Different parameters are required depending on the type of Token being renewed:

  • RTM Token: Only the token parameter is required.
  • RTC Token: Both token and channelName parameters are required.

To ensure timely Token renewal, Agora recommends that you listen for the tokenPrivilegeWillExpire callback. See Event Listener for details. Once the event listener is successfully added, the SDK triggers the tokenPrivilegeWillExpire callback 30 seconds before the RTM Token expires, notifying the user that the Token is about to expire. Upon receiving this callback, you can regenerate the RTM Token on your server and call the renewToken method to pass the new RTM Token to the SDK.

Method

You can call the renewToken method as follows:

renewToken(
    token: string,
    options?: RenewTokenOptions
): Promise<RenewTokenResponse>;
ParameterTypeRequiredDefaultDescription
tokenstringYes-The newly generated Token.
optionsobjectNo-Token renewal options.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
channelNamestringOptional-Channel name. Required when renewing an RTC Token.

Basic usage

rtmClient.addEventListener('tokenPrivilegeWillExpire', async (channelName) => {
    if (!channelName){
 // RTM Token is about to expire
        const newToken = "<Your new token>";
        await rtmClient.renewToken(newToken);
    }
});

Return value

If the method call succeeds, it returns a RenewTokenResponse type:

type RenewTokenResponse = {
    timestamp: number // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

Components and hooks

Components

RTMProvider

This component provides Context to its child components, allowing all components within children to access the client prop you pass in.

Props

PropTypeDefaultDescription
clientRTMClientRequiredThe RTMClient object created using the React Native SDK's createAgoraRtmClient.
childrenReactNativeNodeNoneThe React Native nodes to render.

Basic usage

function App({ children }) {
    const [client] = useState(() => createAgoraRtmClient(
        new RtmConfig({
            userId: uid,
            appId: appId,
        })
    ));
    return <RTMProvider client={client}>{children}</RTMProvider>;
}

Hooks

useLogin

Logs in to the RTM service. Logs in when the component is ready and automatically logs out when the component is unmounted.

Parameters

NameTypeRequiredDescription
clientRTMClientYesThe RTMClient object created using the React Native SDK's createAgoraRtmClient.
loginOptionsLoginOptionsYesLogin options. See login for details.

Basic usage

useLogin(client, { token: "your_token" });

useRtm

Retrieves the RTMClient object.

Parameters

NameTypeRequiredDescription
clientRTMClient | nullNoThe RTMClient object created using the React Native SDK's createAgoraRtmClient.

Return value

Returns an RTMClient object.

Basic usage

const rtmClient = useRtm();

useRtmEvent

Registers a listener for a specific event on the RTMClient object.

  • Registers the specified event listener when the component is mounted.
  • Removes the event listener when the component is unmounted.

Parameters

NameTypeRequiredDescription
clientRTMClientYesThe RTMClient object created using the React Native SDK's createAgoraRtmClient.
eventstringYesThe name of the event. For supported events, see Add Listener.
listenerFunctionYesCallback function that is invoked when the specified event is triggered.

Basic usage

useRtmEvent(client, 'message', (message: MessageEvent) => {
 // your code
});

Channels

A channel is a management mechanism for data transmission in the RTM real-time network. Any user who subscribes to or joins a channel can receive messages and events transmitted in the channel within 100 milliseconds. RTM allows clients to subscribe to hundreds or even thousands of channels. Most RTM APIs perform sending, receiving, encryption, and other operations based on channels.

Based on Agora's capabilities, RTM channels are categorized into three types to match different application scenarios:

  • Message Channel: Follows the industry-standard Pub/Sub (publish/subscribe) model. Channels do not need to be created in advance. You can send and receive messages in a channel by subscribing to it. There is no limit to the number of publishers and subscribers in a channel.
  • User Channel: Enables point-to-point messaging based on the Pub/Sub model. Users do not need to subscribe to a channel. You can send a message by specifying the user ID, and receive messages by simply listening to the message event.
  • Stream Channel: Follows a room-based observer pattern similar to that used in the industry. Users must create and join a channel before sending and receiving messages. Channels can contain multiple Topics, and messages are organized and managed through Topics.

subscribe

Description

RTM provides capabilities for message, status, and event change notifications. By setting up event listeners, you can receive messages and events from the channels you have subscribed to. For how to add and configure event listeners, see the Event Listener section.

By calling the subscribe method, the client can subscribe to a Message Channel and start receiving messages and event notifications from that channel. After the method is successfully called, users who subscribe to the channel and have enabled Presence event listening will receive a presence event of type remoteJoinChannel. See Event Listener for details.

Info

This method applies to Message Channels only.

Method

You can call the subscribe method as follows:

subscribe(
    channelName: string,
    options?: SubscribeOptions
): Promise<SubscribeResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-The name of the channel.
optionsobjectNo-Subscription options for the channel.

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
withMessagebooleanOptionaltrueWhether to subscribe to message event notifications in the channel.
withPresencebooleanOptionaltrueWhether to subscribe to Presence event notifications in the channel.
beQuietbooleanOptionalfalseWhether to subscribe to the channel silently. When set to true, the behavior is as follows:
- You can still receive event notifications from other users in the channel.
- Other users in the channel will not receive notifications when you subscribe/unsubscribe to the channel or set/get/delete temporary states.
- You will not appear in the result of the getOnlineUsers method.
- Channels you silently subscribe to will not appear in the result of the getUserChannels method.
withMetadatabooleanOptionalfalseWhether to subscribe to Storage event notifications in the channel.
withLockbooleanOptionalfalseWhether to subscribe to Lock event notifications in the channel.

Basic usage

const options ={
    withMessage : true,
    withPresence : true,
    beQuiet : false,
    withMetadata : false,
    withLock : false
};
try {
    const result = await rtm.subscribe("chat_room", options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, the SDK returns a SubscribeResponse type:

type SubscribeResponse = {
    timestamp : number // Reserved field
    channelName : string // Name of the channel in this operation
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

unsubscribe

Description

If you no longer need to follow a channel, you can call the unsubscribe method to unsubscribe from it. After a successful unsubscription, other users who have subscribed to the channel and enabled event listening will receive a presence event of type remoteLeaveChannel. See Event Listener for details.

Info

This method applies to Message Channels only.

Method

You can call the unsubscribe method as follows:

unsubscribe(channelName: string): Promise<UnsubscribeResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-The name of the channel.

Basic usage

try {
    const result = await rtm.unsubscribe("chat_room");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, the SDK returns a UnsubscribeResponse type:

type UnsubscribeResponse = {
    timestamp : number // Reserved field
    channelName : string // Name of the channel in this operation
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

createStreamChannel

Description

Before using a Stream Channel, you need to call the createStreamChannel method to create an RTMStreamChannel instance. After the instance is successfully created, you can call its related methods such as joining the channel, leaving the channel, sending Topic messages, and subscribing to Topic messages.

Info

This method applies to Stream Channels only.

Method

You can call the createStreamChannel method as follows:

createStreamChannel(channelName: string): Promise<RTMStreamChannel>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-The name of the channel.

Basic usage

try{
    const Loc_stChannel = await rtm.createStreamChannel( "Location");
    console.log("Create Stream Channel success!: ");
} catch (status){
    console.log(status);
}

Return value

An RTMStreamChannel instance.

RTMStreamChannel

join

Description

After successfully creating a Stream Channel, you can call the join method to join the Stream Channel.

You must join the channel before performing any channel-related operations. Users who subscribe to the channel and have added event listeners will receive the following event notifications:

  • Local user:
    • A presence event of type snapshot.
    • A topic event of type snapshot.
  • Remote users: A presence event of type remoteJoinChannel.

Info

This method applies to Stream Channels only.

Method

You can call the join method as follows:

join(options?: JoinChannelOptions): Promise<JoinChannelResponse>;
ParameterTypeRequiredDefaultDescription
optionsobjectNo-Options for joining the channel.

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
tokenstringOptional-The token used to join the Stream Channel.
- If your project has token authentication enabled, you can provide an RTC temporary token or a server-generated RTC token.
- If your project does not use token authentication, you can leave this blank or use your App ID that has both RTC and RTM services enabled.
withPresencebooleanOptionaltrueWhether to subscribe to Presence event notifications in the channel.
beQuietbooleanOptionalfalseWhether to join the channel silently. When set to true, the behavior is as follows:
- You can still receive event notifications from other users in the channel.
- Other users in the channel will not receive notifications when you join/leave the channel or set/get/delete temporary states.
- You will not appear in the result of the getOnlineUsers method.
- Channels you silently join will not appear in the result of the getUserChannels method.
withMetadatabooleanOptionalfalseWhether to subscribe to Storage event notifications in the channel.
withLockbooleanOptionalfalseWhether to subscribe to Lock event notifications in the channel.

Basic usage

const options ={
    token : "yourToken",
    withPresence : true,
    beQuiet : false,
    withMetadata : false,
    withLock : false
};
try {
    const result = await stChannel.join(options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, the SDK returns a JoinChannelResponse type:

type JoinChannelResponse = {
    timestamp : number, // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

leave

Description

If you no longer need to stay in a channel, you can call the leave method to leave it. After leaving, you will no longer receive any messages, status updates, or event notifications from the channel. Your publisher role and all Topic subscriptions in that channel will be automatically removed. To restore your previous publisher role and subscriptions, you must call the join method again and manually call joinTopic and subscribeTopic.

After successfully leaving the channel, remote users in the channel will receive a presence event of type remoteLeaveChannel. See Event Listener for details.

Info

This method applies to Stream Channels only.

Method

You can call the leave method as follows:

abstract leave(): Promise<LeaveChannelResponse>;

Basic usage

try{
    const result = await streamChannel.leave();
    console.log(result);
} catch (status){
    console.log(status);
}

Return value

If the method call succeeds, the SDK returns a LeaveChannelResponse type:

export type LeaveChannelResponse = {
    timestamp : number // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

Topics

A Topic is a data stream management mechanism within a Stream Channel. You can use Topics to subscribe to, distribute, and receive event notifications for data streams in a Stream Channel.

Info

Topics exist only in Stream Channels. Before using any related features, you must first create an instance of the RTMStreamChannel object.

RTMStreamChannel

joinTopic

Description

Calling joinTopic registers the user as a publisher to the specified Topic, allowing them to send messages to it. This operation does not affect whether the user is a subscriber to the Topic.

Info

  • RTM currently supports a single client joining up to 8 Topics in the same Stream Channel.
  • Before calling this method, you must create an RTMStreamChannel instance and call the join method to join the channel.

After successfully joining a Topic, users who have subscribed to that Topic and enabled event listening will receive a topic event of type remoteJoinTopic. See Event Listener for details.

Method

You can call the joinTopic method as follows:

joinTopic(
    topicName: string,
    options?: JoinTopicOptions
): Promise<JoinTopicResponse>;
ParameterTypeRequiredDefaultDescription
topicNamestringYes-Name of the Topic.
optionsobjectNo-Reserved parameter.

Basic usage

try {
    const result = await stChannel.joinTopic("gesture", options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a JoinTopicResponse type:

type JoinTopicResponse = {
    timestamp: number, // Reserved field
    topicName: string // Name of the Topic joined
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

publishTopicMessage

Description

The publishTopicMessage method sends a message to a Topic. Users in the channel who have subscribed to the Topic and the publisher will receive the message within 100 milliseconds. To use this method, you must first join the Stream Channel and register as a publisher of the Topic by calling joinTopic.

Messages sent by the user are encrypted with TLS during transmission. Data link encryption is enabled by default and cannot be disabled. You can also enable end-to-end encryption during initialization for higher data security. See Initial Configuration for details.

Method

You can call the publishTopicMessage method as follows:

publishTopicMessage(
    topicName: string,
    message: string | Uint8Array,
    options?: TopicMessageOptions
): Promise<PublishTopicMessageResponse>;
ParameterTypeRequiredDefaultDescription
topicNamestringYes-Name of the Topic.
messagestring | Uint8ArrayYes-Message payload. Supports string and Uint8Array types.
optionsobjectNo-Message options.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
messageTypeRtmMessageTypeNo-RTM message type. Supports binary and string.
sentTsstringNo-Timestamp used to sync with media stream. Only effective if syncWithMedia is set to true when joining the Stream Channel.
customTypestringNo-Custom user-defined field. Only supports string.

Basic usage

Example 1: Send a string message to a specific Topic

try {
    const result = await stChannel.publishTopicMessage("Gesture", "message");
    console.log(result);
} catch (status) {
    console.log(status);
}

Example 2: Send a Uint8Array message to a specific Topic

try {
    const result = await stChannel.publishTopicMessage("Gesture", new Uint8Array(Buffer.from(your_message)));
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a PublishTopicMessageResponse type:

type PublishTopicMessageResponse = {
    timestamp: number, // Reserved field
    topicName: string // Name of the Topic the message was sent to
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

leaveTopic

Description

If you no longer need to publish messages to a Topic, you can call the leaveTopic method to unregister as a publisher, thereby releasing resources. This method does not affect your subscription to the Topic or any operations by other users.

After a successful call, users who subscribe to the channel and have enabled event listening will receive a topic event of type remoteLeaveTopic. See Event Listener for details.

Method

You can call the leaveTopic method as follows:

leaveTopic(topicName: string): Promise<LeaveTopicResponse>;
ParameterTypeRequiredDefaultDescription
topicNamestringYes-Name of the Topic.

Basic usage

try {
    const result = await stChannel.leaveTopic("gesture");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a LeaveTopicResponse type:

type LeaveTopicResponse = {
    timestamp: number, // Reserved field
    topicName: string // Name of the Topic
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

subscribeTopic

Description

After joining a channel, you can call the subscribeTopic method to subscribe to publishers of a Topic in that channel.

subscribeTopic is incremental. For example, if the first call subscribes to [UserA, UserB] and the second call subscribes to [UserB, UserC], the final result is [UserA, UserB, UserC].

Each user can subscribe to up to 50 Topics in the same channel, and up to 64 publishers per Topic.

Method

You can call the subscribeTopic method as follows:

subscribeTopic(
    topicName: string,
    options?: TopicOptions
): Promise<SubscribeTopicResponse>;
ParameterTypeRequiredDefaultDescription
topicNamestringYes-Name of the Topic.
optionsobjectNo-Subscription options.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
usersstring[]No-List of user IDs of publishers to subscribe to. If not set, the SDK randomly subscribes to up to 64 users.
userCountnumberNo0Number of publishers to subscribe to.

Basic usage

Example 1: Subscribe to specific publishers in a Topic

var UIDs = ["zhangsan", "lisi", "wangwu"];
try {
    const result = await rtm.subscribeTopic("Gesture", { users: UIDs });
    console.log(result);
} catch (status) {
    console.log(status);
}

Example 2: Randomly subscribe to 64 publishers in a Topic

try {
    const result = await stChannel.subscribeTopic("Gesture");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a SubscribeTopicResponse type:

type SubscribeTopicResponse = {
    succeedUsers: string[], // List of users successfully subscribed to
    failedUsers: string[], // List of users failed to subscribe to
    timestamp: number, // Reserved field
    topiclName: string // Name of the Topic subscribed to
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

unsubscribeTopic

Description

If you are no longer interested in a Topic or no longer need to subscribe to one or more publishers in a Topic, you can call the unsubscribeTopic method to unsubscribe from the Topic or specific publishers.

Method

You can call the unsubscribeTopic method as follows:

unsubscribeTopic(
    topicName: string,
    options?: TopicOptions
): Promise<UnsubscribeTopicResponse>;
ParameterTypeRequiredDefaultDescription
topicNamestringYes-Name of the Topic.
optionsobjectNo-Options for unsubscribing. If not set, unsubscribes from the entire Topic.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
usersstring[]No-List of user IDs of publishers to unsubscribe from. If not set, unsubscribes from the entire Topic.
userCountnumberNo0Number of publishers to unsubscribe from.

Basic usage

Example 1: Unsubscribe from specific publishers in a Topic

try {
    const result = await rtm.unsubscribeTopic("Gesture", { users: ["Tony", "Bo"] });
    console.log("unsubscribe Topic success: ", result);
} catch (status) {
    console.log("unsubscribe Topic failed: ", result);
}

Example 2: Randomly unsubscribe from 64 publishers in a Topic

try {
    const result = await rtm.unsubscribeTopic("Gesture");
    console.log("unsubscribe topic success: ", result);
} catch (status) {
    console.log("unsubscribe topic failed: ", result);
}

Return value

If the method call succeeds, it returns an UnsubscribeTopicResponse type:

type UnsubscribeTopicResponse = {
    timestamp: number // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

Messages

Sending and receiving messages is one of the core features of the RTM service. Any message sent using RTM will be delivered to any online subscribed user within 100 ms. You can send a message to a single user or broadcast messages to multiple users, depending on your use case.

RTM supports three types of channels: Message Channel, User Channel, and Stream Channel. The main differences between these channel types are as follows:

  • Message Channel: A real-time channel with strong scalability where messages are transmitted through the channel. A local user can call the publish method, set the channelType parameter to message, and provide the channelName to send a message. Remote users can call the subscribe method to subscribe to the channel and receive messages.
  • User Channel: Sends point-to-point messages to a specified user. A local user can call the publish method, set the channelType to user, and set channelName to the target user's userId to send a message. The target user receives the message via the message event notification.
  • Stream Channel: A stream-based channel where users must first join the channel and then join a Topic. Messages are transmitted through Topics. A local user can call the publishTopicMessage method to send messages to a Topic. Remote users can call the subscribeTopic method to subscribe to the Topic and receive messages.

This document describes how to send and receive messages in Message Channels and User Channels.

publish

Description

You can directly call the publish method to send a message to all online users subscribed to the specified channel. You can still send messages to a channel even if you haven't subscribed to it.

Info

The following practices can help improve message delivery reliability:

  • Keep the message payload under 32 KB. Otherwise, the message will fail to send.
  • The maximum message sending rate to a single channel is 60 QPS. If the rate exceeds this limit, some messages may be dropped. Lower rates are preferred when possible.

After the method is successfully called, the SDK triggers a message event notification. Users who have subscribed to the channel and enabled event listening will receive this notification. See Event Listener for details.

Method

You can call the publish method as follows:

publish(
    channelName: string,
    message: string | Uint8Array,
    options?: PublishOptions
): Promise<PublishResponse>;
ParameterTypeRequiredDefaultDescription
messagestring / Uint8ArrayYes-The message payload. Supports both string and Uint8Array types.
channelNamestringYes-- To send a message to a Message Channel, provide the channel name.
- To send a message to a User Channel, provide the user ID.
optionsobjectNo-Message options.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
channelTypeRtmChannelTypeNomessageChannel type. See Channel Type.
messageTypeRtmMessageTypeNobinaryMessage type. See Message Type.
customTypestringNo-Custom user-defined field. Only supports string.
storeInHistorybooleanNofalseWhether to store the message in history. If true, the message will be stored and can be retrieved using the getMessages method.

Basic usage

Example 1: Send a string message to a specified Message Channel and store it in history

try {
    const result = await rtm.publish("my_channel", "Hello world", { channelType: "MESSAGE", storeInHistory: true });
    console.log(result);
} catch (status) {
    console.log(status);
}

Example 2: Send a Uint8Array message to a specified Message Channel and store it in history

try {
    const result = await rtm.publish("my_channel", new Uint8Array(Buffer.from(your_message)), { channelType: "MESSAGE", storeInHistory: true });
    console.log(result);
} catch (status) {
    console.log(status);
}

Example 3: Send a string message to a specified User Channel

try {
    const result = await rtm.publish("user_b", "Hello world", { channelType: "USER" });
    console.log(result);
} catch (status) {
    console.log(status);
}

Example 4: Send a Uint8Array message to a specified User Channel

try {
    const result = await rtm.publish("user_b", new Uint8Array(Buffer.from(your_message)), { channelType: "USER" });
    console.log(result);
} catch (status) {
    console.log(status);
}

Info

After the method is successfully called, the SDK triggers a message event notification. Users who have subscribed to the channel and enabled event listening will receive this notification. See Event Listener for details.

Return value

If the method call succeeds, it returns a PublishResponse type:

type PublishResponse = {
    timestamp: number, // Reserved field
    channelName: string // Channel name
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

RtmHistory

getMessages

Description

If you need to retrieve historical messages from a specified channel, call the getMessages method on the client.

Method

You can call the getMessages method as follows:

getMessages(
    channelName: string,
    channelType: RtmChannelType,
    options?: GetHistoryMessagesOptions
): Promise<GetMessagesResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See RtmChannelType.
optionsobjectYes-Query options. Type: GetHistoryMessagesOptions.

The GetHistoryMessagesOptions type includes the following properties:

PropertyTypeRequiredDefaultDescription
messageCountnumberNo100Maximum number of messages to retrieve in a single query. If the number of messages in the time range exceeds this value, you must call getMessages multiple times.
startlongNo0Start timestamp for historical messages.
endlongNo0End timestamp for historical messages.

Info

The RTM SDK provides start and end parameters that you can set based on your needs:

  • If only start is set, messages older than the start timestamp are returned.
  • If only end is set, messages between the current time and the end timestamp (inclusive) are returned.
  • If both start and end are set, messages between start and end (inclusive) are returned.

Basic usage

const options = { messageCount: 50, start: 0, end: 0 };
try {
    const result = await rtm.history.getMessages("my_channel", "MESSAGE", options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a GetMessagesResponse type:

type GetMessagesResponse = BaseResponse & {
    messageList: HistoryMessage[]; // List of historical messages
    count: number; // Total number of historical messages
    newStart: number; // Timestamp of the next message. If 0, there are no more messages
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

Receiving messages

RTM provides event notifications for messages, status updates, and other changes. By setting up event listeners, you can receive messages and events from subscribed channels. The following example shows how to receive messages from a User Channel:

rtm.addEventListener("message", event => {
    const channelType = event.channelType; // Channel type: "STREAM", "MESSAGE", or "USER"
    const channelName = event.channelName; // Channel name where the message comes from
    const topic = event.topicName; // Topic name, valid only if channelType is "STREAM"
    const messageType = event.messageType; // Message type: "STRING" or "BINARY"
    const customType = event.customType; // User-defined type
    const publisher = event.publisher; // Message publisher
    const message = event.message; // Message payload
    const timestamp = event.timestamp; // Message timestamp
});

For details on how to add and configure event listeners, see the Event Listener section.

Presence

Presence provides the ability to monitor user online and offline status as well as historical state change notifications. With Presence, you can retrieve the following information in real time:

  • Real-time event notifications when users join or leave a specified channel
  • Real-time event notifications when temporary user states are set or changed
  • Query which channels a specific user has joined or subscribed to
  • Query which users have joined a specific channel and their temporary state data

Info

Presence is available for both Message Channels and Stream Channels.

getOnlineUsers

Description

Call the getOnlineUsers method to get real-time information about the number of online users, the list of online users, and their temporary states in a specified channel.

Method

You can call the getOnlineUsers method as follows:

getOnlineUsers(
    channelName: string,
    channelType: RtmChannelType,
    options?: PresenceOptions
): Promise<getOnlineUsersResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
optionsobjectNo-Additional query options.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
includedUserIdbooleanNotrueWhether to include user IDs of online members in the result.
includedStatebooleanNofalseWhether to include temporary state data of online users in the result.
pagestringNo-Page bookmark. If not provided, the SDK returns the first page. Check the return value to see if more pages are available.

Basic usage

const options = {
    includedUserId : true,
    includedState : true,
    page : "yourBookMark"
}
try {
    const result = await rtm.presence.getOnlineUsers("chat_room", "MESSAGE", options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a getOnlineUsersResponse type:

type getOnlineUsersResponse = {
    timestamp: number, // Reserved field
    totalOccupancy: number, // Total number of online users in the channel
    occupants: [{
        states: StateItem[{}],
        userId: string,
        statesCount: number
    }], // List of online users and their temporary state information
    nextPage: string // Bookmark for the next page
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

getUserChannels

Description

In scenarios such as data analysis or app debugging, you may need to know all the channels a specific user has joined or subscribed to. Call the getUserChannels method to retrieve a list of channels the user is currently in.

Method

You can call the getUserChannels method as follows:

getUserChannels(userId: string): Promise<getUserChannelsResponse>;
ParameterTypeRequiredDefaultDescription
userIdstringYes-User ID. If set to an empty string "", the SDK uses the local user's userId.

Basic usage

try {
    const result = await rtm.presence.getUserChannels("Tony");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a getUserChannelsResponse type:

type getUserChannelsResponse = {
    timestamp: number, // Reserved field
    totalChannel: number, // Number of channels the user is in
    channels: [{
        channelName: string, // Name of the channel
        channelType: RtmChannelType // Type of the channel
    }]
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

setState

Description

To meet various business needs for user status, RTM provides the setState method to set custom temporary user states. Users can define states such as score, game status, location, mood, mic status, etc.

Once set successfully, the custom state persists in the channel as long as the user remains subscribed and online. The setState method sets a temporary user state. When the user leaves the channel or disconnects from RTM, the state is lost. To restore the state after rejoining or reconnecting, you must cache the data locally. To persist user state permanently, Agora recommends using the Storage feature's setUserMetadata method instead.

If a user updates their temporary state, RTM triggers a presence event of type remoteStateChanged in real time. You can receive this event by subscribing to the channel and enabling the corresponding event listener.

Method

You can call the setState method as follows:

setState(
    channelName: string,
    channelType: RtmChannelType,
    state: StateItem
): Promise<SetStateResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
stateobjectYes-A JSON object in key-value format. Keys and values must be of type string.

Basic usage

var newState = { "mood": "pumped", "isTyping": false };

try {
    const result = await rtm.Presence.setState("chat_room", "MESSAGE", newState);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a SetStateResponse type:

type SetStateResponse = {
    timestamp: number // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

getState

Description

To get the temporary state of a specified user in a specified channel, call the getState method.

Method

You can call the getState method as follows:

getState(
    userId: string,
    channelName: string,
    channelType: RtmChannelType
): Promise<GetStateResponse>;
ParameterTypeRequiredDefaultDescription
userIdstringYes-User ID.
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.

Basic usage

try {
    const result = await rtm.presence.getState("Tony", "chat_room", "MESSAGE");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a GetStateResponse type:

type GetStateResponse = {
    timestamp: number, // Reserved field
    userId: string, // User ID
    states: object, // Key-value pairs of user state
    statesCount: number // Number of user states
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

removeState

Description

When a temporary user state is no longer needed, you can call the removeState method to delete one or more of your own temporary states. After successful deletion, users who subscribe to the channel and have enabled Presence event listening will receive a presence event of type remoteStateChanged. See Event Listener for details.

Method

You can call the removeState method as follows:

removeState(
    channelName: string,
    channelType: RtmChannelType,
 // Pass in state keys; if omitted, all states will be removed
    options?: RemoveStateOptions
): Promise<RemoveStateResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
optionsobjectNo-Options for removing temporary states. If omitted, all states will be removed by default.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
statesstring[]No-List of state keys to remove. If omitted or an empty array, all states will be removed.

Basic usage

const options = {
    states: ["mode", "Typing"]
}
try {
    const result = await rtm.Presence.removeState("chat_room", "MESSAGE", options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a RemoveStateResponse type:

type RemoveStateResponse = {
    timestamp: number // Reserved field
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

Storage

The Storage feature in RTM provides a dynamic database mechanism that allows developers to dynamically set, store, update, and delete data such as Channel Metadata and User Metadata.

setChannelMetadata

Description

The setChannelMetadata method sets Channel Metadata for a channel (Message Channel or Stream Channel). A channel can only have one set of metadata, but each set can contain one or more Metadata Items. If you call this method multiple times, the SDK will iterate through the Metadata Item key values and process them as follows:

  • If the key values are different, new items are added in the order of the calls.
  • If the key values are the same, the value from the most recent call overwrites the previous one.

After setting the Channel Metadata successfully, users who have subscribed to the channel and enabled event listening will receive a storage event of type channel. See Event Listener for details.

Channel Metadata also supports CAS (Compare And Set) version control. This method provides two independent version control fields, and you can choose one or both depending on your business needs:

  • Use the majorRevision property in options to enable version validation for the entire set of Channel Metadata.
  • Use the revision property in a single Metadata Item in data to enable version validation for that specific item.

When setting Channel Metadata or Metadata Items, you can control whether version validation is enabled using the version properties:

  • If the version property is -1 (default), CAS validation is disabled. If the Channel Metadata or Metadata Item exists, it will be overwritten with the new value; if it does not exist, the SDK will create it.
  • If the version property is a positive integer, CAS validation is enabled. The SDK will update the value only if the version matches; otherwise, it will return an error.

Method

You can call the setChannelMetadata method as follows:

setChannelMetadata(
    channelName: string,
    channelType: RtmChannelType,
    data: Metadata,
    options?: IMetadataOptions
): Promise<SetChannelMetadataResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
dataArray&lt;object&gt;Yes-Array of Metadata Items. Each item is a JSON object with predefined properties. Custom properties are not supported.
optionsobjectNo-Channel Metadata configuration options.

The data object includes the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1
- Returned as the actual version number during read operations.
- Used as a version control switch during write operations:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version matches this value.
itemsMetadataItemOptionalEmpty arrayArray of Metadata Items.
itemCountnumberOptional0Number of Metadata Items.

Each Metadata Item includes the following properties:

class MetaDataItem = {
    key: string, // Metadata Item key
    value: string, // Metadata Item value
    revision: number, // Metadata Item version
    updatedTs: string, // Last updated timestamp
    authorUserId: string, // User ID of the last editor
}

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1Version control switch:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version matches this value.
lockNamestringOptionalEmpty string ''Lock name. Only the user who acquires this lock via the acquireLock method can perform the operation.
addTimeStampbooleanOptionalfalseWhether to record the edit timestamp.
addUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

Basic usage

const data = [
    {
        key : "Apple",
        value : "100",
        revision : 174298200
    },
    {
        key : "Banana",
        value : "200",
        revision : 174298100
    }
];
const options = {
    majorRevision : 174298270,
    lockName: "lockName",
    addTimeStamp : true,
    addUserId : true
};
try {
    const result = await rtm.storage.setChannelMetadata("channel_name", "MESSAGE", data, options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a SetChannelMetadataResponse type:

type SetChannelMetadataResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType // Channel type
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

getChannelMetadata

Description

The getChannelMetadata method retrieves the Metadata of a specified channel.

Method

You can call the getChannelMetadata method as follows:

getChannelMetadata(
    channelName: string,
    channelType: RtmChannelType
): Promise<GetChannelMetadataResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.

Basic usage

try {
    const result = await rtm.storage.getChannelMetadata("channel_name", "MESSAGE");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a GetChannelMetadataResponse type:

type GetChannelMetadataResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    majorRevision: number, // Version number
    items: MetadataItem[], // JSON object containing Metadata Item data
    itemCount: number // Number of Metadata Items
}

Each Metadata Item includes the following properties:

class MetaDataItem = {
    key: string, // Metadata Item key
    value: string, // Metadata Item value
    revision: number, // Metadata Item version
    updatedTs: string, // Last updated timestamp
    authorUserId: string // User ID of the last editor
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

removeChannelMetadata

Description

The removeChannelMetadata method deletes Channel Metadata or an array of Channel Metadata Items.

When deleting, you can control whether version validation is enabled by using the version property as follows:

  • If the version property is set to -1 (default), CAS validation is disabled. If the Channel Metadata or Metadata Item exists, the SDK deletes it; if it does not exist, the SDK returns an error code.
  • If the version property is a positive integer, CAS validation is enabled. If the Channel Metadata or Metadata Item exists, the SDK deletes it only after the version number passes validation; otherwise, the SDK returns an error code.

After successfully deleting Channel Metadata or a Metadata Item, users who subscribe to the channel and have enabled event listening will receive a storage event of type channel. See Event Listener for details.

Method

You can call the removeChannelMetadata method as follows:

removeChannelMetadata(
    channelName: string,
    channelType: RtmChannelType,
    options?: RemoveChannelMetadataOptions
): Promise<RemoveChannelMetadataResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
optionsobjectNo-Channel Metadata configuration options.

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
itemsArray&lt;object&gt;Required-Array of Metadata Items. Each Metadata Item is a JSON object with predefined properties. Custom properties are not supported.
itemCountnumberOptional0Number of Metadata Items.
majorRevisionnumberOptional-1Version control switch:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version matches this value.
lockNamestringOptionalEmpty string ''Lock name. Only the user who acquires this lock via the acquireLock method can perform the operation.
addTimeStampbooleanOptionalfalseWhether to record the edit timestamp.
addUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

Each Metadata Item includes the following properties:

class MetaDataItem = {
    key: string, // Metadata Item key
    value: string, // Metadata Item value
    revision: number, // Metadata Item version
    updatedTs: string, // Last updated timestamp
    authorUserId: string, // User ID of the last editor
}

Basic usage

const data = [
    {
        key : "Apple",
        revision : 174298200
    }
];
const options = {
    data : data,
    majorRevision : 174298270,
};
try {
    const result = await rtm.storage.removeChannelMetadata("channel_name", "MESSAGE", options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a RemoveChannelMetadataResponse type:

type RemoveChannelMetadataResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: string // Channel type
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

updateChannelMetadata

Description

The updateChannelMetadata method updates existing Channel Metadata. Each call can update the entire Channel Metadata or one or more Metadata Items.

After a successful update, users who subscribe to the channel and have enabled event listening will receive a storage event of type channel. See Event Listener for details.

Info

This method cannot operate on Metadata Items that do not exist.

Method

You can call the updateChannelMetadata method as follows:

updateChannelMetadata(
    channelName: string,
    channelType: RtmChannelType,
    data: Metadata,
    options?: IMetadataOptions
): Promise<UpdateChannelMetadataResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See [Channel Type]](enumv#channeltype).
dataArray&lt;object&gt;Yes-Array of Metadata Items. Each item is a JSON object with predefined properties. Custom properties are not supported.
optionsobjectNo-Channel Metadata configuration options.

The data object includes the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1
- Returned as the actual version number during read operations.
- Used as a version control switch during write operations:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version matches this value.
itemsMetadataItemOptionalEmpty arrayArray of Metadata Items.
itemCountnumberOptional0Number of Metadata Items.

Each Metadata Item includes the following properties:

class MetaDataItem = {
    key: string, // Metadata Item key
    value: string, // Metadata Item value
    revision: number, // Metadata Item version
    updatedTs: string, // Last updated timestamp
    authorUserId: string, // User ID of the last editor
}

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1Version control switch:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version matches this value.
lockNamestringOptionalEmpty string ''Lock name. Only the user who acquires this lock via the acquireLock method can perform the operation.
addTimeStampbooleanOptionalfalseWhether to record the edit timestamp.
addUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

Basic usage

const data = [
    {
        key : "Mute",
        value : "false",
        revision : 174298100
    }
];
const options = {
    userId : "Tony",
    majorRevision : 174298270,
    addTimeStamp : true,
    addUserId : true
};
try {
    const result = await rtm.storage.updateUserMetadata(data, options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns an UpdateChannelMetadataResponse type:

type UpdateChannelMetadataResponse = {
    timestamp: number, // Reserved field
    channelName : string, // Channel name
    channelType : RtmChannelType // Channel type
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

setUserMetadata

Description

The setUserMetadata method sets User Metadata. If this method is called multiple times, the SDK will iterate over the key values of the User Metadata Items and handle them according to the following rules:

  • If the key values of the Metadata Items are different, they are added sequentially in the order of the calls.
  • If the key values are the same, the value of the last Metadata set will overwrite the previous one.

Once User Metadata is successfully set, users who subscribe to the Metadata of that user and have enabled event listening will receive an event notification of type user. See Event Listening for details.

User Metadata also introduces CAS (Compare-And-Swap) version control logic. This method provides two independent version control fields, and you can configure either or both depending on your business needs:

  • Use the majorRevision property in options to enable version verification for the entire group of User Metadata.
  • Use the revision property in data to enable version verification for each Metadata Item in the array.

When setting User Metadata, the version attributes determine whether to enable version verification for the current call, following this logic:

  • If the version attribute is set to -1 (default), CAS verification is disabled. If the User Metadata or Metadata Item already exists, the value will be overwritten with the new value; if it does not exist, it will be created.
  • If the version attribute is a positive integer, CAS verification is enabled. If the User Metadata or Metadata Item already exists, the SDK will update the value only if the version matches; otherwise, the SDK will return an error code.

Method Signature

You can call the setUserMetadata method as follows:

setUserMetadata(
    data: Metadata,
    options?: SetOrUpdateUserMetadataOptions
): Promise<SetUserMetadataResponse>;
ParameterTypeRequiredDefaultDescription
dataArray&lt;object&gt;Required-Array of Metadata Items. A Metadata Item is a JSON-formatted object that includes predefined properties. Custom properties beyond the predefined ones are not supported.
optionsobjectOptional-Metadata configuration options.

The data object contains the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1
- Returned as the actual version number during read operations.
- Used as a version control flag during write operations:
- -1: Disable version verification.
- > 0: Enable version verification. The operation only proceeds if the target version matches this value.
itemsMetadataItemOptionalEmpty arrayArray of Metadata Items.
itemCountnumberOptional0Number of Metadata Items.

Each Metadata Item contains the following properties:

class MetaDataItem = {
    key: string, // Key of the Metadata Item
    value: string, // Value of the Metadata Item
    revision: number, // Version number of the Metadata Item
    updatedTs: string, // Timestamp of the last update
    authorUserId: string, // User ID of the last editor
}

The options object contains the following properties:

ParameterTypeRequiredDefaultDescription
userIdstringOptionalCurrent user's userIdUser ID.
majorRevisionnumberOptional-1Version control flag:
- -1: Disable version verification.
- > 0: Enable version verification. The operation only proceeds if the target version matches this value.
lockNamestringOptionalEmpty string ''Lock name. When set, only users who acquire the lock using the acquireLock method can perform the operation.
addTimeStampbooleanOptionalfalseWhether to record the timestamp of the edit.
addUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

Basic usage

const data = [
    {
        key : "Name",
        value : "Tony"
        revision : 174298200
    },
    {
        key : "Mute",
        value : "true",
        revision : 174298100
    }
];
const options = {
    userId : "Tony",
    majorRevision : 174298270,
    addTimeStamp : true,
    addUserId : true
};
try {
    const result = await rtm.storage.setUserMetadata(data, options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a SetUserMetadataResponse type object:

type SetUserMetadataResponse = {
    timestamp: number, // Reserved field
    channelName: string;
    channelType: RtmChannelType
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

getUserMetadata

Description

The getUserMetadata method retrieves the Metadata and User Metadata Items of a specified user.

Method Signature

You can call the getUserMetadata method as follows:

getUserMetadata(
    options?: GetUserMetadataOptions
): Promise<GetUserMetadataResponse>;
ParameterTypeRequiredDefaultDescription
optionsobjectOptional-Metadata configuration options.

The options object contains the following properties:

PropertyTypeRequiredDefaultDescription
userIdstringOptionalCurrent user's userIdUser ID.

Basic usage

try {
    const result = await rtm.storage.getUserMetadata({ userId: "Tony" });
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a GetUserMetadataResponse type object:

type GetUserMetadataResponse = {
    timestamp: number, // Reserved field
    userId : string, // User ID
    itemCount : number, // Number of Metadata Items
    majorRevision : number, // Version number
    items : MetadataItem[] // JSON object containing MetadataItem data
}

Each Metadata Item contains the following properties:

class MetaDataItem = {
    key: string, // Key of the Metadata Item
    value: string, // Value of the Metadata Item
    revision : number, // Version number of the Metadata Item
    updatedTs : string, // Timestamp of the last update
    authorUserId : string, // User ID of the last editor
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

removeUserMetadata

Description

The removeUserMetadata method deletes User Metadata or specific User Metadata Items.

After successful deletion, users who subscribe to the Metadata of that user and have enabled event listening will receive a storage event of type user. See Event Listening for details.

Method Signature

You can call the removeUserMetadata method as follows:

removeUserMetadata(
    options?: RemoveUserMetadataOptions
): Promise<RemoveUserMetadataResponse>;
ParameterTypeRequiredDefaultDescription
optionsobjectOptional-Metadata configuration options. If not provided, all user properties of the current user will be deleted.

The options object contains the following properties:

ParameterTypeRequiredDefaultDescription
userIdstringOptionalCurrent user's userIdUser ID.
dataArray&lt;object>Optional-Array of Metadata Items. A Metadata Item is a JSON object with predefined properties.
Custom properties beyond the predefined ones are not supported.
If this parameter is not provided, all Metadata will be deleted.
majorRevisionnumberOptional-1Version control flag:
- -1: Disable version verification.
- > 0: Enable version verification. The operation only proceeds if the target version matches this value.
lockNamestringOptionalEmpty string ''Lock name. When set, only users who acquire the lock using the acquireLock method can perform the operation.
addTimeStampbooleanOptionalfalseWhether to record the timestamp of the edit.
addUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

The data object contains the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1
- Returned as the actual version number during read operations.
- Used as a version control flag during write operations:
- -1: Disable version verification.
- > 0: Enable version verification. The operation only proceeds if the target version matches this value.
itemsMetadataItemOptionalEmpty arrayArray of Metadata Items.
itemCountnumberOptional0Number of Metadata Items.

Each Metadata Item contains the following properties:

class MetaDataItem = {
    key: string, // Key of the Metadata Item
    value: string, // Value of the Metadata Item
    revision: number, // Version number of the Metadata Item
    updatedTs: string, // Timestamp of the last update
    authorUserId: string // User ID of the last editor
}

Basic usage

const data = [
    {
        key : "Mute",
        revision : 174298100
    }
];
const options = {
    userId: "Tony",
    data : data,
    majorRevision : 174298270
};
try {
    const result = await rtm.storage.removeUserMetadata(options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a RemoveUserMetadataResponse type object:

type RemoveUserMetadataResponse = {
    timestamp: number, // Reserved field
    userId : string, // User ID
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

updateUserMetadata

Description

The updateUserMetadata method updates existing User Metadata or Metadata Items. After a successful update, users who subscribe to the User Metadata and have enabled event listening will receive a storage event of type user. See Event Listener for details.

Info

This method cannot operate on Metadata Items that do not exist.

Method

You can call the updateUserMetadata method as follows:

updateUserMetadata(
    data: Metadata,
    options?: SetOrUpdateUserMetadataOptions
): Promise<UpdateUserMetadataResponse>;
ParameterTypeRequiredDefaultDescription
dataArray&lt;object&gt;Yes-Array of Metadata Items. Each item is a JSON object with predefined properties. Custom properties are not supported.
optionsobjectNo-Metadata configuration options.

The data object includes the following properties:

ParameterTypeRequiredDefaultDescription
majorRevisionnumberOptional-1
- Returned as the actual version number during read operations.
- Acts as a version control switch during write operations:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version number matches this value.
itemsMetadataItemOptionalEmpty arrayArray of Metadata Items.
itemCountnumberOptional0Number of Metadata Items.

Each Metadata Item includes the following properties:

class MetaDataItem = {
    key: string, // Metadata Item key
    value: string, // Metadata Item value
    revision: number, // Metadata Item version number
    updatedTs: string, // Last updated timestamp
    authorUserId: string, // User ID of the last editor
}

The options object includes the following properties:

ParameterTypeRequiredDefaultDescription
userIdstringOptionalCurrent user's userIdUser ID.
majorRevisionnumberOptional-1
- Version control switch:
- -1: Disable version validation.
- > 0: Enable version validation. The operation only proceeds if the target version number matches this value.
lockNamestringOptionalEmpty string ''Lock name. Only the user who acquires this lock via the acquireLock method can perform the operation.
addTimeStampbooleanOptionalfalseWhether to record the edit timestamp.
addUserIdbooleanOptionalfalseWhether to record the user ID of the editor.

Basic usage

const data = [
    {
        key : "Mute",
        value : "false",
        revision : 174298100
    }
];
const options = {
    userId : "Tony",
    majorRevision : 174298270,
    addTimeStamp : true,
    addUserId : true
};
try {
    const result = await rtm.storage.updateUserMetadata(data, options);
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns an UpdateUserMetadataResponse type:

type UpdateUserMetadataResponse = {
    timestamp: number, // Reserved field
    userId : string // User ID
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

subscribeUserMetadata

Description

The subscribeUserMetadata method subscribes to the Metadata of a specified user. After a successful subscription and enabling event listening, you will receive a storage event of type user whenever that user's Metadata changes. See Event Listener for details.

Method

You can call the subscribeUserMetadata method as follows:

subscribeUserMetadata(
    userId: string
): Promise<SubscribeUserMetaResponse>;
ParameterTypeRequiredDefaultDescription
userIdstringYes-User ID.

Basic usage

try {
    const result = await rtm.storage.subscribeUserMetadata("Tony");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a SubscribeUserMetaResponse type:

type SubscribeUserMetaResponse = {
    timestamp: number, // Reserved field
    userId : string // User ID
}

unsubscribeUserMetadata

Description

If you no longer need to receive updates for a user's User Metadata, call the unsubscribeUserMetadata method to unsubscribe.

Method

You can call the unsubscribeUserMetadata method as follows:

unsubscribeUserMetadata(
    userId: string
): Promise<UnsubscribeUserMetaResponse>;
ParameterTypeRequiredDefaultDescription
userIdstringYes-User ID.

Basic usage

try {
    const result = await rtm.storage.unsubscribeUserMetadata("Tony");
    console.log("result");
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns an UnsubscribeUserMetaResponse type:

type UnsubscribeUserMetaResponse = {
    timestamp: number, // Reserved field
    userId : string // User ID
}

Lock

A critical resource can only be used by one process at a time. If multiple processes share a critical resource, they must use mutual exclusion to avoid interfering with each other. RTM provides a complete Lock solution that allows you to manage distributed processes and resolve user contention for shared resources.

Info

The client SDK supports setting, deleting, and revoking locks. We recommend that you control client-side permissions for lock operations based on your business needs.

setLock

Description

You need to configure properties such as the lock name and expiration time (TTL), then call the setLock method. After successful configuration, all users in the channel receive a lockSet type lock event notification. See Event Listener for details.

Method

You can call the setLock method as follows:

setLock(
    channelName: string,
    channelType: RtmChannelType,
    lockName: string,
    options?: SetLockOptions
): Promise<SetLockResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
lockNamestringYes-Lock name.
optionsobjectNo-Lock configuration options.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
ttlnumberNo10Lock expiration time in seconds. Range: [10, 300]. If the user holding the lock goes offline and returns to the channel within the TTL, they can still use the lock. Otherwise, the lock is released and users listening for lock events receive a lockReleased event.

Basic usage

try {
    const result = await rtm.Lock.setLock(
        channel: "my_channel",
        channelType: "STREAM",
        lockName: "my_lock",
        { ttl: 30 }
    );
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a SetLockResponse type:

type SetLockResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    lockName: string // Lock name
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

acquireLock

Description

After configuring a Lock, you can call the acquireLock method on the client to obtain ownership of the lock. Once acquired, other users in the channel receive a lockAcquired type lock event notification. See Event Listener for details.

Method

You can call the acquireLock method as follows:

acquireLock(
    channelName: string,
    channelType: RtmChannelType,
    lockName: string,
    options?: AcquireLockOptions
): Promise<AcquireLockResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
lockNamestringYes-Lock name.
optionsobjectNo-Options for acquiring the lock.

The options object includes the following properties:

PropertyTypeRequiredDefaultDescription
retrybooleanNofalseWhether to retry acquiring the lock until successful or the user leaves the channel.

Basic usage

try {
    const result = await rtm.Lock.acquireLock(
        "chat_room",
        "STREAM",
        "my_lock",
        { retry: false }
    );
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns an AcquireLockResponse type:

type AcquireLockResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    lockName: string // Lock name
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

releaseLock

Description

When a user no longer needs to hold a lock, they can call the releaseLock method to release it. After the lock is released, other users in the channel receive a lockReleased type lock event. See Event Listener for details.

At this point, if another user wants to acquire the lock, they can call acquireLock to compete for it. New users and those with retry enabled have equal priority.

Method

You can call the releaseLock method as follows:

releaseLock(
    channelName: string,
    channelType: RtmChannelType,
    lockName: string
): Promise<ReleaseLockResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
lockNamestringYes-Lock name.

Basic usage

try {
    const result = await rtm.lock.releaseLock(
        "chat_room",
        "STREAM",
        "my_lock"
    );
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a ReleaseLockResponse type:

type ReleaseLockResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    lockName: string // Lock name
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

revokeLock

Description

If a lock is held and you need to ensure your business logic proceeds, you may need to revoke the lock to give other users a chance to acquire it. Call revokeLock to revoke the held lock. After revocation, all users in the channel receive a lockReleased type lock event. See Event Listener for details.

At this point, if another user wants to acquire the lock, they can call acquireLock to compete for it. New users and those with retry enabled have equal priority.

Method

You can call the revokeLock method as follows:

revokeLock(
    channelName: string,
    channelType: RtmChannelType,
    lockName: string,
    owner: string
): Promise<RevokeLockResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
lockNamestringYes-Lock name.
ownerstringYes-User ID of the current lock owner.

Basic usage

try {
    const result = await rtm.lock.revokeLockLock(
        "chat_room",
        "STREAM",
        "my_lock",
        "Tony"
    );
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a RevokeLockResponse type:

type RevokeLockResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    lockName: string // Lock name
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

getLock

Description

If you need to query information such as the number of locks in a channel, their names, owners, and expiration times, call the getLock method on the client.

Method

You can call the getLock method as follows:

getLock(
    channelName: string,
    channelType: RtmChannelType
): Promise<GetLockResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.

Basic usage

try {
    const result = await rtm.lock.getLock("chat_room", "STREAM");
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a GetLockResponse type:

type GetLockResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    totalLocks: string, // Number of locks
    lockDetails: [{
        lockName: string, // Lock name
        owner: string, // Lock owner
        ttl: number // Lock expiration time
    }]
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

removeLock

Description

If you no longer need a specific lock in a channel, you can call the removeLock method to delete it. After successful deletion, all users in the channel receive a lockRemoved type lock event notification. See Event Listener for details.

Method

You can call the removeLock method as follows:

removeLock(
    channelName: string,
    channelType: RtmChannelType,
    lockName: string
): Promise<RemoveLockResponse>;
ParameterTypeRequiredDefaultDescription
channelNamestringYes-Channel name.
channelTypeRtmChannelTypeYes-Channel type. See Channel Type.
lockNamestringYes-Lock name.

Basic usage

try {
    const result = await rtm.Lock.removeLockLock(
        "chat_room",
        "STREAM",
        "my_lock"
    );
    console.log(result);
} catch (status) {
    console.log(status);
}

Return value

If the method call succeeds, it returns a RemoveLockResponse type:

type RemoveLockResponse = {
    timestamp: number, // Reserved field
    channelName: string, // Channel name
    channelType: RtmChannelType, // Channel type
    lockName: string // Lock name
}

If the method call fails, it returns an ErrorInfo type object:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

You can look up the value of the errorCode field in the error code list to understand the cause and find the corresponding solution.

Enumerated types

RtmAreaCode

Access region, indicating the region of the server the SDK connects to.

Enum ValueDescription
cn1: Mainland China.
na2: North America.
eu4: Europe.
as8: Asia excluding Mainland China.
jp16: Japan.
in32: India.
glob4294967295: Global.

RtmChannelType

Channel type.

Enum ValueDescription
none0: Unknown channel type.
message1: Message Channel
stream2: Stream Channel
user3: User Channel

RtmConnectionChangeReason

Reasons for SDK connection state changes.

Enum ValueDescription
rtmConnectionChangedConnecting0: Connecting to the network.
rtmConnectionChangedJoinSuccess1: Successfully joined the channel.
rtmConnectionChangedInterrupted2: Network connection interrupted.
rtmConnectionChangedBannedByServer3: Connection blocked by the server.
rtmConnectionChangedJoinFailed4: SDK failed to join the channel for 20 minutes and stopped retrying.
rtmConnectionChangedLeaveChannel5: Left the channel.
rtmConnectionChangedInvalidAppId6: Invalid App ID.
rtmConnectionChangedInvalidChannelName7: Invalid channel name.
rtmConnectionChangedInvalidToken8: Invalid Token.
rtmConnectionChangedTokenExpired9: Token expired.
rtmConnectionChangedRejectedByServer10: Connection rejected by the server.
rtmConnectionChangedSettingProxyServer11: Reconnecting due to proxy server settings.
rtmConnectionChangedRenewToken12: Token renewal caused connection state change.
rtmConnectionChangedClientIpAddressChanged13: Client IP changed due to network type or carrier. Reconnecting.
rtmConnectionChangedKeepAliveTimeout14: Keep-alive timeout. SDK is reconnecting.
rtmConnectionChangedRejoinSuccess15: Successfully rejoined the channel.
rtmConnectionChangedLost16: Lost connection to the server.
rtmConnectionChangedEchoTest17: Connection state changed due to echo test.
rtmConnectionChangedClientIpAddressChangedByUser18: Client IP changed by user. Reconnecting.
rtmConnectionChangedSameUidLogin19: Same user ID logged in from another device.
rtmConnectionChangedTooManyBroadcasters20: Too many broadcasters in the channel.
rtmConnectionChangedLicenseValidationFailure21: License validation failed.
rtmConnectionChangedCertificationVerifyFailure22: Server certificate verification failed.
rtmConnectionChangedStreamChannelNotAvailable23: Stream Channel does not exist.
rtmConnectionChangedInconsistentAppid24: App ID does not match Token.
rtmConnectionChangedLoginSuccess10001: Successfully logged in to RTM system.
rtmConnectionChangedLogout10002: Logged out of RTM system.
rtmConnectionChangedPresenceNotReady10003: Presence service not ready. You need to call login again and reinitialize SDK operations.

RtmConnectionState

SDK connection state.

Enum ValueDescription
disconnected1: Disconnected from server.
connecting2: Connecting to server.
connected3: Connected to server.
reconnecting4: Reconnecting to server.
failed5: Failed to connect to server.

RtmEncryptionMode

Encryption mode.

Enum ValueDescription
none0: No encryption.
aes128Gcm1: AES 128-bit GCM encryption.
aes256Gcm2: AES 256-bit GCM encryption.

RtmLockEventType

Lock event types.

Enum ValueDescription
none0: Unknown state.
snapshot1: Lock snapshot when joining the channel.
lockSet2: Lock set.
lockRemoved3: Lock removed.
lockAcquired4: Lock acquired.
lockReleased5: Lock released.
lockExpired6: Lock expired.

RtmLogLevel

Log output level.

Enum ValueDescription
none0x0000: No logs.
info0x0001: Logs at fatal, error, warn, and info levels. Recommended.
warn0x0002: Logs at fatal, error, and warn levels.
error0x0004: Logs at fatal and error levels.
fatal0x0008: Logs only fatal level.

RtmMessagePriority

Message priority.

Enum ValueDescription
highest0: Highest priority.
high1: High priority.
normal4: Normal priority.
low8: Low priority.

RtmMessageQos

QoS level for Topic messages.

Enum ValueDescription
unordered0: Messages are not ordered.
ordered1: Messages are ordered.

RtmMessageType

Message type.

Enum ValueDescription
binary0: Binary type.
string1: String type.

RtmPresenceEventType

Presence event type.

Enum ValueDescription
none0: Unknown status.
snapshot1: Presence snapshot when joining the channel.
interval2: When the number of users in the channel reaches a threshold, real-time notifications become interval-based.
remoteJoinChannel3: Remote user joined the channel.
remoteLeaveChannel4: Remote user left the channel.
remoteTimeout5: Remote user timed out.
remoteStateChanged6: Remote user’s temporary state changed.
errorOutOfService7: Presence not enabled when joining the channel.

RtmLinkOperation

Operation type.

Enum ValueDescription
login0: Login.
logout1: Logout.
join2: Join Stream Channel.
leave3: Leave Stream Channel.
serverReject4: Rejected by server.
autoReconnect5: Auto reconnect.
reconnected6: Reconnected.
heartbeatLost7: Heartbeat timeout.
serverTimeout8: Server timeout.
networkChange9: Network change.

RtmLinkState

Link connection state.

Enum ValueDescription
idle0: Initial state.
connecting1: Connecting.
connected2: Connected.
disconnected3: Disconnected.
suspended4: Suspended.
failed5: Failed.

RtmLinkStateChangeReason

Reason for link state change.

Enum ValueDescription
unknown0: Unknown reason.
login1: Logging in.
loginSuccess2: Login successful.
loginTimeout3: Login timed out.
loginNotAuthorized4: Login not authorized.
loginRejected5: Login rejected.
relogin6: Relogin.
logout7: Logout.
autoReconnect8: Auto reconnect.
reconnectTimeout9: Reconnect timed out.
reconnectSuccess10: Reconnect successful.
join11: Joining channel.
joinSuccess12: Joined channel successfully.
joinFailed13: Failed to join channel.
rejoin14: Rejoin channel.
leave15: Left channel.
invalidToken16: Invalid Token.
tokenExpired17: Token expired.
inconsistentAppId18: App ID mismatch.
invalidChannelName19: Invalid channel name.
invalidUserId20: Invalid user ID.
notInitialized21: SDK not initialized.
rtmServiceNotConnected22: RTM service not connected.
channelInstanceExceedLimitation23: Channel instance limit exceeded.
operationRateExceedLimitation24: Operation rate limit exceeded.
channelInErrorState25: Channel in error state.
presenceNotConnected26: Presence service not connected.
sameUidLogin27: Same user ID logged in.
kickedOutByServer28: Kicked out by server.
keepAliveTimeout29: Keep-alive timeout.
connectionError30: Connection error.
presenceNotReady31: Presence service not ready.
networkChange32: Network change.
serviceNotSupported33: Service not supported.
streamChannelNotAvailable34: Stream Channel not available.
storageNotAvailable35: Storage service not available.
lockNotAvailable36: Lock service not available.
loginTooFrequent37: Login operation too frequent.

RtmProtocolType

Message transport protocol type.

Enum ValueDescription
tcpUdp0: TCP and UDP.
tcpOnly1: TCP only. Both environments use TCP.

RtmServiceType

Service type.

Enum ValueDescription
noneBasic services, including Message Channel, User Channel, Presence, Storage, and Lock.
messageMessage Channel service.
streamStream Channel service.

Info

To use all RTM services, you can use bitwise operations to combine multiple service types.

RtmProxyType

Proxy type.

Enum ValueDescription
none0: Proxy disabled.
http1: HTTP proxy enabled.
cloudTcp2: TCP Cloud Proxy enabled.

RtmStorageEventType

Storage event type.

Enum ValueDescription
none0: Unknown event type.
snapshot1: Triggered when a user first subscribes to Channel Metadata or User Metadata, or joins a channel.
set2: Triggered when calling setChannelMetadata or setUserMetadata. Only returned in incremental update mode.
update3: Returned when calling methods that add, update, or delete Channel Metadata or User Metadata.
remove4: Triggered when calling removeChannelMetadata or removeUserMetadata. Only returned in incremental update mode.

RtmStorageType

Storage type.

Enum ValueDescription
none0: Unknown type.
user1: User Metadata event.
channel2: Channel Metadata event.

RtmTopicEventType

Topic event type.

Enum ValueDescription
none0: Unknown event type.
snapshot1: Snapshot of Topics when joining a channel.
remoteJoinTopic2: Remote user joined the Topic.
remoteLeaveTopic3: Remote user left the Topic.

Troubleshooting

Refer to the following information for troubleshooting API calls.

ErrorInfo

When you call an RTM React Native API and an error occurs, the SDK throws an object of type ErrorInfo, which contains the following properties:

type ErrorInfo = {
    error: boolean;        // Whether the operation failed
    reason: string;        // Name of the API that triggered the error
    operation: string;     // Operation code
    errorCode: number;     // Error code
};

The errorCode and reason fields report the error code and the API name, respectively.

Error code tables

Refer to the table below for possible causes and solutions:

CodeNameDescription
0okCall succeeded.
-10002notLoginThe user is not logged in to the RTM system, timed out, or logged out before calling the API. Please log in to the RTM system first.
-10003invalidAppIdInvalid App ID:
- Check whether the App ID is correct.
- Check whether the App ID has RTM service enabled.
-10004invalidEventHandlerInvalid event handler.
-10005invalidTokenInvalid Token. Check whether the Token Provider generates an RTM Token.
-10006invalidUserIdInvalid user ID:
- Check if the username is empty.
- Check if the username contains illegal characters.
-10008invalidChannelNameInvalid channel name:
- Check if the channel name is empty.
- Check if the channel name contains illegal characters.
-10009tokenExpiredThe Token has expired. You need to call the logout method to log out of RTM, create an RTM instance with a new Token, and call login to log in again.
-10010loginNoServerResourcesServer resource limit reached. Try logging in again.
-10011loginTimeoutLogin timed out. Check if the network is stable and switch to a stable network environment. If you're on an internal network, verify that your firewall allows the correct domain names and ports.
-10012loginRejectedSDK login rejected by the server:
- Check if the App ID has RTM service enabled.
- Check if the Token or userId is banned.
-10013loginAbortedSDK login interrupted due to unknown issues:
- Check if the network is stable and switch to a stable environment.
- The same userId may have logged in from another device.
-10015loginNotAuthorizedNo RTM service permission. Possible reasons:
- RTM service not enabled in the console.
- Service is overdue.
- Account is banned.
-10016inconsistentAppidApp ID used for login or channel join is inconsistent.
-10017duplicateOperationDuplicate operation.
-10018instanceAlreadyReleasedRTMClient or RTMStreamChannel instance already released.
-10019invalidChannelTypeInvalid channel type. The SDK supports the following types only:
- MESSAGE: Message Channel
- STREAM: Stream Channel
- USER: User Channel
-10020invalidEncryptionParameterInvalid encryption parameters:
- Check if the encryption key is a string.
- Check if the salt is a Uint8Array of 32 bytes.
- Check if the encryption mode matches the key and salt.
-10021operationRateExceedLimitationAPI call rate for Channel Metadata or User Metadata exceeded. Keep it under 10 calls per second.
-10022serviceNotSupportedUnsupported service type. Check if the service type set in RtmServiceType is correct. This error is only for private deployment features.
-10023loginCanceledLogin operation canceled. Possible reasons:
- You called login again before the previous call completed.
- You called logout before login completed.
-10025notConnectedRTM server not connected. This error occurs when calling message subscription, Metadata, or Lock APIs without a connection.
-10026renewTokenTimeoutToken renewal timed out.
-11001channelNotJoinedUser has not joined the channel:
- The user is offline, has disconnected, or has not joined the channel.
- Verify that the userId is spelled correctly.
-11002channelNotSubscribedUser has not subscribed to the channel:
- The user is offline, has disconnected, or has not joined the channel.
- Verify that the userId is spelled correctly.
-11003channelExceedTopicUserLimitationThe number of users subscribed to the Topic exceeds the limit.
-11005channelInstanceExceedLimitationThe number of created or subscribed channels exceeds the limit.
-11006channelInErrorStateThe channel is unavailable. Please recreate the Stream Channel or resubscribe to the Message Channel.
-11007channelJoinFailedFailed to join the channel:
- Check if the number of joined channels exceeds the limit.
- Check if the channel name is invalid.
- Check if the network is disconnected.
-11008channelInvalidTopicNameInvalid Topic name:
- Check whether the Topic name contains illegal characters.
- Check whether the Topic name is empty.
-11009channelInvalidMessageInvalid message. Check whether the message type is valid. RTM only supports string and binary message types.
-11010channelMessageLengthExceedLimitationMessage length exceeds the limit. Check whether the message payload size exceeds the threshold:
- Message Channel: each message must be less than 32 KB.
- Stream Channel: each message must be less than 1 KB.
-11012channelNotAvailableThe Stream Channel feature is not enabled and is currently unavailable. Check whether the Stream Channel feature is enabled in the Console.
-11013channelTopicNotSubscribedThe Topic is not subscribed.
-11014channelExceedTopicLimitationThe number of Topics exceeds the limit.
-11015channelJoinTopicFailedFailed to join the Topic. Check whether the number of joined Topics exceeds the limit.
-11016channelTopicNotJoinedThe Topic is not joined. You must join the Topic before sending messages to it.
-11017channelTopicNotExistThe Topic does not exist. Check whether the Topic name is correct.
-11018channelInvalidTopicMetaThe meta parameter in the Topic is invalid. Check whether the meta parameter exceeds the 256-byte limit.
-11019channelSubscribeTimeoutChannel subscription timed out. Check if the connection is lost.
-11020channelSubscribeTooFrequentChannel subscription operations are too frequent. Make sure you do not subscribe to the same channel more than twice within 5 seconds.
-11021channelSubscribeFailedChannel subscription failed. Check whether the number of subscribed channels exceeds the limit.
-11023channelEncryptMessageFailedMessage encryption failed:
- Check whether the encryption key is valid.
- Check whether the encryption salt is valid.
- Check whether the encryption mode matches the key and salt.
-11024channelPublishMessageFailedMessage publishing failed. Check if the connection is lost.
-11026channelPublishMessageTimeoutMessage publishing timed out. Check if the connection is lost.
-11028channelLeaveFailedFailed to leave the channel. Check if the connection is lost.
-11029channelCustomTypeLengthOverflowThe customType field exceeds the maximum length. The length of customType must be within 32 characters.
-11030channelInvalidCustomTypeThe customType field is invalid. Check whether it contains illegal characters.
-11033channelReceiverOfflineThe remote user is offline when sending a user message:
- Verify that the user ID set in the method is correct.
- Check whether the remote user is logged in and online.
-12001storageOperationFailedStorage operation failed.
-12002storageMetadataItemExceedLimitationThe number of Storage Metadata Items exceeds the limit.
-12003storageInvalidMetadataItemInvalid Metadata Item.
-12004storageInvalidArgumentInvalid argument.
-12005storageInvalidRevisionInvalid Revision parameter.
-12006storageMetadataLengthOverflowMetadata length exceeds the limit.
-12007storageInvalidLockNameInvalid Lock name.
-12008storageLockNotAcquiredThe Lock has not been acquired.
-12009storageInvalidKeyInvalid Metadata key.
-12010storageInvalidValueInvalid Metadata value.
-12011storageKeyLengthOverflowMetadata key length exceeds the limit.
-12012storageValueLengthOverflowMetadata value length exceeds the limit.
-12014storageOutdatedRevisionOutdated Revision parameter.
-12015storageNotSubscribeThe channel is not subscribed.
-12017storageSubscribeUserExceedLimitationThe number of subscribed user Metadata exceeds the limit.
-12018storageOperationTimeoutStorage operation timed out.
-12019storageNotAvailableStorage service is not available.
-13001presenceNotConnectedUser is not connected to the system.
-13003presenceInvalidArgumentInvalid argument.
-13004presenceCachedTooManyStatesThe number of cached temporary user states before joining the channel exceeds the limit.
-13005presenceStateCountOverflowThe number of temporary state key-value pairs exceeds the limit.
-13006presenceInvalidStateKeyInvalid state key.
-13008presenceStateKeySizeOverflowState key length exceeds the limit.
-13010presenceStateDuplicateKeyDuplicate state key.
-13009presenceStateValueSizeOverflowState value length exceeds the limit.
-13011presenceUserNotExistThe user does not exist.
-13012presenceOperationTimeoutPresence operation timed out.
-13013presenceOperationFailedPresence operation failed.
-14001lockOperationFailedLock operation failed.
-14002lockOperationTimeoutLock operation timed out.
-14003lockOperationPerformingLock operation in progress.
-14004lockAlreadyExistThe Lock already exists.
-14005lockInvalidNameInvalid Lock name.
-14006lockNotAcquiredThe Lock has not been acquired.
-14007lockAcquireFailedFailed to acquire the Lock.
-14008lockNotExistThe Lock does not exist.
-14009lockNotAvailableLock service is not available.
-15001historyOperationFailedHistory message operation failed.
-15003historyOperationTimeoutHistory message operation timed out.
-15005historyNotAvailableHistory message service is not available.

If the above measures do not resolve your issue, or if you need assistance with a solution, please compile your request and send it via email to: rtm-support@agora.io. We will contact you as soon as we receive your message.