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.

var filters = {};

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

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

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

❗️

Important note

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

❗️

Important note

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

🚧

Pay attention

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

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

🚧

Pay attention

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.

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

📘

Note

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

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

📘

Note

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

📘

Note

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

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 (err) {
  if (err) {
    // 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 (err) {
  if (err) {
    // no pong received
  } else {
    // pong received from user
  }
});

Parameters

Required

Description

userJid

yes

JID of the user.

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 (err) {
  if (err) {
    // 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 5 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.