# Conversation

## Overview

This section is dedicated to launching and managing chat conversations. You can set up how the list of conversations and new conversations are created and launched.

You can also create a conversation with specific human agents and bots. Also, you can either choose to open the same conversation thread for a particular user every time they come to chat or create a new thread instead.

> Note: All the methods in this section accept `activityContext` since the process invloves launching an Activity. If you are calling the methods in Activity, then use `YourActivity.this` in place of `activityContext`. If you are calling the methods in Fragment, then use `getActivity()` in place of `activityContext`.

## Open conversation

### Conversation screen

Open the conversation screen (where all the conversations are listed in descending order of time of communication) by using the below method:

```
Kommunicate.openConversation(activityContext);
```

If you need a callback when the screen is opened, then use the below method:

```
Kommunicate.openConversation(activityContext, null, new KmCallback() {
                        @Override
                        public void onSuccess(Object message) {
                            Utils.printLog(activityContext, "ChatTest", "Launch Success : " + message);
                        }

                        @Override
                        public void onFailure(Object error) {
                            Utils.printLog(activityContext, "ChatTest", "Launch Failure : " + error);
                        }
                    });
```

### Particular conversation thread

You can open a particular conversation thread screen if you have the conversationId of that particular conversation by using the below method:

```
  KmConversationHelper.openConversation(activityContext, 
                                        true, 
                                        conversationId, 
                                        new KmCallback() {
                @Override
                public void onSuccess(Object message) {
                    
                }

                @Override
                public void onFailure(Object error) {

                }
            });
```

The second parameter in the above method is `skipConversationList`(passed as `true`), pass it 'false' if you would like to show the conversation list after the user presses the back button in the conversation thread. If this parameter is passed 'true' then on pressing the back button, you would be navigated to the activity from where the conversation was launched, thus skipping the conversation list.

## Create conversation

### New conversation

You can create a new conversation as below:

```
     new KmConversationBuilder(activityContext)
                       .setSingleConversation(false) 
                      .createConversation(new KmCallback() {
                        @Override
                        public void onSuccess(Object message) {
                            String conversationId = message.toString();
                        }

                        @Override
                        public void onFailure(Object error) {
                            Log.d("ConversationTest", "Error : " + error);
                        }
                    });
```

If you have the list of your human agents and/or bots and need to create a conversation with them then use the builder as described below:

```
     List<String> agentIds = new ArrayList<>();
     agentIds.add(""); 
     List<String> botIds = new ArrayList<>(); 
     botIds.add(""); 
     
     new KmConversationBuilder(activityContext)
                            .setSingleConversation(false) 
                            .setAgentIds(agentIds) 
                            .setBotIds(botIds) 
                            .createConversation(new KmCallback() {
                        @Override
                        public void onSuccess(Object message) {

                        }

                        @Override
                        public void onFailure(Object error) {

                        }
                    });
```

## Single conversation

You can create a unique conversation every time a particular user comes to chat by employing the below method.

A unique conversation is identified by the list of AGENT\_IDs and BOT\_IDs used to create the conversation. If the same set of IDs are passed to the below method, then the already existing conversation would be returned instead of creating a new conversation. A single unique conversation would be created if you skip the `setSingleConversation` parameter in the builder.

```
       new KmConversationBuilder(activityContext)
                     .createConversation(new KmCallback() {
                        @Override
                        public void onSuccess(Object message) {
                            String conversationId = message.toString();
                        }

                        @Override
                        public void onFailure(Object error) {
                            Log.d("ConversationTest", "Error : " + error);
                        }
                    });
```

If you have the list of your human agents and/or bots and need to create a single unique conversation with them then use the builder as described below:

```
     List<String> agentIds = new ArrayList<>();
     agentIds.add(""); 
     List<String> botIds = new ArrayList<>(); 
     botIds.add("BOT_ID");
     
     new KmConversationBuilder(activityContext)
                         .setAgentIds(agentIds)
                         .setBotIds(botIds)
                            .createConversation(new KmCallback() {
                        @Override
                        public void onSuccess(Object message) {

                        }

                        @Override
                        public void onFailure(Object error) {

                        }
                    });
```

### Custom Title

In Kommunicate you can also create a conversation with a custom title. If you do this, then in place of the agent name, the title you give to the converation will be displayed on the toolbar.

#### Below are the steps to create a conversation with a custom title:

* First create a `KmConverationBuilder` object using the code: `new KmConversationBuilder(activityContext)`. Pass the **activity context** in context.
* Then set the conversation title on it using the `setConverationTitle("Your title")` method.
* Also call the `setSingleConversation(false)` method on the Converation Builder object. This will create a new conversation every time you create one.
* Then launch(or create) the conversation using the `launchConveration(KmCallback KmCallback)` method on the KmConverationBuilder object. This method take a KmCallback object. You will get the conversationId the message object on the `onSuccess()` method callback of this object.
* You can use this `converationId` to later re-open the conversation, using [this](/documentation/docs/conversation-1.md#open-a-particular-conversation-thread) method.

You can refer to this code:

```
new KmConversationBuilder(activityContext)
       .setConversationTitle("My Title")
       .setSingleConversation(false)
       .launchConversation(new KmCallback() {
            @Override
            public void onSuccess(Object message) {
                
                String conversationId = message.toString(); 
            }

            @Override
            public void onFailure(Object error) {

            }
        });
```

### Custom conversation

You can customize the process of creating or launching a conversation by building the `KmConversationBuilder` object according to your requirements.

Here is the list of parameters along with the methods you can pass in `KmConversationBuilder` to customize the conversation according to your requirements:

> Note: The parameters should be passed as arguments in the methods.

| Parameter            | Parameter type | Method                                                    | Description                                                                                                                                                                                                                                                                             |
| -------------------- | -------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| activityContext      | Activity       | new KmConversationBuilder()                               | Passed in the constructor. Only Activity Context is accepted. Exception is thrown otherwise                                                                                                                                                                                             |
| APP\_ID              | String         | setAppId()                                                | Ignore if you have already initialized the SDK with [APP\_ID](https://dashboard.kommunicate.io/settings/install)                                                                                                                                                                        |
| kmUser               | KMUser         | setKmUser()                                               | If you have user details, you can pass them here. Ignore if you do not have user details.                                                                                                                                                                                               |
| withPreChat          | boolean        | setWithPreChat()                                          | Pass true if you would like the user to fill the details (such as name, email and phone etc.) before starting the chat. If you already have user details, then you can pass false.                                                                                                      |
| isSingleConversation | boolean        | setSingleConversation()                                   | Pass false if you would like to create new conversation every time a particular user starts a conversation. This is true by default which means only one conversation will open for the user every time the user starts a conversation.                                                 |
| agentList            | List           | setAgentIds()                                             | Pass the list of human agents. The agent IDs would be the email IDs of your team members which they used to register on Kommunicate. Otherwise, you can ignore it if you want to assign the conversation to the default agent.                                                          |
| botList              | List           | setBotIds()                                               | Pass the list of bots. In Kommunicate dashboard, go to [Manage Bots](https://dashboard.kommunicate.io/bots/manage-bots) -> Copy botID. Otherwise ignore if you haven't integrated any bots                                                                                              |
| clientConversationId | String         | setClientConversationId()                                 | Set the clientConversationId if you would like to identify a conversation based on your unique ID. One clientConversationId is mapped to only one conversation. Whenever this clientConversationId is passed to launch or create a conversation, the same conversation would be opened. |
| fcmDeviceToken       | String         | setFcmDeviceToken()                                       | Pass the fcmDeviceToken (Push notification token from FCM) obtained from FirebaseInstanceIdListener. Refer [here](/documentation/docs/push-notification.md) for more details.                                                                                                           |
| messageMetadata      | Map            | setMessageMetadata()                                      | This metadata, if set, will be sent with all the messages sent from that device. Also, this metadata will be set to all the conversations created from that device.                                                                                                                     |
| conversationAssignee | String         | setConversationAssignee()                                 | Should be either an agent Id or a botId. If set, will assign the conversation to the agent or bot thus skipping the routing rules set in the dashboard.                                                                                                                                 |
|                      | String         | setTeamId()                                               | Set the team ID in the conversation builder to assign the conversation directly to a team.                                                                                                                                                                                              |
| conversationMetadata | Map            | setConversationMetadata()                                 | This metadata, if set, will be sent with the conversation.                                                                                                                                                                                                                              |
| callback             | KmCallback     | <p>launchConversation()<br>OR<br>createConversation()</p> | Callback to notify Success or Failure                                                                                                                                                                                                                                                   |

The difference between `launchConversation` and `createConversation` is that `launchConversation` will launch the chat after creating it, whereas `createConversation` will only create the chat and won't launch it, returning the conversationId. To launch this created conversation in future use [this](https://docs.kommunicate.io/docs/android-conversation#open-a-particular-conversation-thread) method.

### Sending a message

You can send a message to the conversation using MessageBuilder. Use the below code to send a simple text message to a user.

```
  new MessageBuilder(context)
    .setMessage("Hello there")
    .setGroupId(123456).  
    .send();
```

### Sending a message with attachment

To send an attachment type message, use the filePath of the attachment with the MessageBuilder as below:

```
 new MessageBuilder(context)
               .setContentType(Message.ContentType.ATTACHMENT.getValue())
               .setGroupId(12345).  
               .setFilePath("")
               .send();
```

### Sending a message with metadata

To send the extra imformation with a message as metadata, use the below code:

```

Map metadata = new HashMap<>();
metadata.put("key1","value1");
metadata.put("key2","value2");

new MessageBuilder(context)
  .setMessage("Hello there")
  .setGroupId(12345) 
  .setMetadata(metadata)
  .send();
```

### Sending message with callback

To send a callback for the attachment upload progress and message sent event. Add the `MediaUploadProgressHandler` in the `send()` method as below:

```

new MessageBuilder(context)
                .setContentType(Message.ContentType.ATTACHMENT.getValue())
                .setGroupId(12345)
                .setFilePath("the files absolute path in string")
                .send(new MediaUploadProgressHandler() {
                    @Override
                    public void onUploadStarted(ApplozicException e, String oldMessageKey) {
                        if(e == null){
                          
                        }
                    }

                    @Override
                    public void onProgressUpdate(int percentage, ApplozicException e, String oldMessageKey) {
                       if(e == null){
                         
                       }
                    }

                    @Override
                    public void onCancelled(ApplozicException e, String oldMessageKey) {
                        
                    }

                    @Override
                    public void onCompleted(ApplozicException e, String oldMessageKey) {
                       if(e == null){
                         
                       }else{
                        
                       }
                    }

                    @Override
                    public void onSent(Message message, String oldMessageKey) {
                      
                    }
                });
                
```

## Rich Message

Rich message provide a better overall conversational experience to the users, make the interface look pretty, they also drive more actions from your users and provide a good conversational experience. There are a variety of response types to choose from. For example, you can show images, play videos, provide buttons, list, forms, or card carousels.

Refer the following link to use rich messages in Kommunicate.

> * [Rich Messages](https://docs.kommunicate.io/docs/message-types)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.flexmoney.uk/documentation/docs/conversation-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
