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.

🚧

This is our new documentation for beta version of QuickBlox React Native SDK. Please contact our Customer Support Team to provide your feedback, suggestions, and requests to improve this page.

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.

QB.chat
  .connect({
    userId: 12345,
    password: 'passw0rd!'
  })
  .then(function () {
    // connected successfully
  })
  .catch(function (e) {
    // some error occurred
  });

Check if connected to Chat server

Check the connection state using the following code snippet.

QB.chat
  .isConnected()
  .then(function (connected) { // boolean
    // handle as necessary, i.e.
    // if (connected === false) reconnect()
  })
  .catch(function (e) {
    // handle error
  });

Disconnect from Chat server

Disconnect from the Chat server using the snippet below.

QB.chat
  .disconnect()
  .then(function () {
    // disconnected successfully
  })
  .catch(function (e) {
    // handle error
  });

Autoreconnect to Chat

The SDK reconnects automatically when the connection to the Chat server is lost. There is a way to disable it and then manage it manually.

QB.settings
  .enableAutoReconnect({ enable: false })
  .then(function () {
    // done
  })
  .catch(function (e) {
    // handle error
  });

Chat in background

To handle chat offline messages correctly do disconnect() when an app goes to background and connect() when an app goes to the foreground.

import { AppState } from 'react-native'
import QB from 'quickblox-react-native-sdk'

AppState.addEventListener('change', trackAppState)

function trackAppState (appState) {
  if (appState.match(/inactive|background/)) {
    QB.chat
      .disconnect()
      .then(function () { /* disconnected successfully */ })
      .catch(function (e) { /* handle error */ });
  } else {
    QB.chat
      .connect({
        userId: 12345,
        password: 'passw0rd!'
      })
      .then(function () { /* connected successfully */ })
      .catch(function (e) { /* some error occurred */ });
    }
}

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 QB.chat.DIALOG_TYPE.CHAT as a type and ID of an opponent you want to create a chatwith.

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.CHAT,
    occupantsIds: [12345]
  })
  .then(function (dialog) {
    // handle as neccessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

Create group dialog

You need to pass QB.chat.DIALOG_TYPE.GROUP_CHAT as a type and IDs of opponents you want to create a chat with.

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.GROUP_CHAT,
    name: 'Group Chat',
    occupantsIds: [12345, 12346, 12347]
  })
  .then(function (dialog) {
    // handle as neccessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

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 just open for everybody. You need to pass QB.chat.DIALOG_TYPE.PUBLIC_CHAT as a type to create a public dialog.

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.PUBLIC_CHAT,
    name: 'Awesome Public Chat'
  })
  .then(function (dialog) {
    // handle as neccessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

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 dialogs, and public dialogs you are subscribed to.

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

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

Update a group dialog name and occupants using updateDialog() method.

const update = {
  dialogId: 'dsfsd934329hjhkda98793j2',
  addUsers: [12340],
  removeUsers: [12345],
  name: 'Team room'
};

QB.chat
  .updateDialog(update)
  .then(function (updatedDialog) {
    // handle as necessary
  })
  .catch(function (e) {
    // handle error
  });

❗️

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

Remove dialog

The following snippet is used to delete a conversation.

QB.chat
  .deleteDialog({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () {
    // dialog was removed successfully
  })
  .catch(function (e) {
    // handle error
  });

❗️

Only dialog owner can remove the conversation for all users.

Chat history

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

QB.chat
  .getDialogMessages({
    dialogId: 'dsfsd934329hjhkda98793j2',
    sort: {
      ascending: false,
      field: QB.chat.MESSAGES_SORT.FIELD.DATE_SENT
    },
    markAsRead: false
  })
  .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
  });

🚧

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

Receive messages

Set up events listener to receive a notification from SDK about a new incoming message as well as handle different connection states, message events, etc.

import { NativeEventEmitter } from 'react-native'
import QB from 'quickblox-react-native-sdk'

const emitter = new NativeEventEmitter(QB.chat);

// every event have following signature
// {
// type - event name (string)
// payload - event data (if any)
// }

function connectionEventHandler(event) {
  // handle connection event
}

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
}

const QBConnectionEvents = [
  QB.chat.EVENT_TYPE.CONNECTED,
  QB.chat.EVENT_TYPE.CONNECTION_CLOSED,
  QB.chat.EVENT_TYPE.CONNECTION_CLOSED_ON_ERROR,
  QB.chat.EVENT_TYPE.RECONNECTION_FAILED,
  QB.chat.EVENT_TYPE.RECONNECTION_SUCCESSFUL,
]

QBConnectionEvents.forEach(eventName => {
  emitter.addListener(eventName, connectionEventHandler)
})

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
)

🚧

Messages from group & public chat dialogs will be received in this callback only after you join the dialogs.

1-1 dialog

To send a message to 1-1 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 */ })

📘

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.

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.

QB.chat
  .joinDialog({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () { /* joined successfully */ })
  .catch(function (e) { /* handle error */ })

Send a message to group/public dialog

To send/receive messages to the group/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 1-1 dialog, group dialog, 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.

Leave group/public dialog

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

QB.chat
  .leaveDialog({ dialogId: 'dsfsd934329hjhkda98793j2' })
  .then(function () { /* left successfully */ })
  .catch(function (e) { /* handle error */ })

Ping user

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

const userId = 12345;

QB.chat
  .pingUser(userId)
  .then(function () { /* success */ })
  .catch(function (error) { /* handle error */ });

Parameters

Required

Description

userId

yes

ID of the user.

Ping server

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

QB.chat
  .pingServer()
  .then(function () { /* success */ })
  .catch(function (error) { /* handle error */ });

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.