Messaging

Learn how to send and receive messages, mark messages as delivered or read, etc.

Before you begin

  1. Register a QuickBlox account. This is a matter of a few minutes and you will be able to use this account to build your apps.
  2. Configure QuickBlox SDK for your app. Check out our Setup page for more details.
  3. Create a user session to be able to use QuickBlox functionality. See our Authentication page to learn how to do it.
  4. Connect to the Chat server. See our Connection page to learn how to do it.
  5. Create a dialog. See our Dialogs page to learn how to do it.

Visit our Key Concepts page to get an overall understanding of the most important QuickBlox concepts.

Subscribe message events

Add the event handler to receive messages in real-time. The event handler enables the app to receive message events associated with receiving a message, delivery receipts, and read receipts.

import { NativeEventEmitter } from "react-native";
import QB from "quickblox-react-native-sdk";

const emitter = new NativeEventEmitter(QB.chat);

function receivedNewMessage(event) {
  const { type, payload } = event;
  // handle new message
  // type - event name (string)
  // payload - message received (object)
}

function messageStatusHandler(event) {
  // handle message status change
}

function systemMessageHandler(event) {
  // handle system message
}

function userTypingHandler(event) {
  // handle user typing / stopped typing event
}

emitter.addListener(
  QB.chat.EVENT_TYPE.RECEIVED_NEW_MESSAGE,
  receivedNewMessage
);

emitter.addListener(QB.chat.EVENT_TYPE.MESSAGE_DELIVERED, messageStatusHandler);

emitter.addListener(QB.chat.EVENT_TYPE.MESSAGE_READ, messageStatusHandler);

emitter.addListener(QB.chat.EVENT_TYPE.RECEIVED_SYSTEM_MESSAGE, systemMessageHandler);

emitter.addListener(QB.chat.EVENT_TYPE.USER_IS_TYPING, userTypingHandler);

emitter.addListener(QB.chat.EVENT_TYPE.USER_STOPPED_TYPING, userTypingHandler);

Send text message

To send a message to a private dialog, use the code snippet below.

const message = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  body: 'Hey there!',
  saveToHistory: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* send successfully */ })
  .catch(function (e) { /* handle error */ })

📘

You need to join the public and group dialog by calling the join() method before you start chatting in a dialog. Once the dialog is joined, you can receive/send messages. See this section to learn how to join the dialog.

To send messages to a group or public dialog, use the code snippet below.

const message = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  body: 'Hey there!',
  saveToHistory: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* send successfully */ })
  .catch(function (e) { /* handle error */ })

Use the same code snippet to send/receive messages for private, group, and public dialog.

📘

Make sure to set the saveToHistory as true to save the message on the server. If the saveToHistory is set as false, the message won't be saved on the server. However, the message will be delivered to the user in either case.

Send message with attachment

Chat attachments are supported by the content API. In order to send a chat attachment, you need to upload the file to QuickBlox cloud storage and obtain a link to the file (file UID). Then you need to include this UID into the chat message and send it.

const contentUploadParams = {
  url: "...", // path to file in local file system
  public: false,
};

QB.content
  .upload(contentUploadParams)
  .then(function (file) {
    // create a message
    const message = {
      attachments: [],
      dialogId: "dsfsd934329hjhkda98793j2",
      body: "Hey there!",
      saveToHistory: true,
    };
    // attach file
    message.attachments.push({
      id: file.uid,
      type: file.contentType.includes("image") ? "image" : "file",
    });
    // send a message
  })
  .catch(function (e) {
    /* handle file upload error */
  });

The flow on the receiver's side is the following: when you receive a message, you need to get the file URL to download the file from the cloud storage.

// received message
const { attachments } = message
const [attachment] = attachments
const contentGetFileUrlParams = { uid: attachment.id };

QB.content
  .getPrivateURL(contentGetFileUrlParams)
  .then(function (url) { /* you download file using obtained url */ })
  .catch(function (e) { /* handle error */ });

Send message with extra data

You have an option to extend the message with additional fields. Specify one or more key-value items in the properties. Using these items, you can implement the ability for a user to send self-location information to another user or notification messages signifying that a user has left a group, etc.

const message = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  body: 'How are you today!',
  properties: {
    customParam1: "book",
    customParam2: "21"
  },
  saveToHistory: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* send successfully */ })
  .catch(function (e) { /* handle error */ })

The sendMessage() method accepts one argument of the object type that has the following fields:

FieldRequiredDescription
dialogIdyesThe ID of a dialog.
bodynoA message text.
propertiesnoExtra data. Specify any key-value pairs. In each pair, the key and value are both string values.
saveToHistorynoSpecifies if the message will be saved on the server. Set the saveToHistory as true to save the message on the server.

Retrieve chat history

Every dialog stores its chat history that you can retrieve using the getDialogMessages() method. The request below will return messages for a specific dialog, sorted by the date_sent field in descending order.

const getDialogMessagesParams = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  sort: {
    ascending: false,
    field: QB.chat.MESSAGES_SORT.FIELD.DATE_SENT
  },
  markAsRead: false
};

QB.chat
  .getDialogMessages(getDialogMessagesParams)
  .then(function (result) {
    // result.messages - array of messages found
    // result.skip - number of items skipped
    // result.limit - number of items returned per page
  })
  .catch(function (e) {
    // handle error
  });

🚧

If you want to mark all retrieved chat messages as a read, set the markAsRead parameter as true. If you decide not to mark chat messages as read, just set markAsRead parameter as false or omit the parameter.

If you want to retrieve only messages updated after some specific date time and order the search results, you can apply operators. This is useful if you cache messages somehow and do not want to obtain the whole list of messages on every app start. Thus, you can apply search and sort operators to list messages on the page so that it is easier to view specific messages.

If you want to get a paginated list of messages from the server, you can set the following pagination parameters:

Pagination parametersDescription
skipSkip N records in search results. Useful for pagination. Default (if not specified): 0.
limitLimit search results to N records. Useful for pagination. Default value: 100.

Search operators

You can use search operators to search for the exact data that you need.

Search operatorsApplicable to typesApplicable to fieldsDescription
ltnumber, string, datedate_sent, sender_id, recipient_id, updated_atLess Than operator.
ltenumber, string, datedate_sent, sender_id, recipient_id, updated_atLess Than or Equal to operator.
gtnumber, string, datedate_sent, sender_id, recipient_id, updated_atGreater Than operator.
gtenumber, string, datedate_sent, sender_id, recipient_id, updated_atGreater Than or Equal to operator.
nenumber, string, date_id, message, date_sent, sender_id, recipient_idNot Equal to operator.
innumber, string, datedate_sent, sender_id, recipient_idIN array operator.
ninnumber, string, datedate_sent, sender_id, recipient_idNot IN array operator.
ornumber, string, datedate_sent, sender_id, recipient_idAll records that contain a value 1 or value 2.
ctnstringmessageAll records that contain a particular substring.

Sort operators

Here are the sort options that you can use to order search results.

Sort optionsApplicable to typesDescription
ascendingAll typesSort results in the ascending order by setting the ascending as true.
decsendingAll typesSort results in the descending order by setting the ascending as false.

Check if a message is sent

The message is considered as sent if it has been delivered to the server. To get to know that a message has been delivered to the server, make sure to enable a stream management before connecting to the Chat server. See this section to learn how to enable the stream management.

Thus, you send a message to the server and if no error is returned, it is considered as sent (by default). There is no field for a sent status in the message model.

QB.chat
  .sendMessage(message)
  .then(function () { /* message sent */ })
  .catch(function (e) { /* message is not sent */ });

🚧

You should enable Stream Management before you do the login() because the Stream Management is initialized while Chat login is performed.

The Stream Management defines an extension for active management of a stream between a client and server, including features for stanza acknowledgments.

Mark message as delivered

As a sender, you may want to be informed that a message has been successfully delivered to the recipient. The mark-as-delivered functionality allows to notify the sender about message delivery.

To track the event when the message has been delivered to the user, use the event listener. As a result, when a user receives a message, the SDK receives the QB.chat.EVENT_TYPE.MESSAGE_DELIVERED event.

import { NativeEventEmitter } from "react-native";
import QB from "quickblox-react-native-sdk";

const emitter = new NativeEventEmitter(QB.chat);

function messageDelivered(event) {
  const {
    type, // name of the event (the one you've subscribed for)
    payload, // event data
  } = event;
  const {
    dialogId, // in dialog with id specified
    messageId, // message with id specified
    userId, // was delivered to user with id specified
  } = payload;
  // handle as necessary
}

emitter.addListener(QB.chat.EVENT_TYPE.MESSAGE_DELIVERED, messageDelivered);

Use the markMessageDelivered() method to mark a message as delivered. As a result, the server will notify a sender about the delivery receipt.

const markMessageDeliveredParams = {
  message: {
    id: 'ghtsd934679hjhkda98793t4',
    dialogId: 'dsfsd934329hjhkda98793j2',
    senderId: 12345,
  },
};
QB.chat
  .markMessageDelivered(markMessageDeliveredParams)
  .then(function () {
    /* marked as "delivered" successfully */
  })
  .catch(function (e) {
    /* handle error */
  });

A message can be marked as delivered automatically by the server once a message is successfully delivered to the recipient. Set the markable as true using the sendMessage() method if you want, as a sender, to receive message delivery receipts from other recipients. Thus, the markable parameter enables the sender to request the delivery receipt. It also enables the recipient to confirm the message delivery. However, if markable is false or omitted, then you can notify a sender about the delivery receipt using the markMessageDelivered() method.

const message = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  body: 'Hello!',
  markable: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* message sent */ })
  .catch(function (e) { /* message is not sent */ });

📘

Make sure to understand, that marking-as-delivered operation just confirms the fact of message delivery. The message acquires the delivered status when the QB.chat.EVENT_TYPE.MESSAGE_DELIVERED event is received.

When a message is marked as delivered, the IDs of users who have received the message are stored in the message model, on the server. Thus, you can request a chat history from the server to get to know who received the message using the getDialogMessages() method. See this section to learn how to retrieve chat history.

Mark message as read

As a sender, you may want to be informed that a message has been read by the recipient. The mark-as-read functionality allows to notify the sender that a message has been read.

To track the event when the message has been read by the user, you need to subscribe to this event using the code snippet below. As a result, when a user reads a message, the SDK receives the QB.chat.EVENT_TYPE.MESSAGE_READ event.

import { NativeEventEmitter } from "react-native";
import QB from "quickblox-react-native-sdk";

const emitter = new NativeEventEmitter(QB.chat);

function messageRead(event) {
  const {
    type, // name of the event (the one you've subscribed for)
    payload, // event data
  } = event;
  const {
    dialogId, // in dialog with id specified
    messageId, // message with id specified
    userId, // was delivered to user with id specified
  } = payload;
  // handle as necessary
}

emitter.addListener(QB.chat.EVENT_TYPE.MESSAGE_READ, messageRead);

Use the markMessageRead() method to mark a message as read. As a result, the server will notify a sender about the read receipt.

const markMessageReadParams = {
  message: {
    id: "ghtsd934679hjhkda98793t4",
    dialogId: "dsfsd934329hjhkda98793j2",
    senderId: 12345,
  },
};
QB.chat
  .markMessageRead(markMessageReadParams)
  .then(function () {
    /* marked as "read" successfully */
  })
  .catch(function (e) {
    /* handle error */
  });

📘

When a message is marked as read, the IDs of users who have read the message are stored in the message model, on the server. Thus, you can request a chat history from the server to get to know who read the message using the getDialogMessages() method. See this section to learn how to retrieve chat history.

Send typing indicators

You may want, as a sender, to let the recipient know that you are typing the message or have stopped typing the message. Use typing indicators as a form of chat-specific presence. Typing indicators allow to indicate if users are typing messages in a dialog at the moment.

There are the following typing notifications supported.

  • typing. The user is composing a message. The user is actively interacting with a message input interface specific to this chat session (e.g. by typing in the input area of a chat window).
  • stopped. The user had been composing but now has stopped. The user has been composing but has not interacted with the message input interface for a short period of time (e.g. 30 seconds).

To track the event when the sender is typing the message, use the event listener. As a result, when a sender is typing a message, the SDK receives the QB.chat.EVENT_TYPE.USER_IS_TYPING event.

import { NativeEventEmitter } from "react-native";
import QB from "quickblox-react-native-sdk";

const emitter = new NativeEventEmitter(QB.chat);

function userTypingHandler(event) {
  const {
    type, // name of the event (the one you've subscribed for)
    payload, // event data
  } = event;
  const {
    dialogId, // in dialog with id specified
    userId, // user with id specified is typing
  } = payload;
  // handle as necessary
}

emitter.addListener(QB.chat.EVENT_TYPE.USER_IS_TYPING, userTypingHandler);

To track the event when the sender has stopped typing, use the event listener. Thus, when a sender has stopped typing a message, the SDK receives the QB.chat.EVENT_TYPE.USER_STOPPED_TYPING event.

import { NativeEventEmitter } from "react-native";
import QB from "quickblox-react-native-sdk";

const emitter = new NativeEventEmitter(QB.chat);

function userStoppedTypingHandler(event) {
  const {
    type, // name of the event (the one you've subscribed for)
    payload, // event data
  } = event;
  const {
    dialogId, // in dialog with id specified
    userId, // user with id specified stopped typing
  } = payload;
  // handle as necessary
}

emitter.addListener(
  QB.chat.EVENT_TYPE.USER_STOPPED_TYPING,
  userStoppedTypingHandler
);

To notify a recipient that a sender is typing the message, use the sendIsTyping() method. As a result, the server will notify a recipient about the event.

const isTypingParams = { dialogId: "dsfsd934329hjhkda98793j2" };

QB.chat
  .sendIsTyping(isTypingParams)
  .then(function () {
    /* sent successfully */
  })
  .catch(function (e) {
    /* handle error */
  });

To notify a recipient that a sender had been composing a message but now has stopped, use the sendStoppedTyping() method. As a result, the server will notify a recipient about the event.

const isTypingParams = { dialogId: "dsfsd934329hjhkda98793j2" };

QB.chat
  .sendStoppedTyping(isTypingParams)
  .then(function () {
    /* sent successfully */
  })
  .catch(function (e) {
    /* handle error */
  });)

Send system messages

There is a way to send system messages to other users about some events. For example, a system message can be sent when a user has joined or left a group dialog. These messages are handled over a separate channel and are not be mixed up with regular chat messages. Thus, in order to receive these messages, you should subscribe to the QB.chat.EVENT_TYPE.RECEIVED_SYSTEM_MESSAGE event. See this section to learn how to subscribe to this event.

System messages are also not shown in the dialog history and, consequently, are not stored on the server. This means that these messages will be delivered only to online users. Send system messages using the sendSystemMessage() method.

const systemMessage = {
  recipientId: 1234567,
  properties: {
    notification_type: "1",
    dialog_id: "5d75393ba28f9a17e1cb0f9e",
  },
};

QB.chat.sendSystemMessage(systemMessage);

The sendSystemMessage() method accepts one argument of the object type that has the following fields:

FieldRequiredDescription
recipientIdyesID of the recipient.
propertiesnoExtra data. Specify any key-value pairs. In each pair, the key and value are both string values. You can't specify any object, because it won't be passed as an argument.

What’s Next