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

Use the QB.chat.onMessageListener to receive messages in real-time. The event listener enables the app to listen to the incoming message.

function onMessage(userId, message) {
  
};

QB.chat.onMessageListener = onMessage;

Send text message

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

var dialog = "...";

var message = {
  type: "chat",
  body: "How are you today?",
  extension: {
    save_to_history: 1,
    dialog_id: dialog._id
  },
  markable: 1
};

var opponentId = 78;
try {
  message.id = QB.chat.send(opponentId, message);
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}

//...

QB.chat.onMessageListener = onMessage;

function onMessage(userId, message) {}

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

📘

You need to join the group and public 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.

var message = {
  type: "groupchat",
  body: "How are you today?",
  extension: {
    save_to_history: 1,
    dialog_id: dialog._id
  },
  markable: 1
};

var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);
try {
  message.id = QB.chat.send(dialogJid, message);
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}

//...

QB.chat.onMessageListener = onMessage;

function onMessage(userId, message) {}
ArgumentRequiredDescription
dialogJidyesRoom JID. JID (Jabber ID) of XMPP room in the XMPP server. Empty for a privatе dialog. Generated automatically by the server after dialog creation.

You can get JID from the dialog ID. The JID format is the following: <app_id>-<dialog_id>@muc.chat.quickblox.com
messageyesSpecifies message fields that should be set.

📘

Make sure to set the save_to_history: 1 to save the message on the server. If you set save_to_history: 0, 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 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.

// for example, a file from HTML form input field
var inputFile = $("input[type=file]")[0].files[0];

var fileParams = {
  name: inputFile.name,
  file: inputFile,
  type: inputFile.type,
  size: inputFile.size,
  public: false
};
QB.content.createAndUpload(fileParams, function(error, result) {
  if (!error) {
    // prepare a message
    var message = {
      type: dialog.type === 3 ? "chat" : "groupchat",
      body: "[attachment]",
      extension: {
        save_to_history: 1,
        dialog_id: dialog._id,
        attachments: [{ id: result.uid, type: "image" }]
      }
    };

    // send the message
    // ...
  }
});

If you are running Node.js environment, the following code snippet can be used to access a file.

const fs = require("fs");

var imagePath = __dirname + "/dog.jpg";

fs.stat(imagePath, function (statError, stats) {
  if (statError) {
    throw statError;
  }
  fs.readFile(imagePath, function (readError, data) {
    if (readError) {
      throw readError;
    }
    var fileParams = {
      file: data,
      name: "image.jpg",
      type: "image/jpeg",
      size: stats.size,
    };

    // upload
    // ...
  });
});

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.

QB.chat.onMessageListener = function(userId, message) {
  if (message.extension.hasOwnProperty("attachments")) {
    if (message.extension.attachments.length > 0) {
      var fileUID = message.extension.attachments[0].uid;
      var fileUrl = QB.content.privateUrl(fileUID);
      var imageHTML = "<img src='" + fileUrl + "' alt='photo'/>";
    }
  }
};

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 message. 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.

var message = {
  type: "groupchat",
  body: "How are you today?",
  extension: {
    save_to_history: 1,
    customParam1: "book",
    customParam2: "21",
  },
};

try {
  QB.chat.send(jidOrUserId, message);
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}
ArgumentRequiredDescription
jidOrUserIdyesUser ID or Room JID. JID (Jabber ID) of XMPP room in the XMPP server. Empty for a privatе dialog. Generated automatically by the server after dialog creation.

You can get JID from the dialog ID. The JID format is the following: <app_id>-<dialog_id>@muc.chat.quickblox.com.
messageyesSpecifies message fields that should be set.

Set the following fields of the message:

FieldRequiredDescription
typenoMessage type. Possible values: chat and groupchat.
bodynoA message text.
extensionnoExtra data. Specify any key-value pairs. In each pair, the key and value are both string values.

Set save_to_history as true to save the message on the server.

Retrieve chat history

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

var dialogId = "5356c64ab35c12bd3b108a41";
    
var params = {
  chat_dialog_id: dialogId,
  sort_desc: 'date_sent',
  limit: 100,
  skip: 0
};

QB.chat.message.list(params, function(error, messages) {
    
});

🚧

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.

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 fields of the params:

Pagination parameterDescription
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

You can use sort operators to order the search results.

Sort operatorApplicable to typesDescription
sort_ascAll typesSearch results will be sorted in ascending order by the specified field.
sort_descAll typesSearch results will be sorted in descending order by the specified field.

Update message

Update the message text using the update() method.

var messageId = '5f3a7fd75799727266000001';
var updateParams = {
  chat_dialog_id: '5f3166c4a0eb47592eab07aa',
  message: 'Message updated!'
};
QB.chat.message.update(messageId, updateParams, function (error) {
  // if error occurred - error will be returned
});
ArgumentRequiredDescription
messageIdyesID of the message being updated.
updateParamsyesSpecifies key-value fields that should be updated.
function()yesSpecifies the callback function which receives the response from the QuickBlox server for the updating request.

Delete message

Any user in the occupantIDs can delete a message from the dialog. As a result, the message will be deleted from the current user history, without affecting the histories of other users.

The owner of the dialog can completely remove messages from all users' histories. This is achieved by setting the force to 1.

var params = {
  force: 1 // remove message from all users' histories
};
QB.chat.message.delete(messageId, params, function(error, result) {

});

Set the following fields of the params:

ArgumentRequiredDescription
messageIdyesID of the message.
paramsyesSpecifies params fields that should be set.

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. Enable it using the CONFIG object and then call the init() method. See this section to learn how to enable the stream management.

Thus, to handle the event when the message is considered as sent, the onSentMessageCallback() is used.

QB.chat.onSentMessageCallback = function (messageLost, messageSent) {
    
};

🚧

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 QB.chat.onMessageListener. See this section to learn how to add the listener. As a result, when a user receives a message, the SDK receives the onDeliveredStatusListener() callback.

QB.chat.onDeliveredStatusListener = function(messageId, dialogId, userId) {
    
}

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

var params = {
  messageId: "557f1f22bcf86cd784439022",
  userId: 21,
  dialogId: "5356c64ab35c12bd3b108a41",
};
try {
  QB.chat.sendDeliveredStatus(params);
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}

A message can be marked as delivered automatically by the server once a message is successfully delivered to the recipient. Set the markable parameter and pass it within the message to the send() 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 not set or omitted, then you can notify a sender about the delivery receipt using the sendDeliveredStatus() method.

var message = {
  type: "chat",
  body: "How are you today?",
  extension: {
    save_to_history: 1,
    dialog_id: dialog._id,
  },
  markable: 1,
};

var opponentId = 78;
try {
  message.id = QB.chat.send(opponentId, message);
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}

📘

Make sure to understand, that marking-as-delivered operation just confirms the fact of message delivery. The message acquires the delivered status when the onDeliveredStatusListener callback 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 list() 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, use the QB.chat.onMessageListener. See this section to learn how to add the listener. As a result, when a user receives a message, the SDK receives the onReadStatusListener() callback.

QB.chat.onReadStatusListener = function(messageId, dialogId, userId) {
  
};

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

var params = {
  messageId: "557f1f22bcf86cd784439022",
  userId: 21,
  dialogId: "5356c64ab35c12bd3b108a41",
};
try {
  QB.chat.sendReadStatus(params);
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}

📘

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 list() 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 or stopped typing event, use the QB.chat.onMessageListener. See this section to learn how to add the listener. As a result, when a user is typing or stopped typing a message, the SDK receives the onMessageTypingListener() callback.

QB.chat.onMessageTypingListener = function (isTyping, userId, dialogId) {
  if (isTyping) {
    // the user(userId) is typing in the chat(dialogId)
  } else {
    // the user stopped typing
  }
};

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

try {
  QB.chat.sendIsTypingStatus(currentDialog.jidOrUserId);
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}

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

try {
  QB.chat.sendIsStopTypingStatus(currentDialog.jidOrUserId);
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}
ArgumentRequiredDescription
jidyesRoom JID. JID (Jabber ID) of XMPP room in the XMPP server. Pass room JID for type=2 (group dialog). Generated automatically by the server after dialog creation. You can get JID from the dialog ID. The JID format is the following: <app_id>-<dialog_id>@muc.chat.quickblox.com"
dialog).
userIDyesID of the opponent. Pass opponet ID for type=3 (private dialog).

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, they are handled by the onSystemMessageListener callback.

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.

var message = {
  body: "Notification message",
  extension: {
    param1: "value1",
    param2: "value2",
  },
};

var opponentId = 34;
try {
  QB.chat.sendSystemMessage(opponentId, message);
  // or message.id = QB.chat.sendSystemMessage(opponentId, message) if message ID is needed
} catch (e) {
  if (e.name === "ChatNotConnectedError") {
    // not connected to chat
  }
}

QB.chat.onSystemMessageListener = function (receivedMessage) {};
ArgumentDescription
opponentIdID of the opponent.
messageSpecifies system message fields that should be updated.

Set the following fields of the message:

FieldsRequiredDescription
bodynoA system notification text.
extensionnoExtra data. Specify one or more key-value pairs. In each pair, the key and value are both string values.

What’s Next