Skip to main content

LeanMessage Overview

LeanMessage is one of the core features offered by LeanCloud that allows you to quickly implement functions like instant messaging and data synchronization in your app. It is designed with the following goals:

  • Easily add messaging functions to existing apps

    Many of our customers already have their products running smoothly and the only thing they need is to add instant messaging as a bonus feature in their apps. With this in mind, LeanMessage is designed to work independently without interfering your existing account systems. We offer a full collection of UI frameworks and SDKs for you to design and develop messaging functions for browsers (JavaScript), Android, iOS, Unity 3D, and even Windows desktop. In case you need it, we also offer a Python SDK for you to build your custom logic on the server side.

  • Provide extensibility for custom features

    LeanMessage supports common types of messages including text messages, images, audios, videos, locations, and binary data. You can define your own types of messages and build UI for them if you need. You can also implement functions like recalling messages, editing messages, mentioning people, transient messages, delivery receipts, push notifications, and keyword filtering. If you want to build chat rooms that could hold infinite numbers of users, or system conversations that could be used for chatbots, LeanMessage also got you covered.

  • Enhance security with permission management

    When you use LeanMessage, clients and servers use full-duplex communication channels through WebSocket with TLS encrypted transmissions. This ensures that conversations happening within your app cannot be fetched by any unauthorized parties. To further control user activities, you can use our third-party signing mechanism to verify all the sensitive operations before they can be processed. We also provide out-of-the-box role management and blacklist system which works perfectly for scenarios like group chats and chat rooms.

  • Lower costs for maintenance

    With our 24/7 technical support backed by experienced engineers, you can be confident that you are able to integrate our services into your projects with the minimal amount of hassle. Beside this, you are also freed from handling all the errors that might happen to software and infrastructure, as well as upgrading servers when the usage of your app grows quickly.

LeanMessage is already widely used in scenarios like in-app socializing, remote collaboration, customer service, live streaming, and game state synchronization.

Features

Here are the main features offered by LeanMessage:

  • Basic chatting

    • Beside one-on-one chatting and group chats, we also offer open chat rooms that could hold infinite numbers of people, which can be used for scenarios like live streaming and open courses that demand massive discussions in a group. There are also system conversations that could interact with users spontaneously, as well as temporary conversations which work best if you need to build customer service systems. All these functions share the same programming interface.
    • Users can send all kinds of messages, including text messages, images, audios, videos, locations, and binary data. You can develop your own types of messages if you need.
    • History messages are automatically saved on the cloud, which can be retrieved in multiple ways.
  • Advanced messaging features

    • Mentioning people with "@"
    • Recalling and editing messages
    • Getting receipts when messages are delivered and read
    • Muting conversations
    • Sending status updates like "Someone is typing…"
    • Converting messages to push notifications when receivers are offline
    • Setting priorities for messages in chat rooms so that important messages can get quicker delivery
  • Multi device sign-on and message synchronization
    It is becoming a common requirement that users can have their accounts logged in on multiple devices at the same time. Here we allow you to make your own decision whether users can do so and receive messages on all their devices, or they can only log in on a single device at a time.
    What if a user accidentally loses their connection to the Internet? No worries. Our synchronization mechanism guarantees that unreceived messages can always be synchronized to users' devices once the connection is re-established.

  • Group management
    For group chats and chat rooms, users can be nominated as administrators so they can gain additional permissions and help creators manage conversations. Features like inviting users, removing users, blacklisting users, and muting users can also be easily implemented.
    The messages sent through all the conversations can be filtered upon a list of keywords you define or through a plugin you build. This helps your apps comply with the laws and regulations in the area they are operated.

  • Access control
    For any user that wants to send and receive messages, the only thing they need is a clientId identifying them. By decoupling with the account system of the app, it is made easy for you to add LeanMessage into your app and it also helps us better focus on our role as a "messenger".
    We provide third-party signing mechanism that allows you to verify all the operations performed within the app with your own server. This ensures that all the requests sent to the server are legitimate.
    Our SDKs and the cloud use full-duplex communication channels through WebSocket with TLS encrypted transmissions, which further ensures the security of users' conversations.

  • Customizable components
    We offer a number of common features that you can directly use, while you also have the freedom to build your own logic for your special needs:

    • You can verify operations like creating/joining/leaving conversations and retrieving history messages by connecting to your existing account system via our third-party signing mechanism.
    • You can attach hooks to different stages of a message delivery process to implement your custom logic like filtering out certain keywords or customizing push notifications.
    • You can use webhooks to implement message synchronization between LeanCloud and your app's backend.
    • Beside client-side SDKs, we also offer server-side SDKs for you to implement functions under trusted environments.

    Our flexibility and extensibility gives you the power to add more fun to your app beside the basic chatting functions.

Cross-Platform Support

We offer SDKs for the following platforms:

  • Android/Java
  • iOS (both Objective-C and Swift)
  • Browser (JavaScript)
  • Unity
  • Windows desktop
  • Game platforms like Cocos Creator and Egret

Feel free to take a look at their source code on our GitHub page. You are welcome to talk to us if you have any problems or needs.

You may also try out these demos to quickly familiarize yourself with our services:

See LeanCloud Demos for more information.

Core Notions

The concepts mentioned below will be used frequently in our further documentation. It would be helpful if you could familiarize yourself with them.

clientId, User, and Log in

In LeanMessage, each terminal is called a "client". Each client has a unique ID (clientId) that marks itself within an app. Such ID can be generated by your app, but it has to be a string of alphanumeric characters, dashes, and underscores that is not longer than 64 characters and does not begin with a numeric character. For most cases, each client matches an actual user of your app, but it does not mean that only users can act as clients. A probe can also be a client that keeps broadcasting the data collected by it to other people.

To start using LeanMessage, each client needs to build a WebSocket connection to the cloud and register itself with a unique clientId. Such process is called "logging in". Keep in mind that this is separate from the logging in process of the app itself.

By default, LeanCloud allows a clientId to be logged in on multiple devices, as well as multiple clientIds to be logged in on the same device. If you want each user to be logged in on only one device at a time, you can specify a "tag" when logging in so that when duplicated tags are detected on the cloud, the devices that are already logged in will be logged out. You can decide whether to use tags or not based on your actual needs.

After logging in, our SDK will ensure that the connection is always alive and will automatically reconnect if the network status ever changed. On Android devices, the connection is maintained with a service in the background; on iOS devices, the connection will be ended once the app goes into background and push notifications will be used for message delivery.

Conversation

When a user starts chatting with someone after logging in, a Conversation would be formed. In LeanMessage, a conversation contains all the members belonging to it and holds all the messages sent by them, so whenever a client sends a message, it is always sent into a conversation. Before a client could send messages to others, it has to create or join a conversation first and invite other people into it (optional). Only those who are inside a conversation can have access to the messages in it.

When a conversation is created, a record would be added into the _Conversation table which can be found in your app's Dashboard > LeanStorage > Data. Each conversation holds properties like group name, members, as well as custom attributes. The table below shows the relationship between the properties of a conversation and the fields of the _Conversation table:

PropertyTable FieldTypeConstraintDescription
namenameStringOptionalThe name of the group chat.
attributesattrObjectOptionalCustom attributes.
conversationIdobjectIdStringA unique ID generated by the cloud (read only).
creatorcStringThe clientId of the creator (read only).
membersmArrayAll the members of a basic conversation (not applicable for chat rooms or system conversations).
mutemuArrayMembers who muted the conversation. These members will not receive push notifications.
lastMessageAtlmDateThe time the last message is sent.
transienttrBooleanOptionalWhether it is a chat room.
systemsysBooleanOptionalWhether it is a system conversation.
uniqueuniqueBooleanOptionalIf this is true, the same conversation will be reused when a new conversation is created with the same composition of members and unique to be true.

We do have different types of conversations designed for different scenarios. All of them will be stored in _Conversation regardless of their types.

Common Scenarios

Let's first go through some common scenarios where LeanMessage could be used.

  • One-on-one chatting
    This is the conversation between two clients and you can decide whether other users can find it or not (usually it is private). It will be converted to a group chat if new clients are added into it and, again, you can decide if all the members will stay in the same conversation or form a new one.
  • Group chats
    A group chat contains two or more clients and oftentimes members can be added or removed at any time. A name is usually assigned to a group chat, such as "Family", "Friends", or "Co-workers". It is possible for a group chat to have only two or even one member, but it does not make any difference on whether it is considered as a group chat or not. You can decide if group chats are public (such as searchable by name) or not.
  • Chat rooms
    A chat room is similar to a group chat since both of them involve a lot of people. What makes a chat room different is that the number of people in it is often way higher than that of a group chat. In such situation, the number of people in a chat room becomes more meaningful than the specific list of people in it. There is also a difference on how members of a conversation are managed. By opening a chat room, a client joins it, and by closing it, the client leaves it. Therefore, message synchronization and push notifications are disabled for chat rooms.
  • Official accounts and bots
    You can build official accounts into your app and have them broadcast messages to the users who subscribe to them or chat with specific users. You can also implement bots that can automatically reply to messages sent from users.
  • Customer service
    Customers can start temporary conversations with representatives to discuss solutions to their problems. These conversations can be closed once the problems are solved.

LeanMessage offers the following four types of conversations to cover all these scenarios.

Basic Conversation

This is the most commonly used type of conversation that could serve one-on-one chatting and group chats. It offers the following functions:

  • Send and receive messages among members of it
  • Add and remove members (500 maximum) with all the existing members notified
  • Find out who are online
  • Mention members, recall messages, edit messages, send transient messages, get receipts when messages are delivered and read, send will messages, and receive push notifications
  • Receive push notifications when offline and synchronize unreceived messages when online
  • Store message history on the cloud and perform various types of queries on it

Tips:

  • You may assign properties to a conversation to mark if it is an one-on-one chatting or a group chat. You may also mark if a conversation is private or public. Such properties can be stored in Conversation.attributes.
  • To minimize redundancy, you can set unique to be true when creating a conversation with SDK (defaults to true in Java SDK). By doing so, the cloud will check if any existing conversation contains the same group of users and has unique to be true. If so, the existing conversation will be returned, otherwise a new conversation will be created.

Chat Room

This type of conversation is dedicated for chat rooms (it has tr to be true in _Conversation). Similar to a basic conversation, users can create, join, or leave it at any time and all the messages will be stored on the cloud. It is different form a basic conversation on the following basis:

  • No limit on the number of people; does not have a fixed list of members; members are removed once they are offline (field m is ignored)
  • The amount of members can be retrieved instead of the specific list of members
  • No offline messages, push notifications, or delivery receipts
  • No notifications for members joining or leaving
  • Cannot invite or remove people
  • A user can only be in one chat room at each time and will automatically leave the previous one when joining a new one
  • A user has to rejoin a chat room if it becomes offline for more than 30 minutes

Tips:

Although a chat room does not limit the number of people in it, the user experience can be impaired when there are too many people sending a lot of messages. We suggest that you limit the number of people in each chat room to be less than 5,000 and split big chat rooms into small ones if possible.

System Conversation

This type of conversation can be used to build bots, official accounts, service accounts, and in-app notifications (it has sys to be true in _Conversation). It has the following traits:

  • A user subscribes to it by joining and unsubscribes by leaving (field m is ignored)
  • Conversations can only be created on the server side and clients can only subscribe or unsubscribe to the existing conversations
  • Messages can be sent to either all subscribers or specific users
  • The messages sent from users will be stored in the _SysMessage table and cannot be seen by other users
  • You can set up Hook URLs to receive messages from users and reply to them with REST API

Temporary Conversation

This type of conversation does not get stored in the _Conversation table. It is meant for special scenarios with:

  • Short TTL
  • Less members (10 clients maximum)
  • No message history needed

We recommend temporary conversation to be used for customer service. It has the following traits:

  • Members are fixed upon the creation of a conversation and cannot be added or removed afterwards
  • Cannot mute or unmute
  • Cannot update attributes
  • Allow message operations and querying members just like basic conversations

Tips:

Temporary conversations last shorter and do not get stored in the _Conversation table. This reduces the size of data stored in your app and lowers the costs needed as well.

Summary

Type of ConversationScenariosMember ManagementMessage OperationsMessage History
Basic ConversationOne-on-one chatting and group chatsMembers are persisted,
500 members maximum
Only members can send or receive messagesSupported
Chat RoomChat rooms, barrage, and real-time commentsMembers are not persisted,
Users cannot be invited,
No limit on the number of people
Everyone can send messages,
Online users can receive messages
Supported
System ConversationOfficial accounts, bots, system notifications, and custom messagesDoes not have the concept of members,
A list of subscribers can be maintained,
No limit on the number of subscribers
Messages can be sent to subscribers through API,
Webhooks can be set up to handle messages
Supported
Temporary ConversationCustomer serviceFixed membersOnly members can send or receive messagesNot supported

Message

A message is a basic unit for transmitting data within a conversation. Each message can hold at most 5 KB of data in the format of text. There is no requirement on how the text should be formatted and you are free to define your own types of messages based on it.

When sending a message, a parameter can be specified to make it either a normal message or a transient message. A normal message comes with features like delivery receipts, persistent storage, and push notifications, while a transient message cannot be saved, received later, or pushed to offline users. Therefore, status updates like "Someone is typing…" are best sent as transient messages and messages composed by users shall be sent as normal messages.

Our service ensures that a normal message can be delivered for at least once. At the same time, our SDKs are able to filter out duplicate messages. We offer both SDKs and REST API for you to send messages: SDKs are often for clients and REST API is for sending messages from the server side. When using REST API, you can specify the sender of a message and the ID of the target conversation, as well as the receivers of the message if it is sent to a system conversation.

Default Types for Rich Media Messages

We offer a number of predefined JSON-based types (TypedMessage) for rich media messaging, including:

  • Text (TextMessage)
  • Image (ImageMessage)
  • Audio (AudioMessage)
  • Video (VideoMessage)
  • Location (LocationMessage)

The image below shows the inheritance relationships among them: TypedMessage 继承自 Message。TextMessage、ImageMessage、AudioMessage、VideoMessage、LocationMessage 和其他消息类型继承自 TypedMessage。

As mentioned above, rich media messages are based on the JSON format. Therefore, they need to be serialized to a JSON string containing the following properties when sent via the REST API. Client-side SDKs will do the conversion automatically when sending messages.

属性约束说明
_lctypeType of the rich media message
MessageType
Text message-1
Image message-2
Audio message-3
Video message-4
Location message-5
File message-6
以All the types above use negative numbers. Positive numbers are reserved for custom types, and zero is reserved for "no type".
_lctextText description of the rich media message
_lcattrsA JSON string containing custom attributes
_lcfileIf the message contains a file (image, audio, video, generic file),_lcfile would contain the information about that file.
urlThe URL of the file after it is uploaded. Note that the URL in historical messages will not be updated when you bind or re-bind a custom domain name.
objIdOptionalThe objectId of the file in the _File class.
metaDataOptionalFile metadata.

The above properties are common to all types of rich media messages.

Developers can easily extend their own message types based on our framework.

Here we provide some examples of the serialized JSON of built-in rich media messages.

Advanced Features

As mentioned earlier, we offer the following functions beside basic chatting:

  • Mentioning people with "@"
  • Recalling and editing messages
  • Filtering out keywords
  • Getting receipts when messages are delivered and read
  • Muting conversations
  • Sending status updates like "Someone is typing…"
  • Converting messages to push notifications when receivers are offline
  • Setting priorities for messages in chat rooms so that important messages can get quicker delivery

You can read Advanced Messaging Features and Keyword Filtering to learn more about them.

Restrictions

  • In every minute, a client can send at most 60 messages, query history messages for at most 120 times, and perform operations like joining conversations, leaving conversations, logging in, and logging out for at most 30 times. Incoming requests will be rejected if the limits are exceeded (the callbacks implemented with SDK will not be triggered). If you are performing these operations with REST API, the limits will not apply.
  • For each app, at most 160,000 messages can be delivered to all the clients in each second. The messages exceeding the limit will be discarded. Please contact us if your app needs a higher quota.
  • The size of each message (including metadata such as pushData) shall be less than or equal to 5 KB.
  • Each conversation can hold at most 500 people. If you add more than 500 IDs into the m field with LeanStorage API, only the first 500 IDs will be used.
  • The same ID is not supposed to be logged in on too many devices. If we detect that an ID is logged in on more than 5 IP addresses at the same time, this ID will be billed with each IP as an independent user on that day.
  • If a user has more than 50 conversations containing unread messages, the cloud will randomly pick 50 of them and deliver their unread messages (or the amounts of them) to the user when the user logs in. The undelivered messages will not be lost but need to be manually retrieved.
  • If a user has a conversation containing more than 100 offline messages, the former messages will not be automatically delivered when the user logs in and the user will not see the amount of them. The undelivered messages can be manually retrieved.
  • There are request frequency and quantity limitations on invoking LeanMessage-related REST API. See LeanMessage REST API Guide for details.

Lifespan of Conversations

If no message is sent to a conversation (basic conversation, chat room, or system conversation) in the past six months through either SDK or REST API, or none of its fields in the _Conversation table are updated, the conversation will be considered as inactive and will be deleted automatically. Keep in mind that querying messages does not update the _Conversation table, so a conversation that only gets queried will also be seen as inactive.

If you attempt to send a message to a deleted conversation through either SDK or REST API, the error 4401 INVALID_MESSAGING_TARGET will be returned which means that the conversation does not exist anymore. The messages associated with deleted conversations will also be gone.

Active conversations will never get deleted.

Lifespan of Messages

A message will be stored on the cloud for 6 months. This means that you can only query the message history of a conversation in the past 6 months. If you would like to pay to extend the period, please contact us at leancloud-support@xd.com. You may also synchronize the message history to your own server with REST API.

Hooks

See Hooks.

Guides