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.

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 chat with.

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.

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

It will return all your 1-1 dialogs, group dialogs, and public dialogs you are subscribed to.

If you want to retrieve only conversations updated after some specific date time, you can pass the 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

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

❗️

Important note

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

❗️

Important note

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

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.

🚧

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

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
)

🚧

Pay attention

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 */ })

📘

Note

Make sure to specify the saveToHistory: true field to the message. The field is read by the server, and, consequently, the message is stored in the history. If the saveToHistory field is not specified, the message is no longer 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 */ })

📘

Note

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

📘

Note

Make sure to specify the saveToHistory: true field to the message. The field is read by the server, and, consequently, the message is stored in the history. If the saveToHistory field is not specified, the message is no longer 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 */ })

Updated 17 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.