> For the complete documentation index, see [llms.txt](https://docs.sudoplatform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sudoplatform.com/guides/telephony/text-messaging.md).

# Text Messaging

SMS messages received on a provisioned phone number are sleaed by the service and unsealed by the Telephony SDK as they are retrieved, so the message objects returned to your application are already readable.

## Retrieving Phone Messages

Phone messages can be accessed in two ways: via its identifier ([Single Phone Message by Id](#single-phone-message-by-id)), or via a list method ([Multiple Phone Messages](#multiple-phone-messages)).

### Single Phone Message by Id

A single message can be retrieved by its unique `id` using the `getPhoneMessage` method, which returns the record if it exists.

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

```js
// Collect the input phone message id however makes sense for your implementation.
const phoneMessageId = phoneMessage.id
try {
  const phoneMessage = await telephonyClient.getPhoneMessage(phoneMessageId)
  // `phoneMessage` contains the phone message object, else `undefined` if not found.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
/// Collect the input phone message id however makes sense for your implementation.
let phoneMessageId = phoneMessage.id
do {
    let phoneMessage = try await telephonyClient.getPhoneMessage(id: phoneMessageId)
    /// `phoneMessage` contains the phone message object, else `nil` if not found.
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
// Collect the input phone message id however makes sense for your implementation.
val phoneMessageId = phoneMessage.id
launch {
    try {
        val phoneMessage = withContext(Dispatchers.IO) {
            telephonyClient.getPhoneMessage(phoneMessageId)
        }
        // [phoneMessage] contains the phone message object, else [null] if not found.
    } catch (e: PhoneMessageException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

### Multiple Phone Messages

The ability to retrieve multiple phone messages available to the user is supported. These results can be paginated.

#### All Phone Messages for a Phone Number

A phone number's inbox can be retrieved using the `listPhoneMessagesForPhoneNumberId` method. Messages are returned newest first across every conversation of the number. An optional `sortOrder` reverses the order.

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

```js
try {
  const result = await telephonyClient.listPhoneMessagesForPhoneNumberId({
    phoneNumberId: phoneNumber.id,
    sortOrder: SortOrder.Desc, // Optional, defaults to newest first
    limit: 20,
    nextToken: undefined,
  })
  switch (result.status) {
    case ListOperationResultStatus.Success:
      // `result.items` contains the messages with unsealed content.
      result.items.forEach((message) => {
        console.log(`${message.remotePhoneNumber}: ${message.body}`)
      })
      break
    case ListOperationResultStatus.Partial:
      // `result.items` contains the messages that were unsealed.
      // `result.failed` contains the messages that could not be unsealed, without
      // `body` or `remotePhoneNumber`, each with the error that explains why.
      result.failed.forEach(({ item, cause }) => {
        console.log(`Message ${item.id} could not be read: ${cause.message}`)
      })
      break
  }
  // `result.nextToken` is set when there are more pages.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
let localNumber: PhoneNumber
do {
    let listInput = ListPhoneMessagesForPhoneNumberIdInput(
        phoneNumberId: phoneNumber.id,
        conversationId: nil, /// Optionally limit to a single conversation
        sortOrder: .descending, /// Optional, defaults to newest first
        limit: 20,
        nextToken: nil
    )
    let output = try await telephonyClient.listPhoneMessagesForPhoneNumberId(listInput)
    /// `output.items` contains an array of `PhoneMessage` with unsealed content.
    for message in output.items {
        print("\(message.remotePhoneNumber ?? "unknown"): \(message.body)")
    }
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        val input = ListPhoneMessagesForPhoneNumberIdInput(
            phoneNumberId = phoneNumber.id,
            conversationId = null, // Optionally limit to a single conversation
            sortOrder = SortOrder.DESC, // Optional, defaults to newest first
            limit = 20,
            nextToken = null
        )
        val output = withContext(Dispatchers.IO) {
            telephonyClient.listPhoneMessagesForPhoneNumberId(input)
        }
        // [output.items] contains the messages with unsealed content.
        output.items.forEach { message ->
            println("${message.remotePhoneNumber}: ${message.body}")
        }
    } catch (e: PhoneMessageException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

#### All Phone Messages for a Conversation

To retrieve a list of phone messages related to a specific conversation, call the `listPhoneMessagesForConversationId` method. Messages are returned newest first for a specific conversation. An optional `sortOrder` reverses the order.

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

```js
try {
  const result = await telephonyClient.listPhoneMessagesForConversationId({
    conversationId,
    sortOrder: SortOrder.Desc, // Optional, defaults to newest first
    limit: 20,
    nextToken: undefined,
  })
  if (result.status !== ListOperationResultStatus.Failure) {
    // `result.items` contains the messages with unsealed content.
    result.items.forEach((message) => {
      console.log(`${message.remotePhoneNumber}: ${message.body}`)
    })
  }
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
let conversationId: String
do {
    let listInput = ListPhoneMessagesForConversationIdInput(
        conversationId: conversationId,
        sortOrder: .descending, /// Optional, defaults to newest first
        limit: 20,
        nextToken: nil
    )
    let output = try await telephonyClient.listPhoneMessagesForConversationId(listInput)
    /// `output.items` contains an array of `PhoneMessage` with unsealed content.
    for message in output.items {
        print("\(message.remotePhoneNumber ?? "unknown"): \(message.body)")
    }
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        val input = ListPhoneMessagesForConversationIdInput(
            conversationId = conversationId,
            sortOrder = SortOrder.DESC, // Optional, defaults to newest first
            limit = 20,
            nextToken = null
        )
        val output = withContext(Dispatchers.IO) {
            telephonyClient.listPhoneMessagesForConversationId(input)
        }
        // [output.items] contains the messages with unsealed content.
        output.items.forEach { message ->
            println("${message.remotePhoneNumber}: ${message.body}")
        }
    } catch (e: PhoneMessageException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

## Update Phone Messages

The update phone messages API currently supports updating the following phone message attributes:

|      |                                                                   |
| ---- | ----------------------------------------------------------------- |
| seen | Update this attribute to set the seen status of the phone message |

One or more phone message identifiers can be passed into the `updatePhoneMessages` method to perform a batch update of the phone messages associated with those identifiers.

{% hint style="warning" %}
Phone messages can only be updated in batches of 100. Supplying identifiers to the input which exceed this limit will throw a `LimitExceededError`.&#x20;
{% endhint %}

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

```js
try {
  const result = await telephonyClient.updatePhoneMessages({
    ids: messages.map((message) => message.id),
    seen: true,
  })
  // `result.succeededIds` contains the messages that were updated.
  // `result.failedIds` contains the messages that were not found or are not the caller's.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let result = try await telephonyClient.updatePhoneMessages(
        ids: output.items.map { $0.id },
        seen: true
    )
    /// `result.succeededIds` contains the messages that were updated.
    /// `result.failedIds` contains the messages that were not found or are not the caller's.
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        val input = UpdatePhoneMessagesInput(
            ids = output.items.map { it.id },
            seen = true
        )
        val result = withContext(Dispatchers.IO) {
            telephonyClient.updatePhoneMessages(input)
        }
        // [result.succeededIds] contains the messages that were updated.
        // [result.failedIds] contains the messages that were not found or are not the caller's.
    } catch (e: PhoneMessageException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}

## Delete Phone Messages

To delete messages, call the `deletePhoneMessages` method with their identifiers.

{% hint style="warning" %}
Phone messages can only be deleted in batches of 100. Supplying identifiers to the input which exceed this limit will throw a `LimitExceededError`.
{% endhint %}

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

```js
try {
  const result = await telephonyClient.deletePhoneMessages({
    ids: [message.id],
  })
  // `result.succeededIds` contains the messages that were deleted.
} catch (error) {
  // Handle/notify user of error
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
do {
    let result = try await telephonyClient.deletePhoneMessages(ids: [message.id])
    /// `result.succeededIds` contains the messages that were deleted.
} catch {
    /// Handle/notify user of error
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
launch {
    try {
        val input = DeletePhoneMessagesInput(ids = listOf(message.id))
        val result = withContext(Dispatchers.IO) {
            telephonyClient.deletePhoneMessages(input)
        }
        // [result.succeededIds] contains the messages that were deleted.
    } catch (e: PhoneMessageException) {
        // Handle/notify user of exception
    }
}
```

{% endtab %}
{% endtabs %}
