# Manage local conversations (/en/realtime-media/im/build/build-core-messaging/messages/manage-messages/unity)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

In chat apps, a conversation is composed of all the messages in a peer-to-peer chat, chat group, or chatroom. The Chat SDK supports managing messages by conversations, including retrieving and managing unread messages, deleting the historical messages on the local device, and searching historical messages.

    This page introduces how to use the Chat SDK to implement these functionalities.

    ## Understand the tech [#understand-the-tech-6]

    SQLCipher is used to encrypt the database that stores local messages. The Chat SDK uses `IChatManager` and `IConversationManager` to manage local messages. The following are the core methods:

    * `IChatManager.LoadAllConversations`: Loads the conversation list on the local device.
    * `IChatManage.DeleteConversation`: Deletes the specified conversation.
    * `Conversation#DeleteAllMessages`：Deletes all messages sent and received in a local conversation.
    * `Conversation#DeleteMessages`: Deletes messages sent and received in a certain period in a local conversation.
    * `IConversationManager.UnReadCount`: Retrieves the count of unread messages in the specified conversation.
    * `IChatManager.GetUnreadMessageCount`: Retrieves the count of all unread messages.
    * `IChatManager.PinConversation`: Pins a conversation.
    * `IChatManager.GetConversationsFromServerWithCursor`: Retrieves the pinned conversations from the server with pagination.
    * `IChatManager.DeleteConversationFromServer`: Deletes the conversation from the server.
    * `IChatManager.searchMsgFromDB`: Searches for messages from the local database.
    * `Conversation.insertMessage`: Inserts messages in the specified conversation.

    ## Prerequisites [#prerequisites-6]

    Before proceeding, ensure that you meet the following requirements:

    * You have integrated the Chat SDK, initialized the SDK and implemented the functionality of registering accounts and login. For details, see [Chat SDK quickstart](../../../../get-started-sdk).
    * You understand the API call frequency limits as described in [Limitations](../../limitations).

    ## Implementation [#implementation-6]

    This section shows how to implement managing messages.

    ### Retrieve conversations [#retrieve-conversations-6]

    Call `LoadAllConversations` to retrieve all the conversations on the local device:

    ```csharp
    Listlist = SDKClient.Instance.ChatManager.LoadAllConversations();
    ```

    ### Retrieve messages in the specified conversation [#retrieve-messages-in-the-specified-conversation-5]

    Refer to the following code sample to retrieve the messages in the specified conversation:

    ```csharp
    // Get the specified conversation on the local device.
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversationId, convType);
    // Call LoadMessages to retrieve messages by specifying the `startMsgId` and `pageSize`.
    conv.LoadMessages(startMsgId, pagesize, callback:new ValueCallBack>(
      onSuccess: (list) => {
         Debug.Log($"{list.Count} Messages retrieved.");
      },
      onError:(code, desc) => {
         Debug.Log($"Fails to retrieve the message, errCode={code}, errDesc={desc}");
      }
    ));
    ```

    ### Retrieve the count of unread messages in the specified conversation [#retrieve-the-count-of-unread-messages-in-the-specified-conversation-5]

    Refer to the following code example to retrieve the count of unread messages:

    ```csharp
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversationId, convType);
    int unread = conv.UnReadCount;
    ```

    ### Retrieve the count of unread messages in all conversations [#retrieve-the-count-of-unread-messages-in-all-conversations-5]

    Refer to the following code example to retrieve the count of all unread messages:

    ```csharp
    SDKClient.Instance.ChatManager.GetUnreadMessageCount();
    ```

    ### Mark unread messages as read [#mark-unread-messages-as-read-5]

    Refer to the following code example to mark the specified messages as read:

    ```csharp
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversationId, convType);
    // Mark all the messages in the current conversation as read.
    conv.MarkAllMessageAsRead();
    // Mark the specified message as read.
    conv.MarkMessageAsRead(msgId);
    // Mark all unread messages as read.
    SDKClient.Instance.ChatManager.MarkAllConversationsAsRead();
    ```

    ### Clear chat history [#clear-chat-history-6]

    To clear the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms, you can call the `DeleteAllMessagesAndConversations` method. Additionally, you can choose whether to clear the chat history on the server. Note that clearing the chat history on the server means that you will not be able to retrieve conversations and messages from the server, although other users will not be affected.

    ```csharp
    bool clearServerData = false; // or true
    SDKClient.Instance.ChatManager.DeleteAllMessagesAndConversations(clearServerData, new CallBack(
        onSuccess: () =>
        {
        },
        onError: (code, desc) =>
        {
        }
    ));
    ```

    ### Delete conversations and historical messages [#delete-conversations-and-historical-messages-2]

    You can delete conversations on both the local device and the server.

    To delete them on the local device, call `DeleteConversation` and `DeleteMessage`:

    ```csharp
    // Call DeleteConversation to delete the specified conversation.
    // `true` indicates to keep the historical messages while deleting the conversation. To remove the historical messages as well, set it as `false`.
    SDKClient.Instance.ChatManager.DeleteConversation(conversationId, true);
    // Delete the specified message in the current conversation.
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversationId, convType);
    conv.DeleteMessage(msgId);
    ```

    To delete conversations on the server, call `DeleteConversationFromServer`:

    ```csharp
    // Delete a conversation on the server. If you want to keep the historical messages, pass “false” to the third parameter.
    SDKClient.Instance.ChatManager.DeleteConversationFromServer(conversationId, type, true, new CallBack(
        onSuccess: () => {
        },
        onError: (code, desc) => {
        }
    ));
    ```

    ### Delete all messages in the local conversation [#delete-all-messages-in-the-local-conversation]

    You can delete all messages in the local conversation. The sample code is as follows:

    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversionId, conversationType);

    ```csharp
    if (conv.DeleteAllMessages()){
         // Message deleted successfully
    }
    else {
         // Delete message failed
    }
    ```

    ### Delete messages from a single local conversation within a specified time period [#delete-messages-from-a-single-local-conversation-within-a-specified-time-period]

    You can delete local messages for a specified conversation within a period of time. The sample code is as follows:

    ```csharp
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversionId, conversationType);

    if (conv.DeleteMessages(startTime, endTime)) {
         // Message deleted successfully
    }
    else {
         // Delete message failed
    }
    ```

    ### Delete the specified message of a local conversation [#delete-the-specified-message-of-a-local-conversation]

    You can delete specified messages of a single local conversation. The sample code is as follows:

    ```csharp
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversionId, conversationType);

    if (conv.DeleteMessage(msgid)){
         // Message deleted successfully
    }
    else {
         // Delete message failed
    }
    ```

    ### Search for messages using keywords [#search-for-messages-using-keywords-5]

    Search methods provided on this page can be used to search the local database for all types of messages except command messages, because command messages are not stored in the local database.

    Call `SearchMsgFromDB` to search for messages by keywords, timestamp, and message sender:

    ```csharp
    List list = SDKClient.Instance.ChatManager.SearchMsgFromDB(keywords, timeStamp, maxCount, from, MessageSearchDirection.UP);
    ```

    ### Search for messages in all conversations based on search scope [#search-for-messages-in-all-conversations-based-on-search-scope-5]

    You can call the `ChatManager#SearchMsgFromDB(string, long, in, string, MessageSearchDirection, MessageSearchScope, ValueCallBack>)` method to search in all conversations based on the search scope. This means that, in addition to setting the keywords, message timestamps, number of messages, sender, and search direction, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```csharp
    SDKClient.Instance.ChatManager.SearchMsgFromDB("keywords", -1, 10, "from", MessageSearchDirection.UP, MessageSearchScope.CONTENT, new ValueCallBack>(
      onSuccess: (list) => {
          foreach (var it in list)
          {
              //Iterate over the List list
          }
      },
      onError: (code, desc) => {
    }));
    ```

    ### Search for messages in the current conversation based on search scope [#search-for-messages-in-the-current-conversation-based-on-search-scope-5]

    You can call `Conversation#LoadMessagesWithScope(string, MessageSearchScope, long, int, string, MessageSearchDirection, ValueCallBack>)` method to search for messages in the current conversation based on the search scope. This means that, in addition to setting keywords, message timestamps, number of messages, sender, direction, and other parameters, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```csharp
    conv.LoadMessagesWithScope("keywords", MessageSearchScope.CONTENT, -1, 10, "from", MessageSearchDirection.UP, new ValueCallBack>(
        onSuccess: (list) => {
            foreach (var it in list)
            {
                //Iterate over the List list
            }
        },
        onError: (code, desc) => {
        }
    ));
    ```

    ### Import messages [#import-messages-5]

    Call `ImportMessages` to import multiple messages to the specified conversation.

    ```csharp
    SDKClient.Instance.ChatManager.ImportMessages(messages, new CallBack(
      onSuccess: () => {
      },
      onError: (code, desc) =>
      {
      }
    ));
    ```

    ### Insert messages [#insert-messages-3]

    If you want to insert a message to the current conversation without actually sending the message, construct the message body and call `InsertMessage`. This can be used to send notification messages such as "XXX recalls a message", "XXX joins the chat group", and "Typing ...".

    ```csharp
    // Insert the message to the current conversation.
    Conversation conv = SDKClient.Instance.ChatManager.GetConversation(conversationId, convType);
    conv.InsertMessage(message);
    ```

    ## Next steps [#next-steps-6]

    After implementing managing messages, you can refer to the following documents to add more messaging functionalities to your app:

    * [Retrieve conversations and messages from the server](./retrieve-messages)
    * [Message receipts](./message-receipts)

    
  
