> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-rn-guide-message-privately.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Interactive Messages

> Send and receive interactive messages with embedded forms, buttons, and other UI elements using the CometChat Android SDK.

An `InteractiveMessage` is a specialized object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input.

## InteractiveMessage

`InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties:

| Parameter                | Description                                                                                                                                                             |          |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| `receiverId`             | The UID or GUID of the recipient                                                                                                                                        | Required |
| `receiverType`           | The type of the receiver to whom the message is to be sent. Options: `CometChatConstants.RECEIVER_TYPE_USER` (user) or `CometChatConstants.RECEIVER_TYPE_GROUP` (group) | Required |
| `messageType`            | The type of the message that needs to be sent                                                                                                                           | Required |
| `interactiveData`        | A JSONObject holding structured data for the interactive element.                                                                                                       | Required |
| `allowSenderInteraction` | A boolean determining whether the message sender can interact with the message. Default is set to false.                                                                |          |
| `interactionGoal`        | An `InteractionGoal` object encapsulating the intended outcome of interacting with the `InteractiveMessage`. Default is set to none.                                    |          |

## Interaction

An Interaction represents a user action involved with an `InteractiveMessage`. It includes:

* `elementId`: An identifier for a specific interactive element.
* `interactedAt`: A timestamp indicating when the interaction occurred.

## Mark as Interacted

This method marks a message as interacted by identifying it with the provided Id. it also logs the interactive element associated with the interaction.

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    val messageId = 1
    val elementId = "elementId"

    CometChat.markAsInteracted(messageId, elementId, object : CometChat.CallbackListener<Void?>() {
        override fun onSuccess(unused: Void?) {

        }

        override fun onError(e: CometChatException) {
          
        }
    }) 
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    int messageId = 1;
    String elementId = "elementId";
    CometChat.markAsInteracted(messageId, elementId, new CometChat.CallbackListener<Void>() {
       @Override
       public void onSuccess(Void unused) {

        }

       @Override
       public void onError(CometChatException e) {

        }
    });
    ```
  </Tab>
</Tabs>

## Goal Completion

A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal`

You would be tracking every interaction users perform on an `InteractiveMessage` (captured as `Interaction` objects) and comparing those with the defined `InteractionGoal`. The completion of a goal can vary depending on the goal type:

| Goals                        | Description                                                            | Keys                                          |
| ---------------------------- | ---------------------------------------------------------------------- | --------------------------------------------- |
| Any Interaction              | The goal is considered completed if there is at least one interaction. | CometChatConstants.INTERACTION\_TYPE\_ANY     |
| Any of Specific Interactions | The goal is achieved if any of the specified interactions occurred.    | CometChatConstants.INTERACTION\_TYPE\_ANY\_OF |
| All of Specific Interactions | The goal is completed when all specified interactions occur.           | CometChatConstants.INTERACTION\_TYPE\_ALL\_OF |
| None                         | The goal is never completed.                                           | CometChatConstants.INTERACTION\_TYPE\_NONE    |

## InteractionGoal

The `InteractionGoal` represents the desired outcome of an interaction with an InteractiveMessage. It includes:

* `elementIds`: A list of identifiers for the interactive elements.
* `type`: The type of interaction goal from the `CometChatConstants`.

## Send an Interactive Message

The `InteractiveMessage` can be sent using the `sendInteractiveMessage` method of the CometChat class. The method requires an `InteractiveMessage` object and a `CallbackListener` for handling the response.

Before sending interactive messages, ensure you have [initialized the SDK](/sdk/android/setup) and [logged in a user](/sdk/android/authentication-overview).

Here is an example of how to use it:

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    val interactiveData = JSONObject()
    try {
        interactiveData.put("title", "Demo Form")
        val jsonArray = JSONArray()
        val textInput = JSONObject()
        textInput.put("elementType", "textInput")
        textInput.put("elementId", "element1")
        textInput.put("label", "Name")
        textInput.put("optional", false)
        textInput.put("maxLines", 1)
        jsonArray.put(textInput)
        interactiveData.put("formFields", jsonArray)
        val submitElement = JSONObject()
        submitElement.put("elementType", "button")
        submitElement.put("elementId", "element8")
        submitElement.put("buttonText", "Submit")
        submitElement.put("disableAfterInteracted", true)
        val action = JSONObject()
        action.put("actionType", "urlNavigation")
        action.put("url", "https://www.cometchat.com/")
        submitElement.put("action", action)
        interactiveData.put("submitElement", submitElement)
    } catch (e: JSONException) {
        throw RuntimeException(e)
    }

    val interactiveMessage = InteractiveMessage(receiverId, receiverType, "form", interactiveData)

    CometChat.sendInteractiveMessage(interactiveMessage, object : CometChat.CallbackListener<InteractiveMessage>() {
        override fun onSuccess(interactiveMessage: InteractiveMessage) {
            // This block is executed when the InteractiveMessage is sent successfully.
        }

        override fun onError(e: CometChatException) {
            // This block is executed if an error occurs while sending the InteractiveMessage.
        }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    JSONObject interactiveData = new JSONObject();
    try {
      interactiveData.put("title", "Demo Form");
      JSONArray jsonArray = new JSONArray();
      JSONObject textInput = new JSONObject();
      textInput.put("elementType", "textInput");
      textInput.put("elementId", "element1");
      textInput.put("label", "Name");
      textInput.put("optional", false);
      textInput.put("maxLines", 1);
      jsonArray.put(textInput);
      interactiveData.put("formFields", jsonArray);
      JSONObject submitElement = new JSONObject();
      submitElement.put("elementType", "button");
      submitElement.put("elementId", "element8");
      submitElement.put("buttonText", "Submit");
      submitElement.put("disableAfterInteracted", true);
      JSONObject action = new JSONObject();
      action.put("actionType", "urlNavigation");
      action.put("url", "https://www.cometchat.com/");
      submitElement.put("action", action);
      interactiveData.put("submitElement", submitElement);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }

    InteractiveMessage interactiveMessage = new InteractiveMessage(receiverId,receiverType,"form", interactiveData);

    CometChat.sendInteractiveMessage(interactiveMessage, new CometChat.CallbackListener<InteractiveMessage>() {
      @Override
      public void onSuccess(InteractiveMessage interactiveMessage) {
          // This block is executed when the InteractiveMessage is sent successfully.
      }

      @Override
      public void onError(CometChatException e) {
          // This block is executed if an error occurs while sending the InteractiveMessage.
      }
    });
    ```
  </Tab>
</Tabs>

## Real-time Events

CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. For more details on listener management, see [Real-Time Listeners](/sdk/android/real-time-listeners).

On `InteractiveMessage` Received The `onInteractiveMessageReceived` event listener is triggered when an InteractiveMessage is received.

Here is an example:

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChat.addMessageListener("UNIQUE_ID", object : CometChat.MessageListener() {
      override fun onInteractiveMessageReceived(interactiveMessage: InteractiveMessage) {
          // This block is executed when an InteractiveMessage is received.
          // Here you can define logic to handle the received InteractiveMessage and display it in your chat interface.
      }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() {
      @Override
      public void onInteractiveMessageReceived(InteractiveMessage interactiveMessage){
        // This block is executed when an InteractiveMessage is received.
        // Here you can define logic to handle the received InteractiveMessage and display it in your chat interface.
      }          
    });
    ```
  </Tab>
</Tabs>

<Warning>
  Always remove listeners when they're no longer needed (e.g., in `onDestroy()` or when navigating away). Failing to remove listeners can cause memory leaks and duplicate event handling.
</Warning>

## On Interaction Goal Completed

The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved.

Here is an example:

<Tabs>
  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChat.addMessageListener("UNIQUE_ID", object : CometChat.MessageListener() {
      override fun onInteractionGoalCompleted(interactionReceipt: InteractionReceipt) {
          // This block is executed when an interaction goal is completed.
          // Here you can specify the actions your application should take once an interaction goal is achieved, such as updating the UI or notifying the user.
      }
    })
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    CometChat.addMessageListener("UNIQUE_ID", new CometChat.MessageListener() {
      @Override
      public void onInteractionGoalCompleted(InteractionReceipt interactionReceipt) {
      // This block is executed when an interaction goal is completed.
      // Here you can specify the actions your application should take once an interaction goal is achieved, such as updating the UI or notifying the user.
      }
    });
    ```
  </Tab>
</Tabs>

These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience.

## InteractiveMessage Payload Structure

<Accordion title="InteractiveMessage Object">
  The `InteractiveMessage` object contains interactive content like forms and buttons:

  | Parameter                | Type                                       | Description                                                  |
  | ------------------------ | ------------------------------------------ | ------------------------------------------------------------ |
  | `id`                     | long                                       | Unique message identifier                                    |
  | `muid`                   | String                                     | Developer-defined message ID                                 |
  | `sender`                 | [User](#user-object-interactive)           | User who sent the message                                    |
  | `receiver`               | AppEntity                                  | Message receiver ([User](#user-object-interactive) or Group) |
  | `type`                   | String                                     | Message type (e.g., `"form"`, `"card"`)                      |
  | `receiverType`           | String                                     | Type of receiver. Values: `"user"`, `"group"`                |
  | `category`               | String                                     | Message category. Value: `"interactive"`                     |
  | `sentAt`                 | long                                       | Unix timestamp when sent                                     |
  | `metadata`               | JSONObject                                 | Custom message metadata                                      |
  | `conversationId`         | String                                     | Associated conversation ID                                   |
  | `interactiveData`        | JSONObject                                 | Interactive content data                                     |
  | `tags`                   | Array\<String>                             | Message tags                                                 |
  | `interactionGoal`        | [InteractionGoal](#interactiongoal-object) | Goal for interactions                                        |
  | `interactions`           | Array\<[Interaction](#interaction-object)> | User interactions                                            |
  | `allowSenderInteraction` | boolean                                    | If sender can interact                                       |

  **Sample InteractiveMessage Object:**

  ```json theme={null}
  {
    "id": 12345,
    "muid": "msg_abc123",
    "sender": {
      "uid": "user_123",
      "name": "John Doe",
      "avatar": "https://example.com/avatar.png",
      "status": "online",
      "role": "default"
    },
    "receiver": {
      "uid": "user_456",
      "name": "Jane Smith"
    },
    "type": "form",
    "receiverType": "user",
    "category": "interactive",
    "sentAt": 1699900000,
    "metadata": {"priority": "high"},
    "conversationId": "user_123_user_456",
    "interactiveData": {
      "title": "Demo Form",
      "formFields": [
        {
          "elementType": "textInput",
          "elementId": "element1",
          "label": "Name",
          "optional": false,
          "maxLines": 1
        }
      ],
      "submitElement": {
        "elementType": "button",
        "elementId": "element8",
        "buttonText": "Submit",
        "disableAfterInteracted": true,
        "action": {
          "actionType": "urlNavigation",
          "url": "https://www.cometchat.com/"
        }
      }
    },
    "tags": ["interactive"],
    "interactionGoal": {
      "type": "anyOf",
      "elementIds": ["element1", "element8"]
    },
    "interactions": [],
    "allowSenderInteraction": false
  }
  ```
</Accordion>

<Accordion title="InteractionGoal Object">
  The `InteractionGoal` object defines the desired outcome of interactions:

  | Parameter    | Type           | Description                                                      |
  | ------------ | -------------- | ---------------------------------------------------------------- |
  | `type`       | String         | Goal type. Values: `"none"`, `"anyAction"`, `"anyOf"`, `"allOf"` |
  | `elementIds` | Array\<String> | Target element IDs for the goal                                  |

  **Sample InteractionGoal Object:**

  ```json theme={null}
  {
    "type": "anyOf",
    "elementIds": ["button_1", "input_1"]
  }
  ```
</Accordion>

<Accordion title="Interaction Object">
  The `Interaction` object represents a user action on an interactive element:

  | Parameter      | Type   | Description                              |
  | -------------- | ------ | ---------------------------------------- |
  | `elementId`    | String | Identifier of the interacted element     |
  | `interactedAt` | long   | Unix timestamp when interaction occurred |

  **Sample Interaction Object:**

  ```json theme={null}
  {
    "elementId": "element1",
    "interactedAt": 1699900500
  }
  ```
</Accordion>

<Accordion title="User Object (Interactive)">
  The nested `User` object in `sender` contains:

  | Parameter       | Type           | Description                                            |
  | --------------- | -------------- | ------------------------------------------------------ |
  | `uid`           | String         | Unique identifier of the user                          |
  | `name`          | String         | Display name of the user                               |
  | `avatar`        | String         | URL to user's profile picture                          |
  | `link`          | String         | URL to user's profile page                             |
  | `role`          | String         | User role for access control                           |
  | `metadata`      | JSONObject     | Custom data set by developer                           |
  | `status`        | String         | User online status. Values: `"online"`, `"offline"`    |
  | `statusMessage` | String         | Custom status message                                  |
  | `lastActiveAt`  | long           | Unix timestamp of last activity                        |
  | `hasBlockedMe`  | boolean        | Whether this user has blocked the logged-in user       |
  | `blockedByMe`   | boolean        | Whether the logged-in user has blocked this user       |
  | `tags`          | Array\<String> | List of tags for user identification                   |
  | `deactivatedAt` | long           | Unix timestamp when user was deactivated (0 if active) |

  **Sample User Object:**

  ```json theme={null}
  {
    "uid": "user_123",
    "name": "John Doe",
    "avatar": "https://example.com/avatar.png",
    "link": "https://example.com/profile/user_123",
    "role": "default",
    "metadata": {"department": "engineering"},
    "status": "online",
    "statusMessage": "Available",
    "lastActiveAt": 1699900000,
    "hasBlockedMe": false,
    "blockedByMe": false,
    "tags": ["premium"],
    "deactivatedAt": 0
  }
  ```
</Accordion>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Send Messages" icon="paper-plane" href="/sdk/android/send-message">
    Learn how to send text, media, and custom messages
  </Card>

  <Card title="Mentions" icon="at" href="/sdk/android/mentions">
    Mention specific users in messages for better engagement
  </Card>

  <Card title="Receive Messages" icon="envelope" href="/sdk/android/receive-messages">
    Handle incoming messages with real-time listeners
  </Card>

  <Card title="Real-Time Listeners" icon="bell" href="/sdk/android/real-time-listeners">
    Manage event listeners for real-time updates
  </Card>
</CardGroup>
