QuickBlox Documentation

QuickBlox provides powerful Chat API and SDK to add real-time messaging and video calls to your web and mobile apps. Learn how to integrate QuickBlox across multiple platforms and devices. Check out our detailed guides to make integration easy and fast.

Chat

Learn how to enable chat functionality for your app.

Chat API is built on top of real-time (XMPP) protocol. In order to use it you need to setup real-time connection with QuickBlox Chat server and use it to exchange data. By default real-time Chat works over secure TLS connection.

Before you begin

  1. Visit our Key Concepts page to get an overall understanding of the most important QuickBlox concepts.
  2. 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.
  3. Configure QuickBlox SDK for your app. Check out our Setup page for more details.
  4. Create a user session to be able to use QuickBlox functionality. See our Authentication page to learn how to do it.

Connect to Chat server

To connect to Chat server use the code snippet below.

var userCredentials = {
  userId: 4448514,
  password: "awesomepwd"
};

QB.chat.connect(userCredentials, function(error, contactList) {});

Disconnect from Chat server

Disconnect from the Chat server using the snippet below.

QB.chat.disconnect();

QB.chat.onDisconnectedListener = onDisconnectedListener;

function onDisconnectedListener() {
  console.log("onDisconnected");
}

Reconnection

QuickBlox Chat runs over XMPP protocol. To receive messages in a real-time mode, the application should be connected to the Chat over XMPP protocol. The SDK can be reconnected to the Chat server when the connection is lost. There is a way to disable it and then manage it manually. The following 2 callbacks are used to track the state of the connection.

QB.chat.onDisconnectedListener = onDisconnectedListener;
QB.chat.onReconnectListener = onReconnectListener;

function onDisconnectedListener() {}

function onReconnectListener() {}

Dialogs

All chats between users are organized in dialogs. There are 3 types of dialogs:

  • 1-1 dialog - a conversation between 2 users.
  • group dialog - a conversation between the specified list of users.
  • public dialog - an open conversation. Any user from your app can subscribe to it.

You need to create a new dialog and then use it to chat with other users. You also can obtain a list of your existing dialogs.

Create new dialog

Create 1-1 dialog

You need to pass type: 3 and ID of an opponent you want to create a chat with.

var params = {
  type: 3,
  occupants_ids: [56]
};

QB.chat.dialog.create(params, function(error, conversation) {});

Create group dialog

You need to pass type: 2 as a type and IDs of opponents you want to create a chat with.

var params = {
  type: 2,
  occupants_ids: [56, 98, 34],
  name: "Hawaii relax team"
};

QB.chat.dialog.create(params, function(error, conversation) {});

Create public dialog

It's possible to create a public dialog, so any user from your application can subscribe to it. There is no a list with occupants, this dialog is open for everybody. You need to pass type: 1 and a name for a new dialog.

var params = {
  type: 1,
  name: "Blockchain trends"
};

QB.chat.dialog.create(params, function(error, conversation) {});

Retrieve list of dialogs

It's common to request all your conversations on every app login. The request below will return all 1-1 dialogs, group dialog, and public dialogs you are subscribed to.

var filters = {};

QB.chat.dialog.list(filters, function(error, dialogs) {});

Filters

If you want to retrieve only dialogs updated after some specific date time, you can pass the filter. This is useful if you cache dialogs somehow and do not want to obtain the whole list of your dialogs on every app start.

You can apply filters for the following fields:

  • _id (string)
  • type (integer)
  • name (string)
  • last_message_date_sent (integer)
  • created_at (date)
  • updated_at (date)

You can apply sort for the following fields:

  • last_message_date_sent

Filter

Applicable to types

Description

{field_name}

All types

Search records with the field which contains the specified value.

{field_name}[{search_operator}]

All types

Search a record with the field which contains the value according to the specified value and operator.

sort_asc

All types

Search results will be sorted by the specified field in ascending order.

sort_desc

All types

Search results will be sorted by the specified field in descending order.

skip

Integer

Skip N records in search results. Useful for pagination. Default (if not specified): 0.

limit

Integer

Limit search results to N records. Useful for pagination. Default value: 100. If limit is equal to 1, only the last record will be returned.

count

Integer

Count search results. Response will contain only count of records found.

Search operators

Here are the search operators that you can use to retrieve dialogs.

Search operators

Applicable to types

Description

lt

Integer, Float

Less Than operator.

lte

Integer, Float

Less Than or Equal to operator.

gt

Integer, Float

Greater Than operator.

gte

Integer, Float

Greater Than or Equal to operator.

ne

Integer, Float, String, Boolean

Not Equal to operator.

in

Integer, Float, String

IN array operator.

nin

Integer, Float, String

Not IN array operator.

all

Array

ALL are contained in array.

ctn

String

All records that contain a particular substring.

Update dialog

A user can update a group dialog name and occupants using the snippet below.

var dialogId = "5356c64ab35c12bd3b108a41";

var toUpdateParams = {
  name: "Tesla club"
};

QB.dialog.update(dialogId, toUpdateParams, function(error, dialog) {});

❗️

Only group dialog owner can remove other users from a group dialog.

Add/Remove Occupants

To add more occupants use push_all operator. To remove yourself from the conversation use pull_all operator.

var dialogId = "5356c64ab35c12bd3b108a41";

var toUpdateParams = {
  push_all: { occupants_ids: [97, 789] }
};

QB.chat.dialog.update(dialogId, toUpdateParams, function(error, dialog) {});

❗️

Only group dialog owner can remove other users from a group dialog.

Remove dialog

The following snippet is used to delete a dialog.

var dialogId = "5356c64ab35c12bd3b108a41";
    
QB.chat.dialog.delete([dialogId], function(error) {
    
});

🚧

This request will remove this conversation for a current user, but other users still will be able to chat there. Only a group dialog owner can remove the group conversation for all users.

Chat history

Every chat conversation stores its chat history which you can retrieve.

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) {
    
});

🚧

All retrieved chat messages will be marked as read after the request. If you decide not to mark chat messages as read, then make sure to add markAsRead parameter as false to your request.

Filters

If you want to retrieve chat messages that were sent after or before a specific date-time only, you can use the filter. This is useful if you implement pagination for loading messages in your app.

You can apply filters for the following fields:

  • _id (string)
  • message (string)
  • date_sent (timestamp)
  • sender_id (integer)
  • recipient_id (integer)
  • attachments.type (string)
  • updated_at (date)

You can apply sort for the following fields:

  • date_sent

Filter

Applicable to types

Description

{field_name}

All types

Search records with the field which contains the specified value.

{field_name}[{search_operator}]

All types

Search a record with the field which contains the value according to the specified value and operator.

sort_asc

All types

Search results will be sorted by the specified field in ascending order.

sort_desc

All types

Search results will be sorted by the specified field in descending order.

skip

Integer

Skip N records in search results. Useful for pagination. Default (if not specified): 0.

limit

Integer

Limit search results to N records. Useful for pagination. Default value: 100. If limit is equal to 1, only the last record will be returned.

count

Integer

Count search results. Response will contain only count of records found.

Search operators

Here are the search operators that you can use to retrieve messages.

Search operators

Applicable to types

Description

lt

Integer, Float

Less Than operator.

lte

Integer, Float

Less Than or Equal to operator.

gt

Integer, Float

Greater Than operator.

gte

Integer, Float

Greater Than or Equal to operator.

ne

Integer, Float, String, Boolean

Not Equal to operator.

in

Integer, Float, String

IN array operator.

nin

Integer, Float, String

Not IN array operator.

all

Array

ALL are contained in array.

or

Integer, Float, String

All records that contain a value 1 or value 2.

ctn

String

All records that contain a particular substring.

Send/Receive Chat Messages

1-1 dialog

To send a message to 1-1 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;
message.id = QB.chat.send(opponentId, message);

//...

QB.chat.onMessageListener = onMessage;

function onMessage(userId, message) {}

📘

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.

Group/public dialog

Join group/public dialog

Before you start chatting in a group/public dialog, you need to join it by calling join() method.

var dialog = "...";

var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);

QB.chat.muc.join(dialogJid, function(error, result) {});

Argument

Required

Description

dialogJid

yes

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

function()

yes

Specifies a callback function that accepts an error and result.

Send a message to group/public dialog

To send/receive messages to the group/public dialog, use the following code snippet.

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);

message.id = QB.chat.send(dialogJid, message);

//...

QB.chat.onMessageListener = onMessage;

function onMessage(userId, message) {}

Argument

Required

Description

dialogJid

yes

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

message

yes

Specifies message fields that should be set.

📘

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

📘

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.

Leave group/public dialog

You can leave the group/public dialog by calling leave() method.

var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);

QB.chat.muc.leave(dialogJid, function(error) {
    
});

Argument

Required

Description

dialogJid

yes

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

function()

yes

Specifies a callback function that accepts an error.

Unread messages count

You can get a number of unread messages in a particular dialog using the dialog model.

var filters = { limit: 1 };
QB.chat.dialog.list(filters, function(error, dialogs) {
  if (error) {
    // handle error
  } else {
    var dialog = dialogs.items[0];
    var unreadCount = dialog.unread_messages_count;
  }
})

You can also retrieve total unread messages count using unreadCount()
method.

var params = {
  chat_dialog_ids: ["5356c64ab35c12bd3b108a41"]
};

QB.chat.message.unreadCount(params, function(error, result) {
    
});

Parameters

Description

chat_dialog_ids

IDs of dialogs.

  • If chat_dialog_ids are not specified, the total number of unread messages for all dialogs of the user will be returned.
  • If chat_dialog_ids are specified, the total number of unread messages for the specified dialogs will be returned. Also, the total number of unread messages for all dialogs of the user will be returned.

Ping user

QuickBlox SDK can send application-level pings to a user. As a result, you can check if the user is connected to the Chat server.

Ping user by ID

// ping user (by user ID)
QB.chat.ping(userId, function (error) {
  if (error) {
    // no pong received
  } else {
    // pong received from user
  }
});

Parameters

Required

Description

userId

yes

ID of the user.

function()

yes

Specifies a callback function that accepts one argument that specifies what error has happened.

Ping user by JID

// ping user (by user JID)
QB.chat.ping(userJid, function (error) {
  if (error) {
    // no pong received
  } else {
    // pong received from user
  }
});

Parameters

Required

Description

userJid

yes

User JID. JID (Jabber ID) of the user in the in the XMPP server. Assigned automatically by the server upon the login to the Chat. The users will have different JIDs for different apps.

The JID format is the following:
<user_id>-<app_id>@chat.quickblox.com

function()

yes

Specifies a callback function that accepts one argument that specifies what error has happened.

Ping server

QuickBlox SDK can send application-level pings to a server. As a result, you can check if there is a connection with the Chat server.

// ping server (some specific chat server)
var server = 'chat.quickblox.com';
QB.chat.ping(server, function (error) {
  if (error) {
    // no pong received
  } else {
    // pong received from server
  }
});

Parameters

Required

Description

server

no

Custom server address. You can ping a specific chat server. If no server is specified, the server address is taken from the config object. See the Custom endpoints section to learn how to set up custom server endpoints.

function()

yes

Specifies a callback function that accepts one argument that specifies what error has happened.

Set ping timeout

To control how much time it takes to respond to a ping, you should set a pingTimeout. By default, the pingTimeout is 30 seconds. If the response wasn't received within the specified time frame, then the error callback is called.

Set the pingTimeout in seconds, in the CONFIG object. See our Initialize SDK section to learn more about other configuration options.

var APPLICATION_ID = "41";
var AUTH_KEY = "lkjdueksu7392kj";
var AUTH_SECRET = "iiohfdija792hj";
var CONFIG = {
  // other configs
  pingTimeout: 3
};
QB.init(APPLICATION_ID, AUTH_KEY, AUTH_SECRET, CONFIG);

Updated 18 days ago


What's Next

Advanced

Chat


Learn how to enable chat functionality for your app.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.