> For the complete documentation index, see [llms.txt](https://developers.mobile-text-alerts.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.mobile-text-alerts.com/use-cases/two-way-conversational-inbox.md).

# Two-way conversational inbox

Learn how to build a two-way conversational experience with the Mobile Text Alerts API

This guide shows how to retrieve the data needed to construct a two-way conversational messaging inbox. Whereas [Receive and Reply to Messages](https://developers.mobile-text-alerts.com/tutorials/message-sending/receive-and-reply-to-messages.md) covers the mechanics of handling a single reply, this guide takes the broader view of how to model a *conversation* that spans multiple sends and replies.

Mobile Text Alerts is the system of record for *message data*: what was sent, what was received, when, from which number, and with what delivery status. Other attributes of the conversation stream should be stored in your application, such as conversation status (open, pending, resolved), which agent is managing a conversation, internal notes, etc. By storing each user's sent/received message history locally, you can build a fast, queryable Agent UI for managing a two-way conversational inbox.

### Prerequisites

Before building this type of application, you need:

* To have completed the steps in [Getting Started](https://developers.mobile-text-alerts.com/getting-started/get-an-api-key.md) and have a valid API key.
* A verified sending number. Trial accounts and unverified numbers can only send templated content.
* Webhook endpoints already registered and receiving [`message-reply`](https://developers.mobile-text-alerts.com/tutorials/webhooks.md#message-reply) and [`message-send`](https://developers.mobile-text-alerts.com/tutorials/webhooks.md#message-send) events. See [Setting up your first webhook](https://developers.mobile-text-alerts.com/tutorials/webhooks/setting-up-your-first-webhook.md) if this has not been configured yet.

### Overview of conversation workflow&#x20;

1. A subscriber messages one of your numbers.
2. Mobile Text Alerts posts a `message-reply` event to your webhook.
3. Your endpoint acknowledges immediately and writes the inbound message to your data store.
4. Your backend reads the conversation from your data store to populate your Agent UI.
5. When your agent replies, your backend calls `POST /send`.
6. Mobile Text Alerts posts a `message-send` event to your webhook.
7. Your endpoint acknowledges immediately and writes the outbound message to your data store.

## Inbound message data

When a subscriber messages one of your numbers, Mobile Text Alerts posts a `message-reply` event to your webhook.

Ensure your webhook handler persists the necessary fields from the [`message-reply` payload (V3)](https://developers.mobile-text-alerts.com/tutorials/webhooks.md#message-reply) in your data store, including `fromNumber`, `toNumber`, `replyId`, `externalId`, `message`, `messageId`, `url`, `timestamp`, `tags`, and `senderName`.

To avoid slow or failed responses, your webhook handler should immediately return a `200` status code. Process the message event data asynchronously, including persistence.

## Outbound message data

You also need to store information about the messages sent to your subscribers. This ensures you have the context needed to reply to messages.

### Add an internal identifier <a href="#use-request-metadata-to-add-an-internal-identifier" id="use-request-metadata-to-add-an-internal-identifier"></a>

Track your sent-message data with identifying metadata for each `/send` request. Include one or both of the [`externalId`](#include-the-externalid-parameter) and/or [`tags`](#include-the-tags-parameter) fields on message sends to connect future replies to their message streams.

These parameters ensure that the [`message-reply` payload](https://developers.mobile-text-alerts.com/tutorials/webhooks.md#message-reply) sent to your endpoint contains the data needed to create a reply. These fields are included in the inbound events and are not properties of the inbound message itself but are echoed from the **most recent outbound message** sent to that subscriber. This is the only attribution the SMS channel provides.

#### **Include the `externalId` parameter**

The `externalId` parameter is an optional string field for you to create and assign your own identifier to each message request. This is strongly recommended because it ensures consistency between your system and Mobile Text Alerts. An `externalId` can be returned as an identifier in all future webhook calls related to the message, because the next inbound message echoes the `externalId` of the last outbound message.

#### **Include the `tags` parameter**

You can also use the `tags` parameter, a general-purpose tagging system, to assign additional data in requests to the `/send` endpoint. The `tags` object is tracked with the outbound message record and is reflected in all webhook calls related to this outbound message. The `tags` can contain metadata about the recipient, the message send request, an identifier for your external system, and any other data for your use case.

**Example:**

```javascript
"tags": {
  "conversationId": "conv_8f21",
  "ticketId": "T-10442",
  "agentId": "agent_17",
  "queue": "billing"
}
```

#### Store the `messageId`

A successful `/send` request will return a `messageId` as part of the response. This is the unique identifier of the request assigned by Mobile Text Alerts. Store this `messageId` and all relevant message data in your system to record sent message history.

### Track outbound messages with `message-send` webhook

While the `message-reply` webhook payload tells you what a subscriber said, the [`message-send` webhook payload](https://developers.mobile-text-alerts.com/tutorials/webhooks.md#message-send) tells you what the subscriber was sent. A conversation inbox needs the data from both events. The `message-send` data is important because it captures outbound messages sent through methods other than your backend. This can include responses from Automated Replies, Smart Replies, and Chatbots; scheduled messages; broadcasts and campaigns that included the subscriber; workflows; and messages a team member sent from the Mobile Text Alerts dashboard.

#### Data for reply

If you record every outbound message event along with its `externalId` and `tags`, you always know which context the next inbound message will bring back. This identifies which number the subscriber will reply to. A subscriber replies to whichever of your numbers messaged them last. The `fromNumber` on the latest `message-send` event shows which number that is, so you can keep that conversation open and reply from the same `longcodeId`.

#### Message send confirmation

This webhook event also confirms the send request. While a successful `POST /send` response means the request was accepted, the `message-send` event gives you the platform's own `messageId` and `timestamp` for the message. Use this `timestamp` for ordering, and use the `messageId` to match later delivery status events to the message in your conversation view.

## Construct a conversation history

With the relevant inbound and outbound message data, you can construct a full conversation history for a subscriber by merging both streams into a single time-ordered view. **Message data should be ordered by the `timestamp`** rather than the webhook request's arrival time because webhooks are not guaranteed to arrive in the order messages were sent/received.&#x20;

Keep in mind that each subscriber may receive messages from different numbers on your account or may reply to different messages at different times. To ensure messages are attributed to the correct conversation, each conversation should be segmented by both the subscriber and the sending number.

### Backfill conversation history

You may need to backfill part of a conversation history after an outage or if you did not previously store message data. There are several API endpoints that can be used to retrieve historical data, depending on the information you need. Use the results to upsert any missing outbound messages into your data store.

{% hint style="info" %}
To avoid duplicate messages from webhook payloads and backfilled data, use the Mobile Text Alerts `messageId` as a deduplication key.
{% endhint %}

{% hint style="info" %}
**Respect rate limits**

Every response includes `RateLimit-Remaining` and `RateLimit-Reset` headers. Fetch replies only for outbound messages with replies, and back off when `Retry-After` is returned.
{% endhint %}

#### Retrieve outbound history for a subscriber

Call the [`GET /sent-messages` endpoint](https://developers.mobile-text-alerts.com/api-reference/sent-messages.md#get-sent-messages) to list outbound messages. This can be narrowed to one conversation with the following filters:

* `filters[recipientQuery]` — the subscriber's phone number
* `filters[fromNumber]` — your sending number (numeric, digits only)
* `filters[startDate]` / `filters[endDate]` — to bound a backfill window.

**Example query:**

{% tabs %}
{% tab title="cURL" %}

```bash
curl -G "https://api.mobile-text-alerts.com/v3/sent-messages" \
  -H "Authorization: Bearer <APIKey>" \
  --data-urlencode "filters[recipientQuery]=3175551111" \
  --data-urlencode "filters[fromNumber]=18885550100" \
  --data-urlencode "filters[startDate]=2026-10-01" \
  --data-urlencode "filters[endDate]=2026-10-14" \
  --data-urlencode "sortDirection=asc" \
  --data-urlencode "pageSize=100" \
  --data-urlencode "page=1"
```

{% endtab %}

{% tab title="Node" %}

```javascript
const params = new URLSearchParams({
  "filters[recipientQuery]": "3175551111",
  "filters[fromNumber]": "18885550100",
  "filters[startDate]": "2026-10-01",
  "filters[endDate]": "2026-10-14",
  sortDirection: "asc",
  pageSize: "100",
  page: "1",
});

const response = await fetch(
  `https://api.mobile-text-alerts.com/v3/sent-messages?${params}`,
  {
    headers: {
      Authorization: `Bearer ${process.env.MTA_API_KEY}`,
    },
  }
);

const { data } = await response.json();
// data.rows, data.page, data.pageSize, data.total
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.get(
    "https://api.mobile-text-alerts.com/v3/sent-messages",
    headers={"Authorization": f"Bearer {os.environ['MTA_API_KEY']}"},
    params={
        "filters[recipientQuery]": "3175551111",
        "filters[fromNumber]": "18885550100",
        "filters[startDate]": "2026-10-01",
        "filters[endDate]": "2026-10-14",
        "sortDirection": "asc",
        "pageSize": 100,
        "page": 1,
    },
)

data = response.json()["data"]
# data["rows"], data["page"], data["pageSize"], data["total"]
```

{% endtab %}
{% endtabs %}

The response is paginated (`rows`, `page`, `pageSize`, `total`). Each row includes the fields you need for a conversation view: `id`, `message`, `url`, `timestamp`, `externalId`, `fromNumber`, `sentBy`, `source`, and `autoTriggered`.

#### Retrieve inbound replies to a given send

The [`GET /sent-messages/{outboundId}/replies` endpoint](https://developers.mobile-text-alerts.com/api-reference/sent-messages.md#get-sent-messages-outboundid-replies) returns the inbound messages attributed to a specific outbound message.

For a broadcast with many responders, add `filters[recipientQuery]` to return only one subscriber's replies. The other filters listed in the preceding query can also be included.

**Example query:**

{% tabs %}
{% tab title="cURL" %}

```bash
curl -G "https://api.mobile-text-alerts.com/v3/sent-messages/123456789/replies" \
  -H "Authorization: Bearer <APIKey>" \
  --data-urlencode "filters[recipientQuery]=3175551111" \
  --data-urlencode "sortDirection=asc" \
  --data-urlencode "pageSize=100" \
  --data-urlencode "page=1"
```

{% endtab %}

{% tab title="Node" %}

```javascript
const outboundId = "123456789";

const params = new URLSearchParams({
  "filters[recipientQuery]": "3175551111",
  sortDirection: "asc",
  pageSize: "100",
  page: "1",
});

const response = await fetch(
  `https://api.mobile-text-alerts.com/v3/sent-messages/${outboundId}/replies?${params}`,
  {
    headers: {
      Authorization: `Bearer ${process.env.MTA_API_KEY}`,
    },
  }
);

const { data } = await response.json();
// data.rows: [{ message, number, replyDate, subscriberId, fromNumber, attachmentUrl, carrier, ... }]
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

outbound_id = "123456789"

response = requests.get(
    f"https://api.mobile-text-alerts.com/v3/sent-messages/{outbound_id}/replies",
    headers={"Authorization": f"Bearer {os.environ['MTA_API_KEY']}"},
    params={
        "filters[recipientQuery]": "3175551111",
        "sortDirection": "asc",
        "pageSize": 100,
        "page": 1,
    },
)

data = response.json()["data"]
# data["rows"]: [{ message, number, replyDate, subscriberId, fromNumber, attachmentUrl, carrier, ... }]
```

{% endtab %}
{% endtabs %}

#### Retrieve subscribers who responded to a given send, without the content

The [`GET /sent-messages/{outboundId}/replies/subscriber-ids` endpoint](https://developers.mobile-text-alerts.com/api-reference/sent-messages.md#get-sent-messages-outboundid-replies-subscriber-ids) returns only the `subscriberId` of each responder. Use this endpoint when you need to know *who* replied, for example to open a conversation for every responder to a campaign, without downloading every message body.

**Example query:**

{% tabs %}
{% tab title="cURL" %}

```bash
curl "https://api.mobile-text-alerts.com/v3/sent-messages/123456789/replies/subscriber-ids" \
  -H "Authorization: Bearer <APIKey>"
```

{% endtab %}

{% tab title="Node" %}

```javascript
const outboundId = "123456789";

const response = await fetch(
  `https://api.mobile-text-alerts.com/v3/sent-messages/${outboundId}/replies/subscriber-ids`,
  {
    headers: {
      Authorization: `Bearer ${process.env.MTA_API_KEY}`,
    },
  }
);

const { data } = await response.json();
// data: [{ subscriberId: 482910 }, { subscriberId: 482911 }, ...]
const subscriberIds = data.map((row) => row.subscriberId);
```

{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

outbound_id = "123456789"

response = requests.get(
    f"https://api.mobile-text-alerts.com/v3/sent-messages/{outbound_id}/replies/subscriber-ids",
    headers={"Authorization": f"Bearer {os.environ['MTA_API_KEY']}"},
)

data = response.json()["data"]
# data: [{"subscriberId": 482910}, {"subscriberId": 482911}, ...]
subscriber_ids = [row["subscriberId"] for row in data]
```

{% endtab %}
{% endtabs %}

## Send a reply

The `fromNumber` identifies the phone number of the subscriber that replied, but that subscriber may receive messages from different numbers on your account or may be replying to different messages at different points in time. To avoid this confusion, instead of associating your reply to a *subscriber*, it is best to associate a reply to an *outbound message*.

You can determine the initial outbound message being replied to by retrieving the original outbound message from your system [using the `externalId` and/or `tags` in the reply payload](#use-request-metadata-to-add-an-internal-identifier). This enables your application to produce a consistently ordered chain of messages, both outbound and inbound, needed to support two-way conversations.

To form your response message request, you can reuse the initial outbound number by setting the same `longcodeId` value in the `/send` request that was previously used for the original outbound message. Set the recipient to the value of the `fromNumber`. Ensure that you provide a new internal identifier for this outbound message in order to repeat this process of send and reply.

Use `userSignature` to attribute an outbound reply to the agent who wrote it, so your conversation history and reporting show who said what. Store the agent ID on your own message record as well.&#x20;

Visit [Automated Message Replies](https://developers.mobile-text-alerts.com/tutorials/message-sending/automated-message-replies.md) to learn ways to configure your system to respond to messages automatically, without the use of human agents.

## Learn more

* [Receive and Reply to Messages](https://developers.mobile-text-alerts.com/tutorials/message-sending/receive-and-reply-to-messages.md) — the single send-and-reply pattern this guide builds on.
* [Appointment Reminders with Confirmation Replies](https://developers.mobile-text-alerts.com/use-cases/appointment-reminders-with-confirmation-replies.md) — a worked example of handling replies against your own application state.
* [Webhooks](https://developers.mobile-text-alerts.com/tutorials/webhooks.md) — payload reference for `message-reply`, `message-send`, and delivery status events.
* [Sent Messages](https://developers.mobile-text-alerts.com/api-reference/sent-messages.md) — full reference for listing sent messages and their replies.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers.mobile-text-alerts.com/use-cases/two-way-conversational-inbox.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
