> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quickblox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Dialogs

> Learn how to create and manage dialogs.

## Before you begin

1. Register a [QuickBlox account](https://admin.quickblox.com/signin). 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 [Setup](/sdks/js-setup) page for more details.
3. Create a user session to be able to use QuickBlox functionality. See [Authentication](/sdks/js-authentication) page to learn how to do it.
4. Connect to the Chat server. See [Connection](/sdks/js-chat-connection) page to learn how to do it.

Visit [Key Concepts](/docs/key-concepts) page to learn the most important QuickBlox concepts.

## Dialog types

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

* **private dialog** - a dialog between 2 users.
* **group dialog** - a dialog between the specified list of users.
* **public dialog** - an open dialog. Any user from your app can be joined 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 dialog

To create a **private** dialog, you need to set the dialog `type` to `3` and ID of an opponent you want to create a chat with.

```JavaScript JavaScript theme={null}
var params = {
  type: 3,
  occupants_ids: [56]
};

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

To create a **group** dialog for a predefined number of occupants, you need to set the dialog `type` to `2` and IDs of opponents, you want to create a chat with.

```JavaScript JavaScript theme={null}
var params = {
  type: 2,
  occupants_ids: [56, 98, 34],
  name: "Hawaii relax team"
  // Photo can be a link to a file in Content module, Custom Objects module or just a web link.
  // photo: ""
};

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

It's possible to create a **public** dialog, so any user from your application can be joined to it. There is no list of occupants. This dialog is open for everybody. You just need to set the dialog `type` to `1` and a name for a new dialog.

```JavaScript JavaScript theme={null}
var params = {
  type: 1,
  name: "Blockchain trends"
  // Photo can be a link to a file in Content module, Custom Objects module or just a web link.
  // photo: ""
};

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

## Create dialog with custom parameters

A dialog can be extended with additional parameters. These parameters can be used to store additional data. Also, these parameters can be used in dialogs retrieval requests.

To start using additional parameters, create an additional schema of your parameters. This is a custom objects class. Just create an empty class with all fields that you need. These fields will be additional parameters in your dialog. See [this section](/sdks/js-custom-objects) to learn how to create a schema using Custom Objects. Then, specify the parameters defined in the schema in a new dialog.

```JavaScript JavaScript theme={null}
// you should already have created a 'CoolDialog'custom objects class

var params = {
  type: 2,
  name: "My friends",
  data:{
    "class_name":"CoolDialog",
    "category":"friends"
  }
};

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

Set the following fields of the `params`.

| Field | Required | Description                                                                                                         |
| ----- | -------- | ------------------------------------------------------------------------------------------------------------------- |
| type  | yes      | Dialog type. There tree dialog types:- type: 1 - public dialog.- type: 2 - group dialog.- type: 3 - private dialog. |
| name  | yes      | Dialog name.                                                                                                        |
| data  | yes      | Specifies additional parameters in a new dialog.                                                                    |

## Create group dialog with join required

<Warning>
  Available since **QuickBlox JavaScript SDK v2.19.0**. If you use TypeScript, type definitions for `is_join_required` (including the `QBDialogCreateParams` type and runtime validation) are available starting from **v2.23.0**.

  Prior to **server version 2.34.0**, all group dialogs required joining. Starting from **server version 2.34.0**, new applications do not require joining, while existing applications retain the previous behavior. You can change the default in [application settings](/docs/application#set-default-join-required-for-new-group-dialogs).

  If `is_join_required` is explicitly set when creating a dialog, the provided value takes priority over the default in [application settings](/docs/application#set-default-join-required-for-new-group-dialogs).

  Most applications do not need this feature. The default behavior where participants can send and receive real-time messages without joining is recommended for most use cases.
</Warning>

When creating a **group** dialog, you can set the `is_join_required` parameter to `1` to require participants to explicitly join the dialog before they can send or receive real-time messages. This is only needed when you want to restrict real-time messaging in specific dialogs until participants explicitly join.

By default, `is_join_required` is `0` and participants can message without joining. This parameter applies **only to group dialogs** (type `2`). You can change the default in [application settings](/docs/application#set-default-join-required-for-new-group-dialogs).

```JavaScript JavaScript theme={null}
var params = {
  type: 2,
  occupants_ids: [56, 98, 34],
  name: "Hawaii relax team",
  is_join_required: 1
};

QB.chat.dialog.create(params, function(error, dialog) {
  if (error) {
    console.error(error);
  } else {
    var isJoinRequired = dialog.is_join_required;
    console.log("is_join_required:", isJoinRequired);
  }
});
```

The value of `is_join_required` must be `0` or `1`. Invalid values (e.g., `2`, `'yes'`, `-1`) are silently ignored and the dialog is created without this parameter, using the default from [application settings](/docs/application#set-default-join-required-for-new-group-dialogs).

<Note>
  Changing `is_join_required` via `QB.chat.dialog.update()` is **not supported** in the SDK. The parameter can only be set when creating a dialog. To change `is_join_required` for an existing dialog, use the [Server API](/reference/update-dialog) directly.
</Note>

## Check if join required for group dialog

<Info>
  The `is_join_required` field is available starting from **QuickBlox JavaScript SDK v2.19.0**. See [Create group dialog with join required](/sdks/js-chat-dialogs#create-group-dialog-with-join-required) for details.
</Info>

You can get the `is_join_required` value for any group dialog:

```JavaScript JavaScript theme={null}
var isJoinRequired = dialog.is_join_required;
```

## Join group dialog

<Info>
  Starting from **QuickBlox JavaScript SDK v2.19.0**, joining a group dialog is required only when `is_join_required` is set to `1` for a dialog. See [Create group dialog with join required](/sdks/js-chat-dialogs#create-group-dialog-with-join-required) for details.
</Info>

If `is_join_required` is set to `1` for a group dialog, you need to join it by calling the `join()` method before you can send or receive real-time messages. See [this section](/sdks/js-chat-messaging#send-text-message) to learn how to send/receive real-time messages.

You must join the dialog after every new connection or reconnection. If the connection is lost and then restored, whether manually or automatically, you need to call `join()` again for each dialog where `is_join_required` is `1`.

```JavaScript JavaScript theme={null}
var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);
try {
  QB.chat.muc.join(dialogJid, function(error, result) {
    if (error) {
      console.error(error);
    } else {
      // successfully joined
    }
  });
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}
```

| Argument   | Required | Description                                                                                                                                                                                                                                |
| ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| dialogJid  | yes      | Room JID. JID (Jabber ID) of XMPP room in the XMPP server. 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.                                                                                                                                                                            |

<Note>
  You can join a group dialog **only** if your user ID is present in the `occupants_ids` array in the dialog model.

  Your user ID is added to the `occupants_ids` array if you create a dialog **or** you are added to the dialog by another user. See [this section](/sdks/js-chat-dialogs#add-occupants) to learn how to add occupants to the group dialog.
</Note>

## Join public dialog

Before you start chatting in a **public** dialog, you must join it by calling the `join()` method. Unlike group dialogs, joining a public dialog is always required. If you've successfully joined the dialog, you can send/receive real-time messages. See [this section](/sdks/js-chat-messaging#send-text-message) to learn how to send/receive real-time messages.

You must join the dialog after every new connection or reconnection. If the connection is lost and then restored, whether manually or automatically, you need to call `join()` again.

```JavaScript JavaScript theme={null}
var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);
try {
  QB.chat.muc.join(dialogJid, function(error, result) {
    if (error) {
      console.error(error);
    } else {
      // successfully joined
    }
  });
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}
```

## Leave group dialog

You can leave the **group** dialog by calling the `leave()` method. After leaving, you will stop receiving real-time messages from this dialog. You need to join the dialog again to resume receiving real-time messages.

<Info>
  Starting from **QuickBlox JavaScript SDK v2.19.0**, leaving a group dialog is only needed when `is_join_required` is set to `1`. If `is_join_required` is `0`, you do not need to call `leave()`.
</Info>

```JavaScript JavaScript theme={null}
var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);
try {
  QB.chat.muc.leave(dialogJid, function(error) {
    if (error) {
      console.error(error);
    }
  });
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}
```

| Argument   | Required | Description                                                                                                                                                                                                                                |
| ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| dialogJid  | yes      | Room JID. JID (Jabber ID) of XMPP room in the XMPP server. 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.                                                                                                                                                                                       |

<Note>
  When you leave a group dialog, your user ID is still present in the `occupants_ids` array in the dialog model. The dialog will still appear in the list of dialogs and you will still have access to the chat history.

  To remove yourself from the group dialog, use the `update()` method. See [this section](/sdks/js-chat-dialogs#remove-occupants) to learn how to remove occupants from the group dialog.
</Note>

## Leave public dialog

You can leave the **public** dialog by calling the `leave()` method. After leaving, you will stop receiving real-time messages from this dialog. You need to join the dialog again to resume receiving real-time messages.

```JavaScript JavaScript theme={null}
var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialog._id);
try {
  QB.chat.muc.leave(dialogJid, function(error) {
    if (error) {
      console.error(error);
    }
  });
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}
```

## Retrieve online users

You can get a list of online users from the dialog. Call the `listOnlineUsers()` method to get the list of online users who are joined to the dialog. As a result, an array of user IDs is returned.

```JavaScript JavaScript theme={null}
var dialogId = "...";
var dialogJid = QB.chat.helpers.getRoomJidFromDialogId(dialogId);

try {
  QB.chat.muc.listOnlineUsers(dialogJid, function(users) {

  });
} catch (e) {
  if (e.name === 'ChatNotConnectedError') {
    // not connected to chat
  }
}
```

Let's see, how the `listOnlineUsers()` method is used with regard to the dialog type.

| Capabilities          | Public | Group | Private |
| --------------------- | ------ | ----- | ------- |
| Retrieve online users | ✗      | ✓     | ✗       |

<Note>
  You can retrieve online users from the group dialog **only** if you are joined to it.
</Note>

## Retrieve list of dialogs

It's common to request all your dialogs on every app login. The request below will return all **private**, **group**, and **public** dialogs created before the current date, sorted in descending order by the `created_at` field, and limited to 10 dialogs on the page.

```JavaScript JavaScript theme={null}
let params = {
  created_at: {
    lt: Date.now()/1000
  },
  sort_desc: 'created_at',
  limit: 10
};

QB.chat.dialog.list(params, function(error, dialogs) {

});
```

| Argument   | Required | Description                                            |
| ---------- | -------- | ------------------------------------------------------ |
| params     | no       | Specifies param fields that should be set.             |
| function() | yes      | A callback function that an accepts error and dialogs. |

If you want to retrieve only dialogs updated after some specific date time and order the search results, you can apply operators. This is useful if you cache dialogs somehow and do not want to obtain the whole list of your dialogs on every app start. Thus, you can apply [search](/sdks/react-native-chat-dialogs#search-operators) and [sort](/sdks/react-native-chat-dialogs#sort-operators) operators to the list of dialogs on the page so that it is easier to view specific dialogs.

If you want to get a paginated list of dialogs or just a count of dialogs from the server, you can set the following fields of the `filter`:

| Field | Required | Description                                                                                                       |
| ----- | -------- | ----------------------------------------------------------------------------------------------------------------- |
| skip  | no       | Skip N records in search results. Useful for pagination. Default (if not specified): **0**. Should be an Integer. |
| limit | no       | Limit search results to N records. Useful for pagination. Default value: **100**.                                 |

### Search operators

You can use search operators to get more specific search results. The request below will return a list of all **private** and **group** dialogs.

```JavaScript JavaScript theme={null}
let params = {
  type: {
    in: [2,3]
  }
};

QB.chat.dialog.list(params, function(error, dialogs) {

});
```

Here are the search operator that you can use to search for the exact data that you need.

| Search operators | Applicable to types  | Applicable to fields                                | Description                                          |
| ---------------- | -------------------- | --------------------------------------------------- | ---------------------------------------------------- |
| lt               | number, string, date | last\_message\_date\_sent, created\_at, updated\_at | **Less Than** operator.                              |
| lte              | number, string, date | last\_message\_date\_sent, created\_at, updated\_at | **Less Than** or **Equal** to operator.              |
| gt               | number, string, date | last\_message\_date\_sent, created\_at, updated\_at | **Greater Than** operator.                           |
| gte              | number, string, date | last\_message\_date\_sent, created\_at, updated\_at | **Greater Than** or **Equal** to operator.           |
| ne               | number, string, date | \_id, name, last\_message\_date\_sent               | **Not Equal** to operator.                           |
| in               | number, string, date | type, last\_message\_date\_sent, name               | **IN** array operator.                               |
| nin              | number, string, date | last\_message\_date\_sent                           | **IN** array operator.                               |
| all              | number               | occupants\_ids                                      | **ALL** are contained in array.                      |
| ctn              | string               | name                                                | All records that **contain** a particular substring. |

### Sort operators

You can use sort operators to order the search results. The request below will return dialogs created since the beginning of this year and sorted in descending order.

```JavaScript JavaScript theme={null}
let params = {
  created_at: {
    gte: (new Date(new Date().getFullYear(), 0, 1))/1000
  },
  sort_desc: 'sort_desc'
};

QB.chat.dialog.list(params, function(error, dialogs) {

});
```

Here are the sort operators that you can use to order search results.

| Sort operator | Applicable to types | Applicable to fields                             | Description                                                               |
| ------------- | ------------------- | ------------------------------------------------ | ------------------------------------------------------------------------- |
| sort\_asc     | All types           | id, created\_at, name, last\_message\_date\_sent | Search results will be sorted in ascending order by the specified field.  |
| sort\_desc    | All types           | id, created\_at, name, last\_message\_date\_sent | Search results will be sorted in descending order by the specified field. |

### Aggregation operators

You can use an aggregation operator to count search results. The request below will return a count of all **group** dialogs from the server.

```JavaScript JavaScript theme={null}
let params = {
  type: 2,
	count:1
};
QB.chat.dialog.list(params, function(err, result) {
  if (err) {
    console.log(err);
  } else {
  }
});
```

Here are the aggregation operators you can use to retrieve dialogs.

| Aggregation operator | Description                                                                                             |
| -------------------- | ------------------------------------------------------------------------------------------------------- |
| count                | Count search results. The response will contain only a count of records found. Set count to 1 to apply. |

## Retrieve dialogs by custom parameters

You can retrieve dialogs by custom parameters. The request below will return all **private**, **group**, and **public** dialogs with a given `category` and `class_name`.

```JavaScript JavaScript theme={null}
var filters = {
	data: { // search by custom parameters
    category:'friends',
    class_name:'CoolDialog'
  }
};

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

## Update dialog

You can update the information for a **private**, **group**, and **public** dialog.

```JavaScript JavaScript theme={null}
var dialogId = "5356c64ab35c12bd3b108a41";

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

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

Let's see what capabilities a particular user role has with regard to the dialog type.

| Capabilities             | Public dialog  | Group dialog   | Private dialog |
| ------------------------ | -------------- | -------------- | -------------- |
| Update a dialog name     | Owner          | Owner          | ✗              |
| Update a photo           | Owner          | Owner          | ✗              |
| Update custom parameters | Owner,Occupant | Owner,Occupant | Owner,Occupant |

## Add occupants

Set the `push_all` field to add occupants to the dialog. As a result, the ID of the opponent will be added to the `occupants_ids` array.

```JavaScript JavaScript theme={null}
let
 dialogId = "5356c64ab35c12bd3b108a41",
 toUpdateParams = {
  push_all: { occupants_ids: [97, 789] }
};

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

| Arguments      | Required | Description                                             |
| -------------- | -------- | ------------------------------------------------------- |
| dialogId       | yes      | Dialog ID.                                              |
| toUpdateParams | yes      | Specifies the toUpdateParams fields that should be set. |

Let's see what capabilities a particular user role has with regard to the dialog type.

| Capabilities    | Public dialog | Group dialog   | Private dialog |
| --------------- | ------------- | -------------- | -------------- |
| Add other users | ✗             | Owner,Occupant | ✗              |

## Remove occupants

Set the `pull_all` field to remove occupants from the dialog. As a result, the ID of the opponent will be removed from the `occupants_ids` array.

```JavaScript JavaScript theme={null}
let
 dialogId = "5356c64ab35c12bd3b108a41",
 toUpdateParams = {
  pull_all: { occupants_ids: [97, 789] }
};

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

| Argument       | Required | Description                                             |
| -------------- | -------- | ------------------------------------------------------- |
| dialogId       | yes      | Dialog ID.                                              |
| toUpdateParams | yes      | Specifies the toUpdateParams fields that should be set. |

Let's see what capabilities a particular user role has with regard to the dialog type.

| Capabilities       | Public dialog | Group dialog   | Private dialog |
| ------------------ | ------------- | -------------- | -------------- |
| Remove other users | ✗             | Owner          | ✗              |
| Remove yourself    | ✗             | Owner,Occupant | ✗              |

## Delete dialog

The request below will remove the dialog for a current user, but other users will be still able to chat there.

```JavaScript JavaScript theme={null}
var dialogId = "5356c64ab35c12bd3b108a41";

QB.chat.dialog.delete([dialogId], function(error) {

});
```

Set the `force` to `1` to completely remove the dialog for all users. You can also delete multiple dialogs in a single request.

```JavaScript JavaScript theme={null}
var dialogId = "5356c64ab35c12bd3b108a41";

QB.chat.dialog.delete([dialogId], {force: 1}, function(error) {

});
```

Let's see what capabilities a particular user role has with regard to the dialog type.

| Capabilities                                    | Public | Group          | Private        |
| ----------------------------------------------- | ------ | -------------- | -------------- |
| Delete dialog for all userusing forceparameter. | Owner  | Owner          | Owner          |
| Delete dialog for a current user                | Owner  | Owner,Occupant | Owner,Occupant |

## Get number of unread messages

You can get a number of unread messages from a particular dialog using the `list()` method.

```JavaScript JavaScript theme={null}
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.

```JavaScript JavaScript theme={null}
var params = {
  chat_dialog_ids: ["5356c64ab35c12bd3b108a41"]
};

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

});
```

Set the following fields of the `params`:

| Field             | 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 number of unread messages for each specified dialog will be returned. Also, the total number of unread messages for all dialogs of the user will be returned. |

## Resources

A sequence of steps a user takes to start a dialog by moving through the application lifecycle.

<img src="https://mintcdn.com/quickblox/-4CiPyZYUlxdCa4v/images/8d529c8-javascript-starting-dialog.jpg?fit=max&auto=format&n=-4CiPyZYUlxdCa4v&q=85&s=42034d538baa494a9522bf9496a7ca58" alt="javascript-starting-dialog.jpg" className="centered-image" width="1061" height="2120" data-path="images/8d529c8-javascript-starting-dialog.jpg" />
