

# Building AWS Lambda functions for the Amazon Chime SDK PSTN audio service
<a name="writing-lambdas"></a>

The topics in this section explain how to build the AWS Lambda functions used by your PSTN audio service. 

**Topics**
+ [Understanding telephony events for Amazon Chime SDK PSTN audio service](pstn-invocations.md)
+ [Understanding Amazon Chime SDK PSTN audio service actions](about-actions.md)
+ [Learn about the telephony events that invoke AWS Lambda functions for the Amazon Chime SDK PSTN audio service](invoking-Lambda.md)
+ [Responding to invocations with action lists using the Amazon Chime SDK PSTN audio service](invoke-on-call-leg.md)
+ [Supported actions for the Amazon Chime SDK PSTN audio service](specify-actions.md)
+ [Using SIP headers in the Amazon Chime SDK PTSN audio service](sip-headers.md)
+ [Using call detail records in the Amazon Chime SDK PTSN audio service](attributes.md)
+ [Understanding timeouts and retries for the Amazon Chime SDK PTSN audio service](timeouts.md)
+ [Debugging and troubleshooting the Amazon Chime SDK PTSN audio service](debug-pstn.md)
+ [Understanding VoiceFocus for the Amazon Chime SDK PTSN audio service](voice-focus.md)
+ [Amazon Chime SDK PSTN audio service glossary](chm-dg-glossary.md)

# Understanding telephony events for Amazon Chime SDK PSTN audio service
<a name="pstn-invocations"></a>

The Audio Service invokes your AWS AWS Lambda function when certain events occur during a call. The following example shows the events, and text after the example explains each event.

```
{ 
    "SchemaVersion": "1.0", 
    "Sequence": 3, 
    "InvocationEventType": "event-type", 
    "CallDetails": { 
        "TransactionId": "transaction-id-1", 
        "AwsAccountId": "aws-acct-id-1", 
        "AwsRegion": "us-east-1", 
        "SipMediaApplicationId": "sip-media-app-id-1", 
        "Participants": [ 
            { 
                "CallId": "call-id-1", 
                "ParticipantTag": "LEG-A", 
                "To": "e164PhoneNumber", 
                "From": "e164PhoneNumber", 
                "Direction": "Inbound/Outbound", 
                "StartTimeInMilliseconds": "1641998241509", 
                "Status": "Connected/Disconnected" 
            } 
        ] 
    } 
}
```

**SchemaVersion**  
The version of schema used to create this event object.

**Sequence**  
The sequence of events that invoke your AWS Lambda function. Each time your function is invoked during a call, the sequence is incremented.

**InvocationEventType**  
The type of event that triggers an AWS Lambda invocation. For more information, see [Event types](#pstn-event-types) later in this topic.

**CallDetails**  
Information about the call associated with the AWS Lambda invocation.

**TransactionId**  
The ID of a call associated with an AWS Lambda invocation.

**AwsAccountId**  
The AWS account ID associated with the SIP media application that resulted in the call routing.

**SipMediaApplicationId**  
The ID of the SIP media application associated with the call.

**Participants**  
Information about the participants on the call that invokes an AWS AWS Lambda function.

**CallId**  
A unique ID assigned to each participant.

**ParticipantTag**  
Each call participant gets a tag, `LEG-A` or `LEG-B`.

**To**  
The participant "to" phone number, in E.164 format.

**From**  
The participant “from” phone number, in E.164 format.

**Direction**  
The direction that a call leg comes from. `Inbound` represents a call made to the Audio Service. `Outbound` represents a call made from the Audio Service.

**StartTimeInMilliseconds**  
The epoch time in milliseconds, starting when a participant joins a call.

**Status**  
Whether a participant is `Connected` or `Disconnected`

## Event types
<a name="pstn-event-types"></a>

The Audio Service invokes the Lambda function with these event types:

**NEW\$1INBOUND\$1CALL**  
A new call has been initiated by a phone number associated with your SIP media application.

**NEW\$1OUTBOUND\$1CALL**  
A new outbound call has been made via the [CreateSipMediaApplicationCall](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html) API.

**ACTION\$1SUCCESSFUL**  
An action returned from your AWS Lambda function has succeeded. Successful actions include `ActionData` that matches the successful action.   

```
    "ActionData": {
        // The previous successful action 
    },
```

**ACTION\$1FAILED**  
An action returned from your AWS Lambda function did not succeed. Unsuccessful actions include `ActionData` that matches the failed action, an error type, and an error message that describes the failure:  

```
    "ActionData": {
        // The previous unsuccessful action
        "ErrorType": "error-type",
        "ErrorMessage": "error message"
    },
```

**ACTION\$1INTERRUPTED**  
An action in the process of running was interrupted by an [ UpdateSipMediaApplicationCall](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API invocation. The `ActionData` includes the interrupted actions:   

```
"ActionData": {
        // The action that was interrupted
    },
```

**HANGUP**  
A user or the application hung up a call leg. The `ActionData` includes these details about the event:  

```
   "ActionData": {
        "Type": "Hangup",
        "Parameters": {
            "SipResponseCode": 486,
            "CallId": "c70f341a-adde-4406-9dea-1e01d34d033d",
            "ParticipantTag": "LEG-A"
        }
    },
```  
**Type**  
Hangup.  
**Parameters**  
The information about the `HANGUP` event:   
+ **SipResponseCode** – The response code associated with the event. The most common codes are:
  + **0** – Normal clearing
  + **480** – No answer
  + **486** – User busy
+ **CallId** The ID of the participant that hung up.
+ **ParticipantTag** The tag of the participant that hung up.

**CALL\$1ANSWERED**  
The Audio Service answered an incoming call was answered. This event is returned on a dial-out call unless the call is bridged.

**INVALID\$1LAMBDA\$1RESPONSE**  
The response provided to the last AWS Lambda invocation caused a problem. The `ActionData` includes these additional fields:  

```
    "ErrorType": "error-type-1", 
    "ErrorMessage": "error-msg-1"
```

**DIGITS\$1RECEIVED**  
The application received DTMF digits after completion of a `ReceiveDigits` action. The `ActionData` includes the received digits.  

```
    "ActionData": {
        "ReceivedDigits": ###
        // The ReceiveDigits action data
    },
```

**CALL\$1UPDATE\$1REQUESTED**  
The [UpdateSipMediaApplicationCall](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API was invoked. The `ActionData` includes information about the update request:  

```
    "ActionData": {
        "Type": "CallUpdateRequest", 
        "Parameters": {
            "Arguments": {
                "leg": "LEG-A"
                }
            }
        },
    }
```

**RINGING**  
A call leg is ringing

# Understanding Amazon Chime SDK PSTN audio service actions
<a name="about-actions"></a>

In the PSTN audio service, SIP media applications trigger AWS Lambda functions. In turn, the AWS Lambda functions can return a list of instructions known as *actions*. An action is an item that you want to run on a leg of a phone call, such as sending or receiving digits, joining a meeting, and so on. Actions can also return data, so you can think of actions as objects with data fields. For more information about the actions invoked by the PSTN audio service, see [Understanding telephony events for Amazon Chime SDK PSTN audio service](pstn-invocations.md).

# Learn about the telephony events that invoke AWS Lambda functions for the Amazon Chime SDK PSTN audio service
<a name="invoking-Lambda"></a>

The Audio Service invokes AWS Lambda functions in response to different events. Each invocation specifies an invocation event type and provides the call details, including its participants, if applicable. The following topics describe the Audio Service events that invoke AWS Lambda functions. 

# Making an outbound call for using Amazon Chime SDK PSTN audio service
<a name="use-create-call-api"></a>

To create an outbound call, you use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html) API. The API invokes the endpoint of a specified `SIP media application ID`. Customers can control the flow of the call by giving different signaling and [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_SipMediaApplication.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_SipMediaApplication.html) actions from the endpoint. 

In the event of a successful response, the API returns a 202 http status code along with a transactionId, which you can use with the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API to update an in-progress call.

The following diagram shows the invocations made to the AWS Lambda function endpoint for an outbound call.

![\[Diagram showing the programming flow for invocations made to the AWS Lambda endpoint.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sip-api-1.png)


The endpoint configured for the SIP media application is invoked for different statuses of the outbound call. When a customer initiates a call, The Amazon Chime SDK invokes the endpoint with a `NEW_OUTBOUND_CALL` invocation event type. 

This example shows a typical invocation event for a `NEW_OUTBOUND_CALL`.

```
{
    "SchemaVersion": "1.0",
        "Sequence": 1,
        "InvocationEventType": "NEW_OUTBOUND_CALL",
        "CallDetails": {
            "TransactionId": "transaction-id",
            "AwsAccountId": "aws-account-id",
            "AwsRegion": "us-east-1",
            "SipApplicationId": "sip-application-id",
            "Participants": [
                {
                    "CallId": "call-id-1",
                    "ParticipantTag": "LEG-A",
                    "To": "+1xxxx",
                    "From": "+1xxxxxxx",
                    "Direction": "Outbound",
                    "StartTimeInMilliseconds": "159700958834234"
                }
            ]
    }
}
```

Any response for an event related AWS Lambda invocation is ignored.

When we receive a `RINGING` notification from the receiver, the Amazon Chime SDK invokes the configured endpoint again. 

This example shows a typical invocation event for `RINGING`.

```
{
    "SchemaVersion": "1.0",
        "Sequence": 1,
        "InvocationEventType": "RINGING",
        "CallDetails": {
            "TransactionId": "transaction-id",
            "AwsAccountId": "aws-account-id",
            "AwsRegion": "us-east-1",
            "SipApplicationId": "sip-application-id",
            "Participants": [
                {
                    "CallId": "call-id-1",
                    "ParticipantTag": "LEG-A",
                    "To": "+1xxxx",
                    "From": "+1xxxxxxx",
                    "Direction": "Outbound",
                    "StartTimeInMilliseconds": "159700958834234"
                }
           ]
    }
}
```

Any response for an event related AWS Lambda invocation is ignored.

If the receiver doesn't answer the call, or the call fails due to an error, Chime disconnects the call and invokes the endpoint with the `Hangup` event type. For more information about the `Hangup` event type, refer to [Ending a call using the Amazon Chime SDK PSTN audio service](case-5.md). 

If the call is answered, Chime invokes the endpoint with the `CALL_ANSWERED` action. This example shows a typical invocation event.

```
{
  "SchemaVersion": "1.0",
    "Sequence": 1,
    "InvocationEventType": "CALL_ANSWERED",
    "CallDetails": {
        ""TransactionId": "transaction-id",
            "AwsAccountId": "aws-account-id",
            "AwsRegion": "us-east-1",
            "SipApplicationId": "sip-application-id",
            "Participants": [
                {
                    "CallId": "call-id-1",
                    "ParticipantTag": "LEG-A",
                    "To": "+1xxxx",
                    "From": "+1xxxxxxx",
                    "Direction": "Outbound",
                    "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

At this point, you can return actions by responding to the invocation with an action list. If you don’t want to run any actions, respond with an empty list. You can respond with a maximum of 10 actions for each AWS Lambda invocation, and you can invoke a Lambda function 1,000 times per call. For more information about responding with sets of actions, refer to [Responding to invocations with action lists using the Amazon Chime SDK PSTN audio service](invoke-on-call-leg.md).

# Receiving an inbound call using the Amazon Chime SDK PSTN audio service
<a name="case-1"></a>

When a `NEW_INCOMING_CALL` event occurs, the Audio Service creates a unique `TransactionID` and unique `CallID` that persist until the `HANGUP` event occurs.

You can respond in several ways to a `NEW_INCOMING_CALL` event. For example:
+ Send `PlayAudio` or `RecordAudio` actions and automatically answer the call. 
+ Send a `Pause` action.
+ Send a `Hangup` action, in which case the call isn’t answered and the customer isn’t charged.
+ Send a `CallAndBridge` action and add another user to the call.
+ Do nothing, the call attempt times out after 30 seconds.

When a new inbound call is received, the SIP media application invokes an AWS Lambda function with this payload.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 2,
    "InvocationEventType": "NEW_INBOUND_CALL"
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

# Specifying actions in response to telephony events for the Amazon Chime SDK PSTN audio service
<a name="use-case-2"></a>

In the Audio Service, SIP media applications invoke AWS Lambda functions. In turn, a Lambda function can return a list of instructions known as *actions*. An action is an item that you want to run on a leg of a phone call, such as sending or receiving digits, joining a meeting, and so on. For more information about the actions invoked by the PSTN audio service, see [Understanding telephony events for Amazon Chime SDK PSTN audio service](pstn-invocations.md).

When a SIP media application successfully runs a list of actions, the application calls the AWS Lambda function with an invocation event type of `ACTION_SUCCESSFUL`. If any of the actions fail to complete, the SIP media application calls the AWS Lambda function with the `ACTION_FAILED` event.

The SIP media application only returns `ACTION_SUCCESSFUL` if all the actions on the list succeed. If any of the actions in the list fail, the SIP media application invokes the AWS Lambda function with the `ACTION_FAILED` event and clears the remaining actions in the list after the failed one. Then the SIP media application runs the next action returned by the AWS Lambda function. You use the `ActionData` key to identify which call invoked the function.

The following event shows a sample payload for the `ACTION_SUCCESSFUL` invocation event type after a `PlayAudioAndGetDigits` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "PlayAudioAndGetDigits",
        "Parameters" : {
            "CallId": "call-id-1",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "failure-audio-file.wav"
            },
            "FailureAudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "failure-audio-file.wav"
            },
            "MinNumberOfDigits": 3,
            "MaxNumberOfDigits": 5,
            "TerminatorDigits": ["#"],
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "Repeat": 3,
            "RepeatDurationInMilliseconds": 10000
        },
        "ReceivedDigits": "123"
    }
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
                }
            ]
        }
    }
}
```

When any action in a list fails to complete successfully, the SIP media application invokes the AWS Lambda function to notify you of the failure, and to get a new set of actions to run on that call. The following event shows the sample payload for the `ACTION_FAILED` invocation event type after a `PlayAudio` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type": "PlayAudio",
        "Parameters" : {
            "CallId": "call-id-1",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file.wav"            
            }
        },
        "ErrorType": "InvalidAudioSource",
        "ErrorMessage": "Audio Source parameter value is invalid."
    }
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
}
```

# Receiving caller input for the Amazon Chime SDK PSTN audio service
<a name="case-4"></a>

You use the `ReceiveDigits` action to collect inbound DTMF digits and match them against a regular expression. When the SIP media application receives digits that match the regular expression, it invokes a AWS Lambda function with an `ACTION_SUCCESSFUL` event. The collected digits appear in the `ReceivedDigits` value in the `ActionData` object.

For example:

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "ReceivedDigits": "",
        "Type": "ReceiveDigits",
        "Parameters": {
            "CallId": "call-id-1",
            "InputDigitsRegex": "^\d{2}#$",
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "FlushDigitsDurationInMilliseconds": 10000
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

Once the caller enters digits that match your regular expression pattern, the SIP media application invokes an AWS Lambda function that returns the following type of payload:

```
{
    "SchemaVersion": "1.0",
    "Sequence": 5,
    "InvocationEventType": "DIGITS_RECEIVED",
    "ActionData": {
        "ReceivedDigits": "11#",
        "Type": "ReceiveDigits",
        "Parameters": {
            "CallId": "call-id-1",
            "InputDigitsRegex": "^\d{2}#$",
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "FlushDigitsDurationInMilliseconds": 10000
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# Updating in-progress calls for Amazon Chime SDK PTSN audio
<a name="update-sip-call"></a>

As part of the PSTN audio service, SIP media applications allow you to set actions that are run on a call by invoking user-defined Lambda functions based on the call events, such as an incoming call or DTMF digits. The [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API allows you to trigger a Lambda function at any time while a call is active, replacing the current actions with new actions returned by the invocation.

**Workflow**  
You use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API in variety of cases, such as adding participants to a meeting, muting and unmuting user, disconnecting them, and so on. The following use case describes a typical workflow.

A user calls and listens to music while Amazon Chime SDK sets up the meeting. Once setup completes, Amazon Chime SDK stops the audio and admits the caller into the meeting. Next, assume the use of a separate system, `MyMeetingService`, that manages meetings. Every incoming call should be put on hold. Chime notifies MyMeetingService about incoming calls, and MyMeetingService then creates an attendee for each call, and when the MyMeetingService is ready to start the meeting, it notifies the SIP media application and provides a token for joining the meeting.

To handle this case, the Lambda function has to implement the following logic. 
+ When a new incoming call arrives, the Lambda is invoked with a `NEW_INBOUND_CALL` event. The Lambda calls the `MyMeetingService` and passes the `transactionId` that identifies the current call, and returns the `PlayAudio` action.
+ When the `MyMeetingService` is ready to add the caller to the meeting, the service calls the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API and passes the call's `transactionId` and `JoinToken` as part of its arguments. This API call triggers the Lambda function again, now with the `CALL_UPDATE_REQUESTED` event. The MyMeetingService passes the `JoinToken` to the Lambda function as part of the event, and the token is used to return the `JoinChimeMeeting` action to the SIP media application, which interrupts the `PlayAudio` action and connects the caller to the meeting.

![\[Diagram showing the flow of data in the UpdateSipMediaApplicationCall API.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/update-sip-call-flow3.png)


**Note**  
The [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API returns HTTP 202 (Accepted). The SIP media application confirms that the call is in progress and can be updated, so it attempts to invoke the Lambda function. The invocation is performed asynchronously, so a successful response from the API doesn’t guarantee that the Lambda function has started or completed.

The following example shows the request syntax.

```
{
    "SipMediaApplicationId": "string",
    "TransactionId": "string",
    "Arguments": {
        "string": "string"
    } 
}
```

**Request parameters**
+ `SipMediaApplicationId` – The ID of the SIP media application that handles the call. 
+ `TransactionId` – The ID of the call transaction. For inbound calls, the `TransactionId` can be obtained from the `NEW_INCOMING_CALL` event passed to the Lambda function on its first invocation. For outbound calls, `TransactionId` is returned in the response of [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html). 
+ **Arguments** – Custom arguments made available to the Lambda function as part of the `CallUpdateRequest` action data. Can contain 0 to 20 key-value pairs.

The following example shows a typical request.

```
aws chime update-sip-media-application-call --sip-media-application-id feb37a7e-2b66-49fb-b2dd-30f4780dc36d --transaction-id 1322a4e7-c106-4e70-aaaf-a8fa4c77c0cb --arguments '{"JoinToken": "abc123"}'
```

**Response syntax**

```
{
  "SipMediaApplicationCall": {
  "TransactionId": "string"
  }
}
```

**Response elements**
+ **TransactionId** – The ID of the call transaction, the same ID as the request.

The following example shows a `CALL_UPDATE_REQUESTED` invocation event.

```
{
  "SchemaVersion": "1.0",
  "Sequence": 2,
  "InvocationEventType": "CALL_UPDATE_REQUESTED",
  "ActionData": {
    "Type": "CallUpdateRequest",
    "Parameters": {
      "Arguments": {
        "string": "string"
      }
    }
  },
  "CallDetails": {
    ...
  }
}
```

**Event elements**
+ **SchemaVersion** – The version of the JSON schema (1.0)
+ **Sequence** – The sequence number of the event in the call
+ **InvocationEventType** – The type of Lambda invocation event, in this case, `CALL_UPDATE_REQUESTED`
+ **ActionData** – The data associated with the `CallUpdateRequest` action.
  + **Type** – The type of action, in this case, `CallUpdateRequest`
  + **Parameters** – The parameters of the action
    + **Arguments** – The arguments passed as part of the `UpdateSipMediaApplicationCall` API request
+ **CallDetails** – The information about the current call state

**Understanding interruptible and non-interruptable actions**  
When a Lambda function returns a new list of actions while existing actions run, all actions that follow the in-progress action are replaced with the new actions. In some cases, the Lambda function interrupts in-progress actions in order to run new actions immediately.

The following diagram shows a typical example. Text below the digram explains the logic.

![\[Diagram showing how actions can be replaced during an ongoing SIP media application call.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/update-sip-actions.png)


If Action 2 is interruptible, we stop it and run new Action 1 instead.

If Action 2 is not interruptible, it completes before the new Action 1 starts.

In both cases, Action 3 isn't run.

If something interrupts an action, the Lambda function is invoked with an `ACTION_INTERRUPTED` event. This event is used for informational purpose only. The SIP media application ignores all actions returned by this invocation.

Types of interruptible actions:
+ `PlayAudio`
+ `RecordAudio`
+ `Pause`

**Sample Lambda function**  
This example shows a typical Lambda function that plays an audio file, passes a join token, and updates the call.

```
const MMS = require('my-meeting-service');
const myMeetingServiceClient = new MMS.Client();

exports.handler = async (event) => {
    console.log('Request: ' + JSON.stringify(event));
    
    const playAudio = () => {
      return {
        Type: 'PlayAudio',
        Parameters: {
          ParticipantTag: 'LEG-A',
          AudioSource: {
            Type: 'S3',
            BucketName: 'chime-meetings-audio-files-bucket-name',
            Key: 'welcome.wav'
          }
        }
      }
    }
    
    const joinChimeMeeting = (joinToken) => {
      return {
        Type: 'JoinChimeMeeting',
        Parameters: {
          JoinToken: joinToken
        }
      }
    }
    
    const response = (...actions) => {
      const r = {
        SchemaVersion: '1.0',
        Actions: actions
      };
      console.log('Response: ' + JSON.stringify(r));
      return r;
    };
    
    switch (event.InvocationEventType) {
      case 'NEW_INBOUND_CALL': 
        myMeetingServiceClient.addPendingCall(event.CallDetails.TransactionId);         
        return response(playAudio());      
      case 'CALL_UPDATE_REQUESTED':
        const joinToken = event.ActionData.Parameters.Arguments['JoinToken']
        return response(joinChimeMeeting(joinToken));
      default:
        return response();
    }
}
```

# Ending a call using the Amazon Chime SDK PSTN audio service
<a name="case-5"></a>

You can use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html) API to end an outbound call. The API invokes the endpoint of a specified **SIP media application ID**. Customers can control the flow of the call by returning actions to the SIP media application.

In the event of a successful response, the API returns a 202 http status code along with the `transactionId`, which you can use with the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API to update an in-progress call.

The following diagram shows the invocations made to the AWS Lambda function endpoint for an outbound call.

![\[The flow of data when you invoke the CreateSipMediaApplicationCall API. The API invokes a different endpoint when the status of an outbound call changes.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sip-api-1.png)


The endpoint configured for the SIP media application is invoked for different statuses of the outbound call. When a customer ands a call, the Amazon Chime SDK invokes the endpoint with a `HANGUP` invocation event type. 

This example shows a typical invocation event for a `HANGUP`.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 6,
    "InvocationEventType": "HANGUP",
    "ActionData": {
        "Type": "Hangup",
        "Parameters": {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "Direction": "Inbound",
                 "To": "+12065551212",
                "From": "+15105550101",
                "StartTimeInMilliseconds": "1597009588",
                "Status": "Disconnected"
            }
        ]
    }
}

// if LEG-B receives a hangup in a bridged call, such as a meeting ending
{
    "SchemaVersion": "1.0",
    "Sequence": 6,
    "InvocationEventType": "HANGUP",
    "ActionData": {
        "Type": "ReceiveDigits",
        "Parameters": {
            "CallId": "call-id-2",
            "ParticipantTag": "LEG-B"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "Leg-A",
                 "To": "+12065551212",
                "From": "+15105550101",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "1597009588",
                "Status": "Connected"
            },
            {
                "CallId": "call-id-2",
                "ParticipantTag": "Leg-B",
                "To": "+17035550122",
                "From": "SMA",
                "Direction": "Outbound",
                "StartTimeInMilliseconds": "15010595",
                "Status": "Disconnected"
            }
        ]
    }
}
```

# Understanding end-to-end calls for the Amazon Chime SDK PSTN audio service
<a name="use-cases"></a>

This use case provides example code for receiving a phone call from a PSTN caller, greeting the caller with an audio message, getting the meeting PIN from the caller, playing audio, and joining the caller to the meeting.

**Invocation events and actions**  
The Audio Service passes invocation events to AWS Lambda functions as JSON objects. The objects include the invocation event type and any relevant metatdata. The AWS Lambda function also returns SIP media application actions as JSON objects, and those objects include an action type and any relevant metadata.

The following table lists the invocation events, and the possible `ActionData.Type`, when you receive an invocation event.


|  Invocation event  |  ActionData.Type  | 
| --- | --- | 
|  ACTION\$1SUCCESSFUL  |  CallAndBridge ReceiveDigits PlayAudio PlayAudioAndGetDigits  JoinChimeMeeting ModifyChimeMeetingAttendees RecordMeeting  | 
|  ACTION\$1FAILED  |  CallAndBridge PlayAudio PlayAudioAndGetDigits ModifyChimeMeetingAttendees RecordMeeting  | 
| HANGUP |  HangUp  | 
|  DIGITS\$1RECEIVED  | ReceiveDigits | 

**Note**  
To implement the following use case, you need at least one phone number in your Amazon Chime SDK inventory, a SIP media application managed object that uses a AWS Lambda function with an Amazon Resource Name (ARN), and a SIP rule that uses the phone number as its trigger.

When Amazon Chime SDK receives a call to the phone number specified in the rule, the PSTN audio service invokes a AWS Lambda function with the `NEW_INBOUND_CALL` invocation event type.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 1,
    "InvocationEventType": "NEW_INBOUND_CALL",
    "CallDetails": {
        "TransactionId": "transaction-id",
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+11234567890",
                "From": "+19876543210",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

You can program the AWS Lambda function to validate call details and store them for future use. For a `NEW_INBOUND_CALL` event, the AWS Lambda function responds with a set of actions that play a welcome prompt and ask for the meeting PIN.

Audio files have the following requirements:
+ You must play audio files from an Amazon Simple Storage Service (S3) bucket. The S3 bucket must belong to the same AWS account as the SIP media application. In addition, you must give the `s3:GetObject` permission to the Amazon Chime SDK Voice Connector service principal—`voiceconnector.chime.amazonaws.com`. You can use the S3 console or the command-line interface (CLI) to do that.
+ You must use PCM WAV files of no more than 50 MB in size. The Amazon Chime SDK recommends 8 KHz mono.
+ The S3 metadata for each WAV file must contain `{'ContentType': 'audio/wav'}`.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type" : "PlayAudio",    
            "Parameters" : {
                "CallId": "call-id-1",
                
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "chime-meetings-audio-files-bucket-name",
                    "Key": "welcome-to-meetings.wav"
                }
            }
        },
        {
            "Type": "PlayAudioAndGetDigits",
            "Parameters" : {
                "ParticipantTag": "LEG-A",
                
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "chime-meetings-audio-files-bucket-name",
                    "Key": "enter-meeting-pin.wav"
                },
                "FailureAudioSource": {
                    "Type": "S3",
                    "BucketName": "chime-meetings-audio-files-bucket-name",
                    "Key": "invalid-meeting-pin.wav"
                },
                "MinNumberOfDigits": 3,
                "MaxNumberOfDigits": 5,
                "TerminatorDigits": ["#"],
                "InBetweenDigitsDurationInMilliseconds": 5000,
                "Repeat": 3,
                "RepeatDurationInMilliseconds": 10000
            }
        }
    ]
}
```

The SIP media application runs these actions on call leg A. Assuming the `PlayAudioAndGetDigits` action receives the digits, the SIP media application invokes the AWS Lambda function with the `ACTION_SUCCESSFUL` event type.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 2,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "PlayAudioAndGetDigits",
        "Parameters" : {
            "ParticipantTag": "LEG-A",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "chime-meetings-audio-files-bucket-name",
                "Key": "enter-meeting-pin.wav"
            },
            "FailureAudioSource": {
                "Type": "S3",
                "BucketName": "chime-meetings-audio-files-bucket-name",
                "Key": "invalid-meeting-pin.wav"
            },
            "MinNumberOfDigits": 3,
            "MaxNumberOfDigits": 5,
            "TerminatorDigits": ["#"],
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "Repeat": 3,
            "RepeatDurationInMilliseconds": 10000
        },
        "ReceivedDigits": "12345" // meeting PIN
    },
    "CallDetails": {
        ... // same as in previous event
    }
}
}
```

You can program an AWS Lambda function to identify the caller based on the `CallDetails` data. You can also validate the meeting PIN received earlier. Assuming a correct PIN, you then use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateMeeting.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateMeeting.html) and [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateAttendee.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateAttendee.html) APIs to create the Amazon Chime SDK meeting and generate the join token used by the meeting attendee. The AWS Lambda function responds with the action to join the Amazon Chime SDK meeting.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type": "JoinChimeMeeting",
            "Parameters": {
                "JoinToken": "meeting-attendee-join-token"
            }
        }
    ]
}
```

Assuming the `JoinToken` is valid, the SIP media application joins the Amazon Chime SDK meeting and invokes a AWS Lambda function with the `ACTION_SUCCESSFUL` event, where `CallDetails` contains the data from the SIP media application and the Chime Media service (`LEG-B`) 

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type" : "JoinChimeMeeting",
        "Parameters" : {
            "JoinToken": "meeting-attendee-join-token"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id", 
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+11234567890",
                "From": "+19876543210",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            },
            {
                "CallId": "call-id-2",
                "ParticipantTag": "LEG-B",
                "To": "SMA",
                "From": "+17035550122",
                "Direction": "Outbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Connected"
            }
        ]
    }
}
```

If you want to stop running actions on the call or call leg at this point, you can respond with an empty set of actions.

```
{
    "SchemaVersion": "1.0"
    "Actions": []
}
```

After the caller hangs up, the SIP media application invokes the AWS Lambda function with the `HANGUP` event. 

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "HANGUP",
    "ActionData": {
        "Type": "Hangup",
        "Parameters": {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A"
        }
    },
    "CallDetails": {
        "TransactionId": "transaction-id", 
        "AwsAccountId": "aws-account-id",
        "AwsRegion": "us-east-1",
        "SipRuleId": "sip-rule-id",
        "SipApplicationId": "sip-application-id",
        "Participants": [
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                "To": "+11234567890",
                "From": "+19876543210",
                "Direction": "Inbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Disconnected"
            },
            {
                "CallId": "call-id-2",
                "ParticipantTag": "LEG-B",
                "To": "SMA",
                "From": "+17035550122",
                "Direction": "Outbound",
                "StartTimeInMilliseconds": "159700958834234",
                "Status": "Disconnected"
            }
        ]
    }
}
```

If you respond to a `Hangup` event with an action, the SIP media application ignores the action if no other `Participants` show a `Status` of `Connected`.

# Responding to invocations with action lists using the Amazon Chime SDK PSTN audio service
<a name="invoke-on-call-leg"></a>

You can respond to an AWS Lambda invocation event with a list of actions to run on the individual participants in a call. You can respond with a maximum of 10 actions for each AWS Lambda invocation, and you can invoke an AWS Lambda function 1,000 times per call.

By default, SIP media applications time out if a Lambda function doesn't respond after 20 seconds.

The following example shows the general response structure.

```
{
    "SchemaVersion": "1.0",
    "Actions": [        
        {
            "Type": "PlayAudio",
            "Parameters": {
                "ParticipantTag": "LEG-A",
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "bucket-name",
                    "Key": "audio-file.wav"
                }
            }
        },
        {
            "Type": "RecordAudio",
            "Parameters": {
                "DurationInSeconds": "10",
                "RecordingTerminators": ["#"],
                "RecordingDestination": {
                    "Type": "S3",
                    "BucketName": "bucket-name"
                }
            }
        }
    ]
}
```

When the AWS Lambda function returns the list of actions to the SIP media application, the following operations occur:

1. The application finishes running the current action on a call.

1. The application then replaces the old action set with a new set of actions received from the latest invocation event.

If the SIP media application receives a `NULL` action set, it keeps the existing actions. 

# Supported actions for the Amazon Chime SDK PSTN audio service
<a name="specify-actions"></a>

You can specify different types of signaling and media actions in a response from an AWS Lambda function. Each action has different properties. The following topics provide example code and explain how to use the actions.

**Topics**
+ [Using TransactionAttributes](transaction-attributes.md)
+ [Using call recording](sip-apps-call-record.md)
+ [CallAndBridge](call-and-bridge.md)
+ [Hangup](hangup.md)
+ [JoinChimeMeeting](join-chime-meeting.md)
+ [ModifyChimeMeetingAttendee (muting and unmuting audio)](mute-unmute.md)
+ [Pause](pause.md)
+ [PlayAudio](play-audio.md)
+ [PlayAudioAndGetDigits](play-audio-get-digits.md)
+ [ReceiveDigits](listen-to-digits.md)
+ [RecordAudio](record-audio.md)
+ [SendDigits](send-digits.md)
+ [Speak](speak.md)
+ [SpeakAndGetDigits](speak-and-get-digits.md)
+ [StartBotConversation](start-bot-conversation.md)

# Using TransactionAttributes
<a name="transaction-attributes"></a>

You use the `TransactionAttributes` data structure to store application-specific information, such as call states or meeting IDs, and then pass that data to AWS Lambda invocations. This structure removes the need for storing data in external databases such as Amazon DynamoDB. 

`TransactionAttributes` are [JSON Objects](https://www.w3schools.com/js/js_json_objects.asp) that contain key/value pairs. The objects can contain a maximum of 100 key/value pairs, and the objects have a maximum payload size of 20 KB. The data in a `TransactionAttributes` structure persists for the life of a transaction.

When an AWS Lambda function passes `TransactionAttributes` to a SIP media application, the application updates any stored attributes. If you pass a `TransactionAttributes` object with an existing key set, you update the stored values. If you pass a different key set, you replace the existing values with the values from that different key set. Passing an empty map ( `{}` ) erases any stored values.

**Topics**
+ [Setting TransactionAttributes](set-trans-attributes.md)
+ [Updating TransactionAttributes](update-trans-attributes.md)
+ [Clearing TransactionAttributes](clear-trans-attributes.md)
+ [Handling ACTION\$1SUCCESSFUL events](attribute-trans-success.md)
+ [Invalid inputs](attribute-trans-invalid.md)

# Setting TransactionAttributes
<a name="set-trans-attributes"></a>

The following example shows how to set `TransactionAttributes` alongside a [PlayAudio](play-audio.md) action and pass the attributes from an AWS Lambda function to a SIP media application.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type": "PlayAudio",
            "Parameters": {
                "ParticipantTag": "LEG-A",
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "mtg1-sipmedia-app-iad",
                    "Key": "Welcome3.wav"
                }
            }
        }
    ],
    "TransactionAttributes": {
        "key1": "value1",
        "key2": "value2"
    }
}
```

# Updating TransactionAttributes
<a name="update-trans-attributes"></a>

To modify stored `TransactionAttributes`, update the contents of the JSON object with new values. In the following example, the keys `NewKey1` and `NewKey2` are added to the `TransactionAttributes`. These keys are paired with the values `NewValue1` and `NewValue2`, respectively.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type": "PlayAudio",
            "Parameters": {
                "ParticipantTag": "LEG-A",
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "mtg1-sipmedia-app-iad",
                    "Key": "Welcome3.wav"
                }
            }
        }
    ],
    "TransactionAttributes": {
        "NewKey1": "NewValue1",
        "NewKey2": "NewValue2"
    }
}
```

If, in the previous example, you passed `NewValue1` to `key1`, the existing value of `key1` would be replaced with `NewValue1`. However, passing a value to `NewKey1` creates a new key/value pair.

# Clearing TransactionAttributes
<a name="clear-trans-attributes"></a>

To clear the contents of the `TransactionAttributes` object, pass the `TransactionAttributes` field with an empty JSON Object:

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type": "PlayAudio",
            "Parameters": {
                "ParticipantTag": "LEG-A",
                "AudioSource": {
                    "Type": "S3",
                    "BucketName": "mtg1-sipmedia-app-iad",
                    "Key": "Welcome3.wav"
                }
            }
        }
    ],
    "TransactionAttributes": {
    }
}
```

**Note**  
You can't clear data from a `TransactionAttributes` structure by setting its value to `null`. Also, omitting the `TransactionAttribute` structure doesn't clear its data. Always pass an empty JSON object with `TransactionAttributes` to clear data from the object.

# Handling ACTION\$1SUCCESSFUL events
<a name="attribute-trans-success"></a>

The following example shows how a successful [PlayAudio](play-audio.md) sends the stored `TransactionAttributes` as part of the `CallDetails `.

```
{ 
    "SchemaVersion": "1.0", 
    "Sequence": 2, 
    "InvocationEventType": "ACTION_SUCCESSFUL", 
    "ActionData": { 
        "Type": "PlayAudio", 
        "Parameters": { 
            "AudioSource": { 
                "Type": "S3", 
                "BucketName": "mtg1-sipmedia-app-iad", 
                "Key": "Welcome3.wav" 
            }, 
            "Repeat": 1, 
            "ParticipantTag": "LEG-A" 
        } 
    }, 
    "CallDetails": { 
        "TransactionId": "mtg1-tx-id", 
        "TransactionAttributes": { 
            "key1": "value1", 
            "key2": "value2" 
        }, 
        "AwsAccountId": "166971021612", 
        "AwsRegion": "us-east-1", 
        "SipRuleId": "aafbd402-b7a2-4992-92f8-496b4563c492", 
        "SipMediaApplicationId": "e88f4e49-dd21-4a3f-b538-bc84eae11505", 
        "Participants": [ 
            { 
                "CallId": "bbff30c5-866a-41b5-8d0a-5d23d5e19f3e", 
                "ParticipantTag": "LEG-A", 
                "To": "+14345550101", 
                "From": "+14255550199", 
                "Direction": "Inbound", 
                "StartTimeInMilliseconds": "1644539405907", 
                "Status": "Connected" 
            } 
        ] 
    } 
}
```

# Invalid inputs
<a name="attribute-trans-invalid"></a>

The following example shows an invalid input. In this case, the JSON object passes too many items to a SIP media application.

```
{ 
    "SchemaVersion": "1.0", 
    "Actions": [ 
        { 
            "Type": "PlayAudio", 
            "Parameters": { 
                "ParticipantTag": "LEG-A", 
                "AudioSource": { 
                    "Type": "S3", 
                    "BucketName": "mtg1-sipmedia-app-iad", 
                    "Key": "Welcome3.wav" 
                } 
            } 
        } 
    ], 
    "TransactionAttributes": { 
        "key1": "value1", 
        "key2": "value2", 
        "key3": "value3", 
        "key4": "value4", 
        "key5": "value5", 
        "key6": "value6", 
        "key7": "value7", 
        "key8": "value8", 
        "key9": "value9", 
        "key10": "value10", 
        "key11": "value11" 
    } 
}
```

The following example shows the response to the previously given input. This output is passed from a SIP media application back to the AWS Lambda function that invoked the application.

```
{ 
    "SchemaVersion": "1.0", 
    "Sequence": 2, 
    "InvocationEventType": "INVALID_LAMBDA_RESPONSE", 
    "CallDetails": { 
        "TransactionId": "mtg1-tx-id", 
        "AwsAccountId": "166971021612", 
        "AwsRegion": "us-east-1", 
        "SipRuleId": "aafbd402-b7a2-4992-92f8-496b4563c492", 
        "SipMediaApplicationId": "e88f4e49-dd21-4a3f-b538-bc84eae11505", 
        "Participants": [ 
            { 
                "CallId": "72cbec69-f098-45d8-9ad6-e26cb9af663a", 
                "ParticipantTag": "LEG-A", 
                "To": "+14345550101", 
                "From": "+14255550199", 
                "Direction": "Inbound", 
                "StartTimeInMilliseconds": "1644540839987" 
            } 
        ] 
    }, 
    "ErrorType": "TransactionAttributesInvalidMapSize", 
    "ErrorMessage": "Transaction Attributes has too many mappings. Maximum number of mappings is 10" 
}
```

# Using call recording
<a name="sip-apps-call-record"></a>

The call recording actions for SIP media applications enable you to build call recording and post-call transcription solutions for a variety of uses. For example, you can record customer-care calls and use them for training.

You use the call recording actions in concert with your SIP media applications. You can also use the actions on-demand or in response to a SIP event. 
+ To start on-demand recording of a call in your SIP media application, you use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice_chime_UpdateSipMediaApplication.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice_chime_UpdateSipMediaApplication.html) API to invoke your application and return the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_StartCallRecording.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_StartCallRecording.html) action. 
+ To start call recording in response to a SIP event, you return the `StartCallRecording` action in your application. 

You can pause and resume an in-progress recording. To pause, use the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_PauseCallRecording.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_PauseCallRecording.html) action. To resume, use the `ResumeCallRecording` action. Each time you pause or resume a recording, the action captures a tone that indicates the pause or resumption. When you pause, the action records silence, which Amazon Chime SDK uses to track the length of the pause and include the pauses in your bill. You can pause and resume recording as often as needed.

To stop call recording, you return the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_StopCallRecording.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_StopCallRecording.html) action. However, call recordings automatically stop when the call stops, and in that case you don’t need to explicitly return the `StopCallRecording` action. You can only start and stop recording once for an individual call leg.

Amazon Chime SDK delivers call recordings to an Amazon S3 bucket that you select. The bucket must belong to your AWS account. Once a call stops, the SIP media application delivers the recording to the folder specified in the `Destination` parameter of the [StartCallRecording](start-call-recording.md) action. The Amazon Chime SDK records calls in an open WAV format. Calls that record incoming and outgoing tracks use stereo mode, with the incoming track in the left channel and the outgoing track on the right channel. If you record only the incoming or outgoing track, the system uses mono mode.

**Note**  
Recordings made using this feature may be subject to laws or regulations regarding the recording of electronic communications. It is your and your end users’ responsibility to comply with all applicable laws regarding the recording, including properly notifying all participants in a recorded session or communication that the session or communication is being recorded, and obtaining their consent.

## Billing for call recording
<a name="call-billing"></a>

Amazon Chime SDK bills you per minute for the time that call recording is enabled for a call leg, and that time includes all pauses. You are billed for the call recording usage once the call recording is delivered to your Amazon S3 bucket.

# Recording audio tracks
<a name="record-legs"></a>

You can record just the incoming or outgoing tracks of call, or both tracks of a call.

This image shows a typical one-legged, or non-bridged, incoming call. 

![\[An incoming call that only communicates with a SIP media application.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/call-record-sma-one-leg.png)


The call only has one leg with a `callID` of **call-id-1**. The `INCOMING` audio track is the audio from the caller to the SIP media application. The `OUTGOING` audio track is the audio from the SIP media application to the caller. Your SIP media application specifies the `CallId` of the call that you want record. To record the participant who placed the call, you specify `INCOMING`. To record the participant who responds to a call, you specify `OUTGOING`. To record both participants, specify `BOTH`.

This image shows a typical bridged call with two participants.

![\[An incoming call that communicates with a SIP media application and a second participant.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/call-record-sma-bridged.png)


In this example, the call has two call legs, **call-id-1** and **call-id-2**, and **call-id-1** is bridged to **call-id-2**. This creates four audio tracks, the incoming and outgoing audio streams for both call IDs. You can specify which of the call IDs and audio tracks to record. For example, if you want to record the audio track from the called participant, you record the `INCOMING` audio track by specifying **call-id-2** as the `CallId` and `INCOMING` as the track.

If you want to record everything that the caller hears, you record the `OUTGOING` audio track by specifying **call-id-1** as the `CallId` and `OUTGOING` as the track. If you want to record all of the audio that the `Caller` said and heard, you record `BOTH` audio tracks by specifying `call-id-1` as the `CallId` and `BOTH` as the track.

# Sample use cases
<a name="recording-use-cases"></a>

SIP media applications provide call recording actions as building blocks. They give you the flexibility to build call-recording solutions for your business use cases. The following cases illustrate some common usage scenarios.

**Topics**
+ [Case 1: Recording a one-legged call that involves SIP actions](#recording-case-1)
+ [Case 2: Selectively recording audio in a bridged call](#recording-case-2)
+ [Case 3: Recording multiple call legs](#recording-case-3)
+ [Case 4: On-demand recording with pause and resume](#on-demand-pause-resume)

## Case 1: Recording a one-legged call that involves SIP actions
<a name="recording-case-1"></a>

You can record a caller and any audio generated by SIP media application actions, such as the [PlayAudio](play-audio.md) and [PlayAudioAndGetDigits](play-audio-get-digits.md) actions. During recording, if a caller presses a digit, the recording captures the tone of that digit. This example uses the `PlayAudioAndGetDigits` action, but the interactive voice response (IVR) can be a complex series of SIP media application actions.

In this example, the SIP media application records both audio tracks between the caller and the SIP media application itself. The recording starts when the call is established, and it stops when the caller hangs up. Billing starts when the call is established, and it stops when the caller hangs up.

![\[Diagram of a SIP media application recording two audio tracks, in this case, between a caller and the app itself.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sma-recording-case-1.png)


## Case 2: Selectively recording audio in a bridged call
<a name="recording-case-2"></a>

You can selectively record the audio track of a single call participant. You can use this feature to selectively enable call recording only for a specific participant.

In this example, the SIP media application records the incoming audio tracks between the called party and the SIP media application itself by specifying **call-id-2** as the `CallId` and `INCOMING` as the track. The call recording starts when the caller is bridged to the called party, and that's also when billing starts. The recording stops when the called party hangs up, and that's also when billing ends. This recording only has the called party’s audio track. 

![\[Diagram of a SIP media application selectively recording one track.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sma-recording-case-2.png)


## Case 3: Recording multiple call legs
<a name="recording-case-3"></a>

You can record multiple call legs. For example, say you bridge a call to a participant. When that participant hangs up, the phone call is bridged to another participant. You can enable call recording for all three call legs. 

This example shows three separate recording files. The recording for the first call leg captures the conversation between the caller, your application, and the two participants that were bridged into the call. The recording for the second call leg captures the conversation between the caller and the first participant. The recording for the third call leg captures the conversation between the caller and the second participant. 

This case creates three call legs, and billing applies to the start and end of each call leg. Put another way, the system delivers three recordings to your S3 bucket, and you're billed for each. 

![\[Diagram of a SIP media application recording multiple call legs.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sma-recording-case-3.png)


## Case 4: On-demand recording with pause and resume
<a name="on-demand-pause-resume"></a>

You can start, stop, pause, and resume call recording on-demand using the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_UpdateSipMediaApplicationCall.html) API. You can build a client application that calls the `UpdateSipMediaApplicationCall` API and invokes your SIP media application to return call recording actions.

Your end users use the client application to control the call recording. For example, in a call center, an agent would use a desktop client application to trigger call recording actions on-demand. In the call center example, the agent might ask the caller’s permission to record the phone call, and they can click in the client application to start recording once the caller agrees. In another example, the caller might need to provide information such as a social security number (SSN). However, the call center policy requires that the agent should not record information such as a customer’s SSN. The agent can click the application to pause the recording while the customer provides the information, then click again to resume the recording. Once the agent handles the caller’s request, the agent clicks the application to stop recording and hangs up the call.

In this use case, the SIP media application records the audio tracks between the caller and SIP media application. Since the `call-id-1` leg is bridged to the `call-id-2` leg, the system records the audio on both legs, caller and called. The recording and the billing start when the `UpdateSipMediaApplicationCall` API invokes the `StartCallRecording` action. The recording and the billing stop when the `UpdateSipMediaApplicationCall` API invokes the `StopCallRecording` action. As a reminder, pausing the recording does not change its duration, and you're billed for all pauses. 

![\[Diagram of a SIP media application recording on-demand with recording paused and resumed.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/sma-recording-on-demand.png)


# Call recording actions for SIP media applications
<a name="use-recording-apis"></a>

You can specify different call recording actions in a response from the AWS Lambda function of your SIP media application. The following topics provide example code and explain how to use the actions.

**Topics**
+ [StartCallRecording](start-call-recording.md)
+ [StopCallRecording](stop-call-recording.md)
+ [PauseCallRecording](pause-call-recording.md)
+ [ResumeCallRecording](resume-call-recording.md)

# StartCallRecording
<a name="start-call-recording"></a>

The `StartCallRecording` action starts the recording of a call leg. You start call recording in your SIP media applications, either on-demand or in response to a SIP event.
+ To start on-demand recording of a call, you use the `UpdateSipMediaApplication` API to invoke your application and return the `StartCallRecording` action.
+ To start call recording in response to a SIP event, you return the `StartCallRecording` action in your application. 

You specify whether you want to record the audio track for the incoming leg, the outgoing leg, or both. The following sections explain how to use the `StartCallRecording` action.

**Note**  
Recordings made using this feature may be subject to laws or regulations regarding the recording of electronic communications. It is your and your end users’ responsibility to comply with all applicable laws regarding the recording, including properly notifying all participants in a recorded session or communication that the session or communication is being recorded, and obtaining their consent.

**Topics**
+ [Requesting a StartCallRecording action](#request-start)
+ [Specifying a recording destination](#recording-destination)
+ [Granting Amazon S3 bucket permissions](#grant-s3-perms)
+ [Action successful response](#action-successful)
+ [Action error response](#action-error)

## Requesting a StartCallRecording action
<a name="request-start"></a>

The following example shows how to request the `StartCallRecording` action for `BOTH` tracks.

```
{
    "SchemaVersion": "1.0",
    "Actions": [
        {
            "Type": "StartCallRecording",
            "Parameters":
            {
                "CallId": "call-id-1",
                "Track": "BOTH",
                "Destination":
                {
                    "Type": "S3",
                    "Location": "valid-bucket-name-and-optional-prefix"
                }
            }
        }
    ]
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

**Track**  
*Description* – Audio `Track` of the call recording.  
*Allowed values* – `BOTH`, `INCOMING`, or `OUTGOING`  
*Required* – Yes  
*Default value* – None

**Destination.Type**  
*Description* – Type of destination. Only Amazon S3 is allowed.  
*Allowed values* – Amazon S3  
*Required* – Yes  
*Default value* – None

**Destination.Location**  
*Description* – A valid Amazon S3 bucket and an optional Amazon S3 key prefix. The bucket must have permissions to the Amazon Chime SDK Voice Connector service principal, voiceconnector.chime.amazonaws.com.  
*Allowed values* – A valid Amazon S3 path for which Amazon Chime SDK has permisions to the `s3:PutObject` and `s3:PutObjectAcl` actions.  
*Required* – Yes  
*Default value* – None

## Specifying a recording destination
<a name="recording-destination"></a>

Amazon Chime SDK delivers call recordings to your Amazon S3 bucket. The bucket must belong to your AWS account. You specify the bucket's location in the `Destination` parameter of the `StartCallRecording` action. The `Type` field in the the `Destination` parameter must be `S3`. The `Location` field consists of your Amazon S3 bucket, plus an optional object-key prefix in which the call recording is delivered. 

The SIP media application uses the specified `Location`, the call leg’s date and time, the transaction ID, and the call ID to format the Amazon S3 object key. The `StartCallRecording` action response returns the full Amazon S3 object key.

When you only provide the Amazon S3 bucket in the `Location` field, the SIP media application appends a default prefix, `Amazon-Chime-SMA-Call-Recordings`, to the Amazon S3 path. The SIP media application also appends the year, month, and day of the call's start time to help organize the recordings. The following example shows the general format of an Amazon S3 path with the default prefix. This example uses `myRecordingBucket` as the `Location` value.

```
myRecordingBucket/Amazon-Chime-SMA-Call-Recordings/2019/03/01/2019–03–01–17–10–00–010_c4640e3b–1478–40fb-8e38–6f6213adf70b_7ab7748e–b47d–4620-ae2c–152617d3333c.wav
```

The following example shows the data represented in the call recording Amazon S3 path.

```
s3Bucket/Amazon-Chime-SMA-Call-Recordings/year/month/date/year-month-date-hour-minute-second-millisecond_transactionId_callId.wav
```

When you provide the Amazon S3 bucket and object key prefix in the `Location` field, the SIP media application uses your object-key prefix in the destination Amazon S3 path instead of the default prefix. The following example shows the general format of a call recording Amazon S3 path with your prefix. For example, you can specify myRecordingBucket/technicalSupport/english as the `Location`. 

```
myRecordingBucket/technicalSupport/english/2019/03/01/2019–03–01–17–10–00–010_c4640e3b1478–40fb–8e38-6f6213adf70b_7ab7748e–b47d–4620–ae2c–152617d3333c.wav
```

The following example shows the data in the Amazon S3 path.

```
s3Bucket/yourObjectKeyPrefix/year/month/date/year-month-date-hour-minute-second-millisecond_transactionId_callId.wav
```

The recording sent to your Amazon S3 bucket contains additional [ Amazon S3 object metadata](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html) about the call leg. The following table lists the supported Amazon S3 object metadata.


| Name | Description | 
| --- | --- | 
| transaction-id | Transaction ID of the phone call | 
| call-id | CallId of participant in the CallDetails of the AWS Lambda function invocation | 
| recording-duration | Call recording duration in seconds | 
| recording-audio-file-format | Call recording audio file format represented as internet media type | 

## Granting Amazon S3 bucket permissions
<a name="grant-s3-perms"></a>

Your destination Amazon S3 bucket must belong to the same AWS account as your application. In addition, the action must give `s3:PutObject` and `s3:PutObjectAcl` permission to the Amazon Chime SDK Voice Connector service principal, `voiceconnector.chime.amazonaws.com`. The following example grants the appropriate permission. 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SIP media applicationRead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [                
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*",
	    "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "123456789012"
                }
            }
        }
    ]
}
```

------

The PSTN audio service reads and writes to your S3 bucket on behalf of your Sip Media Application. To avoid the [confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html), you can restrict S3 bucket permissions to a single SIP media application.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SIP media applicationRead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [                
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*",
	    "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333",
                    "aws:SourceArn": "arn:aws:chime:us-east-1:111122223333:sma/sip-media-application-id"
                }
            }
        }
    ]
}
```

------

## Action successful response
<a name="action-successful"></a>

When the call recording is successfully started on a call leg, the SIP media application invokes an AWS Lambda function with the `ACTION_SUCCESSFUL` event type. The location of call recording is returned in the response. 

```
{
    "SchemaVersion": "1.0",
    "Sequence": INTEGER,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type" : "StartCallRecording",
        "Parameters": {
            "CallId": "call-id-1",
            "Track": "BOTH",
            "Destination": {
                "Type": "S3",
                "Location": "valid-bucket-name"
            }
        }
        "CallRecordingDestination": {
            "Type": "S3",
            "Location": "call-recording-bucket-and-key"
        }
    }
    "CallDetails": {
        ...
    }
}
```

## Action error response
<a name="action-error"></a>

For validation errors, the SIP media application calls the AWS Lambda function with the appropriate error message. The following table lists the error messages.




| Error | Message | Reason | 
| --- | --- | --- | 
| `InvalidActionParameter` | `CallId` parameter for action is invalid | Any parameter is invalid. | 
| `SystemException` | System error while running an action. | Another type of system error occurred while running an action. | 

When the action fails to record the media on a call leg, the SIP media application invokes an AWS Lambda function with the `ActionFailed` event type. 

The following example shows a typical error response.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 5,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type" : "StartCallRecording",
        "Parameters": {
            "CallId": "call-id-1",
            "Track": "BOTH",
            "Destination": {
                "Type": "S3",
                "Location": "valid-bucket-name"
            }
        }
        "Error": "NoAccessToDestination: Error while accessing destination"
    }
    "CallDetails": {
        ...
    }
}
```

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# StopCallRecording
<a name="stop-call-recording"></a>

The `StopCallRecording` action stops the recording of a call leg. Recording stops automatically when a call ends, and your application doesn't need to explicitly return the `StopCallRecording` action. Once recording for a call leg stops, it can’t start again, and the recording is delivered to the destination specified in the `StartCallRecording` action. 

The following example stops recording for the `call-id-1` call leg. 

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "StopCallRecording",
            "Parameters": {
                "CallId": "call-id-1"
            }
        }
    ]
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# PauseCallRecording
<a name="pause-call-recording"></a>

The `PauseCallRecording` action pauses recording of a call leg. Each time you pause a recording, the recording captures a tone that indicates the pause. When you pause, the recording continues, but it only captures silence. Pausing the recording does not affect the total duration of the recording. You can pause and resume recording as often as needed.

The following example pauses recording. 

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "PauseCallRecording",
            "Parameters": {
                "CallId": "call-id-1"
            }
        }
    ]
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# ResumeCallRecording
<a name="resume-call-recording"></a>

The `ResumeCallRecording` action resumes the recording of a call leg. Before the recording restarts, a brief tone is played. You can pause and resume a recording multiple times for the duration of the call leg. 

The following example resumes recording. 

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "ResumeCallRecording",
            "Parameters": {
                "CallId": "call-id-1"
            }
        }
    ]
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# CallAndBridge
<a name="call-and-bridge"></a>

Creates an outbound call to a PSTN phone number, or to a SIP trunk configured as an Amazon Chime SDK Voice Connector or Amazon Chime SDK Voice Connector Group, and then bridges it with an existing call. You use `PSTN` when calling a phone number, and `AWS` when calling a SIP trunk. 

An existing call can be an outbound call created by using the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateSipMediaApplicationCall.html) API, or an inbound call created by a SIP rule that invokes the AWS Lambda function with a `NewInboundCall` event. When you implement a `CallAndBridge` action to a Voice Connector or Voice Connector Group endpoint, you must specify the Amazon Resource Number (ARN) of the Voice Connector or Voice Connector Group.

You can also add custom SIP headers to outbound calls and AWS Lambda functions. Custom headers allow you to pass values such as floor numbers and zip codes. For more information about custom headers, refer to [Using SIP headers in the Amazon Chime SDK PTSN audio service](sip-headers.md).

When using the call and bridge function it is important to note that each call is counted towards your active concurrent call count used to calculate SMA Active Call Limits. With this in mind, when managing your SMA Active Call Limits for call and bridge, you should count 2 calls for every 1 call and bridge action. For more information, see [SIP trunking and voice quotas](https://docs.aws.amazon.com/general/latest/gr/chime-sdk.html#chm-sdk-pstn-quotas) in the *AWS General Reference*.

The following example code shows a typical action that bridges to a PSTN endpoint.

```
{
    "SchemaVersion": "1.0",
    "Actions": [{
            "Type": "CallAndBridge",
            "Parameters": {
                "CallTimeoutSeconds": 30,
                "CallerIdNumber": "e164PhoneNumber", // required            
                "Endpoints": [{
                    "BridgeEndpointType": "PSTN", // required
                    "Uri": "e164PhoneNumber", // required                       
                }],
            }
        }
    ]
}
```

The following example shows a typical action that uses a Voice Connector or Voice Connector Group, plus a custom SIP header.

```
{
   "SchemaVersion":"1.0",
   "Actions":[
      {
         "Type":"CallAndBridge",
         "Parameters":{
            "CallTimeoutSeconds":30,
            "CallerIdNumber": "e164PhoneNumber", // required
            "RingbackTone": { // optional
                    "Type": "S3",
                    "BucketName": "s3_bucket_name",
                    "Key": "audio_file_name"
                },
            "Endpoints":[
               {
                  "BridgeEndpointType":"AWS", // enum type, required                                  
                  "Arn":"arn:aws:chime:us-east-1:0123456789101:vc/abcdefg1hijklm2nopq3rs" //VC or VCG ARN, required for AWS endpoints
                  "Uri":"ValidString", // required, see description below  
               }
            ],
            "SipHeaders": { 
                "x-String":"String"
            }
         }
      }
   ]
}
```

**CallTimeoutSeconds**  
*Description* – The interval before a call times out. The timer starts at call setup.  
*Allowed values* – Between 1 and 120, inclusive  
*Required* – No  
*Default value* – 30

**CallerIdNumber**  
*Description* – A number belonging to the customer, or the From number of the A Leg  
*Allowed values* – A valid phone number in the E.164 format  
*Required* – Yes  
*Default value* – None

**Endpoints**  
*Description* – The endpoints of a call  
*Allowed values*:   
+ `BridgeEndpointType` – `AWS` for Voice Connectors and Voice Connector Groups, otherwise `PSTN`.
+ `Arn` – The ARN of a Voice Connector or Voice Connector Group. Only required when you use `AWS` as the `BridgeEndpointType`. 
+ `Uri` – The URI value depends on the type of endpoint.

  For `PSTN` endpoints, the URI must be a valid E.164 phone number.

  For `AWS` endpoints, the URI value sets the `user` part of the `Request-URI`. You must use [Augmented Backus-Naur Format](https://datatracker.ietf.org/doc/html/rfc2234). Required length: between 1 and 36, inclusive. Use the following values: `a-z, A-Z, 0-9, &, =, +, $, /, %, -, _, !, ~, *, `(`,`), (`.`)

  The host value of the `Request-URI` is derived from the Inbound routes of the target Voice Connector. The following example shows a `CallAndBridge` action with an `AWS` endpoint.

  ```
  {
     "SchemaVersion":"1.0",
     "Actions":[
        {
           "Type":"CallAndBridge",
           "Parameters":{
              "CallTimeoutSeconds":30,
              "CallerIdNumber": "+18005550122",
              "Endpoints":[
                 {
                    "BridgeEndpointType":"AWS",                                   
                    "Arn":"arn:aws:chime:us-east-1:0123456789101:vc/abcdefg1hijklm2nopq3rs", 
                    "Uri":"5550"   
                 }
              ],
              "SipHeaders": { 
                  "x-String":"String"
              }
           }
        }
     ]
  }
  ```

  For more information about Inbound routes and Voice Connectors, refer to [Editing Amazon Chime SDK Voice Connector settings](https://docs.aws.amazon.com/chime-sdk/latest/ag/edit-voicecon.html).
*Required* – Yes  
*Default value* – None

**SipHeaders**  
*Description* – Enables you to pass additional values. Use only with the `AWS` endpoint type.  
*Allowed values* – Valid SIP header  
*Required* – No  
*Default value* – None

The following example shows a successful `CallAndBridge` action that uses a PSTN endpoint:

```
{
   "SchemaVersion": "1.0",
   "Sequence": 3,
   "InvocationEventType": "ACTION_SUCCESSFUL",
   "ActionData": {
      "Type": "CallAndBridge",
      "Parameters": {
         "CallTimeoutSeconds": 30,
         "CallerIdNumber": "e164PhoneNumber",
         "Endpoints":[
            {
               "BridgeEndpointType": "PSTN",
               "Uri": "e164PhoneNumber"               
            }
         ],
         "CallId": "call-id-1"
      }
   },
   "CallDetails":{
      .....
      .....
      "Participants":[
         {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A",
            .....   
            "Status": "Connected"
         },
         {
            "CallId": "call-id-2",
            "ParticipantTag": "LEG-B",
            .....
            "Status": "Connected"
         }
      ]
   }
}
```

The following example shows a failed `CallAndBridge` action.

```
{
   "SchemaVersion": "1.0",
   "Sequence":2,
   "InvocationEventType": "ACTION_FAILED",
      "ActionData":{
      "Type": "CallAndBridge",
      "Parameters":{
         "CallTimeoutSeconds": 30,
         "CallerIdNumber": "e164PhoneNumber",
         "Endpoints": [
            {
               "BridgeEndpointType": "PSTN",
               "Uri": "e164PhoneNumber"           
            }
         ],
         "CallId": "call-id-1"
      },
      "ErrorType": "CallNotAnswered",
      "ErrorMessage": "Call not answered"
   },
   "CallDetails":{
      .....
      .....
      "Participants":[
         {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A",
            .....   
         }
      ]
   }
}
```

## Call flows
<a name="call-bridge-flows"></a>

The `CallAndBridge` action provides a different call signaling and audio experience for an existing call leg, depending on the parameters and whether the leg is connected.

The following diagram shows show the call flows with different parameters when an inbound call leg A is already connected.

![\[The flow of an answered call through the CallAndBridge action.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/call-bridge-ans-2.png)


The following diagram shows the call flow for an unanswered call.

![\[The flow of an unanswered call through the CallAndBridge action.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/SMA_Bridging_NotAns.png)


**Additional Details**  
Remember these facts about the `CallAndBridge` action.
+ `CallTimeoutSeconds` – This timer starts when the SIP invitation is sent on the B-Leg. You can set a desired target value, but this value can be ignored by upstream carriers.
+ `CallerIdNumber` – This phone number must belong to the customer, or be the From number of an A-Leg.
+ **Hang-up behavior and edge cases** – If one call leg hangs up, the other call leg does not automatically hang up the call. When a `Hangup` event is sent to the AWS Lambda function, the remaining leg must be disconnected independently. If a call leg is left hanging, the call is billed until it is hung up. For example, the following scenario may lead to unexpected charges:
  + You try to bridge to a destination phone number. The destination is busy and sends the call straight to voicemail. From the Audio Service's perspective, going to voicemail is an answered call. The A-Leg hangs up, but the B-Leg continues listening for the voicemail message. While the B-Leg listens, you get billed.
  + As a best practice, use the AWS Lambda function, or the party on the other end of the call, to hang up each call leg independently.
+ **Billing** – You're billed for the following when using `CallAndBridge`:
  + Active call minutes for each call leg created (A-Leg, B-Leg, etc.) to the PSTN.
  + Audio Service usage minutes.

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-bridging](https://github.com/aws-samples/amazon-chime-sma-bridging)
+ [https://github.com/aws-samples/amazon-chime-sma-call-forwarding](https://github.com/aws-samples/amazon-chime-sma-call-forwarding)
+ [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# Hangup
<a name="hangup"></a>

Sends a `Hangup` value with a `SipStatusCode` to any leg of a call.

When the Audio Service runs a `Hangup` action on a call leg:
+ For a call with only one call leg, the SIP media application invokes the AWS Lambda function with a `HANGUP` event and ignores the response. The call is then disconnected.
+ For a call leg (Leg A) that is bridged to another call leg (Leg B), if the `Hangup` action is associated with the bridged call leg (Leg B) then the PSTN audio service disconnects the bridged call leg, then invokes the Lambda function with a `HANGUP` event for leg B. The PSTN audio service then runs any actions returned from that Lambda invocation.
+ For a call leg (Leg A) that is bridged to another call leg (Leg B), if the `Hangup` action is associated with the original call leg (Leg A), then the PSTN audio service disconnects the original call leg, then invokes the Lambda function with a `HANGUP` event for leg A. The PSTN audio service then runs any actions returned from that Lambda invocation.
+ For a call leg that joined to a meeting using the `JoinMeeting` action, if the `Hangup` action is associated with the meeting leg (usually Leg B) then the caller disconnects from the meeting and receives an `ACTION_SUCCESSFUL` event for the `Hangup` action.

The following example shows a typical `Hangup` action.

```
{
    "Type": "Hangup",
    "Parameters": {
        "CallId": "call-id-1",
        "ParticipantTag": "LEG-A",
        "SipResponseCode": "0"
    }
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`  
*Allowed values* – `LEG-A` or `LEG-B`  
*Required* – No  
*Default value* – `ParticipantTag` of the invoked `callLeg` Ignored if you specify `CallId`

**SipResponseCode**  
*Description* – Any of the supported SIP response codes  
*Allowed values* – 480–Unavailable; 486–Busy; 0–Normal Termination  
*Required* – No  
*Default value* – 0

After a user ends a call, the SIP media application invokes an AWS Lambda function with the code listed in [Ending a call using the Amazon Chime SDK PSTN audio service](case-5.md).

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-bridging](https://github.com/aws-samples/amazon-chime-sma-bridging)
+ [https://github.com/aws-samples/amazon-chime-sma-call-forwarding](https://github.com/aws-samples/amazon-chime-sma-call-forwarding)
+ [https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications](https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications)
+ [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# JoinChimeMeeting
<a name="join-chime-meeting"></a>

Join an Amazon Chime SDK meeting by providing the attendee join token. To do this, you make AWS SDK calls to the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateMeeting.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateMeeting.html) and [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateAttendee.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_CreateAttendee.html) APIs to get the token and pass it on in the action. See the following example. 

**Note**  
You can't run this action on a bridged call.

```
{
    "Type": "JoinChimeMeeting",
    "Parameters": {
        "JoinToken": "meeting-attendee-join-token",
        "CallId": "call-id-1",
        "ParticipantTag": "LEG-A",
        "MeetingId": "meeting-id"
    }
}
```

**JoinToken**  
*Description* – A valid join token of the Amazon Chime SDK meeting attendee  
*Allowed values* – Valid join token  
*Required* – Yes  
*Default value* – None

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`  
*Allowed values* – `LEG-A`  
*Required* – No  
*Default value* – `ParticipantTag` of the invoked `callLeg` Ignored if you specify `CallId`

**MeetingId**  
*Description* – A valid Amazon Chime SDK meeting ID associated with the `JoinToken`. If the meeting was created using an API in the [Amazon Chime](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_Operations_Amazon_Chime.html) namespace, the meeting ID is not required. If the meeting was created using an API in the [Amazon Chime SDK Meetings](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_Operations_Amazon_Chime_SDK_Meetings.html) namespace, the meeting ID is required. The meeting is joined using the API endpoint used to create the meeting.  
*Allowed values* – A valid meeting ID.  
*Required* – No.  
*Default value* – None.

The SIP media application always invokes an AWS Lambda function after running this action. It returns either the `ACTION_SUCCESSFUL` or `ACTION_FAILED` invocation event types. The following example shows a successful invocation event structure.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEvent": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "JoinChimeMeeting",
        "Parameters": {
            "JoinToken": "meeting-attendee-join-token",
            "CallId": "call-id-1"
            "ParticipantTag": "LEG-A"
        }
    }
    "CallDetails": {
        ...
    }
}
```

**Error handling**  
When a validation error occurs while bridging a meeting, the SIP application calls its AWS Lambda function with one of the error messages shown in the following table.


|  Error  |  Message  |  Reason  | 
| --- | --- | --- | 
|  `InvalidActionParameter`  |  `JoinToken` parameter value is invalid.  |  Any of the action's other parameters is invalid or missing.  | 
|  `SystemException`  |  System error while running action.  |  Another type of system error occurred while running the action.  | 

The following example shows a typical failure event.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEvent": "ACTION_FAILED",
    "ActionData": {
        "Type": "JoinChimeMeeting",
        "Parameters": {
            "JoinToken": "meeting-attendee-join-token",
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A"
        },
        "Error": "ErrorJoiningMeeting: Error while joining meeting."
    }
    "CallDetails": {
        ...
    }
}
```

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-update-call](https://github.com/aws-samples/amazon-chime-sma-update-call)

# ModifyChimeMeetingAttendee (muting and unmuting audio)
<a name="mute-unmute"></a>

Allows the SIP media application to modify the status of a telephony attendee by providing the Amazon Chime SDK meeting ID and attendee list.

**Note**  
This action currently supports mute and unmute operations on telephony attendees. Also, the user must be joined into a meeting using the `JoinChimeMeeting` action. This action can be performed on a `participantTag=“LEG-B”`, or a corresponding `CallId`. 

This action only applies to the callLeg that joins from the SIP media application to `"+`*13605550122*`"`, LEG-B, or the leg joined from the SIP media application to the meeting.

```
{
"SchemaVersion": "1.0",
  "Actions": [
    {
      "Type" : "ModifyChimeMeetingAttendees",
      "Parameters" : {
        "Operation": "Mute",
        "MeetingId": "meeting-id",
        "CallId": "call-id",
        "ParticipantTag": LEG-B",
        "AttendeeList": ["attendee-id-1", "attendee-id-2"]
      }
    }
  ]
}
```

**Operation**  
*Description* – The operation to perform on the list of attendees  
*Allowed values* – Mute, Unmute  
*Required* – Yes  
*Default value* – None

**MeetingId**  
*Description* – The ID of the meeting to which the attendees belong  
*Allowed values* – A valid meeting ID. The person muting or unmuting must also belong to the meeting.  
*Required* – Yes  
*Default value* – None

**CallId**  
*Description* – The ID of the meeting to which the attendees belong  
*Allowed values* – A valid call ID.  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – The tag assigned to the attendee.  
*Allowed values* – A valid tag.  
*Required* – No  
*Default value* – None

**AttendeeList**  
*Description* – List of attendee IDs to mute or unmute  
*Allowed values* – A list of valid attendee IDs  
*Required* – Yes  
*Default value* – None, maximum of 100

After running this action, Audio Service always invoke an AWS Lambda function with the `ACTION_SUCCESSFUL` or `ACTION_FAILED` invocation event type. The following example code shows a typical `ACTION_SUCCESSFUL` invocation event.

```
{
    "SchemaVersion": "1.0",
    "Sequence": INTEGER,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type" : "ModifyChimeMeetingAttendees",
        "Parameters" : {
            "Operation": "Mute",
            "MeetingId": "meeting-id",
            "CallId": "call-id",
            "ParticipantTag": "LEG-B",
            "AttendeeList": ["attendee-id-1", "attendee-id-2"]
        }
    }
    "CallDetails": {
        ...
    }
}
```

**Error handling**  
In cases of invalid instruction parameters or API failures, SIP media applications call an AWS Lambda function with the error message specific to the failed instruction or API.


|  Error  |  Message  |  Reason  | 
| --- | --- | --- | 
|  `InvalidActionParameter`  |  The `ModifyChimeMeetingAttendees Operation` parameter value is invalid  |  The `Operation` value must be Mute or Unmute.  | 
|     |  Meeting ID parameter value is invalid.  |  Meeting ID is empty.  | 
|     |  Attendee List parameter value is invalid.  |  The Attendee ID list is empty, or it exceeds the maximum of 100.  | 
|     |  Invalid action on the call.  |  The call isn't bridged.  | 
|     |  Call is not connected to Chime Meeting.  |  The attendee is not connected to a Chime Meeting.  | 
|     |  One or more attendees are not part of this meeting. All attendees must be part of this meeting.  |  The attendee is not authorized to modify attendees in the meeting.  | 
|  `SystemException`  |  System error while running action.  |  A system error occurred while running an action.  | 

The following example code shows a typical failure event:

```
{
    "SchemaVersion": "1.0",
    "Sequence": INTEGER,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type" : "ModifyChimeMeetingAttendees",
        "Parameters" : {
            "Operation": "Mute",
            "MeetingId": "meeting-id",
            "CallId": "call-id",
            "ParticipantTag": "LEG-B",
            "AttendeeList": ["attendee-id-1", "attendee-id-2"]
        },
        "ErrorType": "",
        "ErrorMessage": "",
        "ErrorList": []
    }
    "CallDetails": {
        ...
    }
}
```

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-bridging](https://github.com/aws-samples/amazon-chime-sma-bridging).
+ [https://github.com/aws-samples/amazon-chime-sma-update-call](https://github.com/aws-samples/amazon-chime-sma-update-call)

# Pause
<a name="pause"></a>

Pause a call for a specified time.

```
{
    "Type": "Pause",
    "Parameters": {
        "CallId": "call-id-1",
        "ParticipantTag": "LEG-A",
        "DurationInMilliseconds": "3000"
    }
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`  
*Allowed values* – `LEG-A` or `LEG-B`  
*Required* – No  
*Default value* – `ParticipantTag` of the invoked `callLeg` Ignored if you specify `CallId`

**DurationInMilliseconds**  
*Description* – Duration of the pause, in milliseconds  
*Allowed values* – An integer >0  
*Required* – Yes  
*Default value* – None

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications](https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications)
+ [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)

# PlayAudio
<a name="play-audio"></a>

Play an audio file on any leg of a call. The audio can be repeated any number of times. The in-progress audio can be terminated using the DTMF digits set in the `PlaybackTerminators`.

Currently, Amazon Chime SDK only supports playing audio files from the Amazon Simple Storage Service (Amazon S3) bucket. The S3 bucket must belong to the same AWS account as the SIP media application. In addition, you must give the `s3:GetObject` permission to the Amazon Chime SDK Voice Connector service principal. You can do that by using the S3 console or the command-line interface (CLI).

The following code example shows a typical bucket policy.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SMARead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*",
                "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                }
            }
        }
    ]
}
```

------

The Audio Service reads and writes to your S3 bucket on behalf of your Sip Media Application. To avoid the [confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html), you can restrict S3 bucket access to a single SIP media application.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SMARead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*",
                "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333",
                    "aws:SourceArn": "arn:aws:chime:us-east-1:111122223333:sma/sip-media-application-id"
                }
            }
        }
    ]
}
```

------

The following code example shows a typical action.

```
{
    "Type": "PlayAudio",
    "Parameters": {
        "CallId": "call-id-1",
        "ParticipantTag": "LEG-A",
        "PlaybackTerminators": ["1", "8", "#"],
        "Repeat": "5",
        "AudioSource": {
            "Type": "S3",
            "BucketName": "valid-S3-bucket-name",
            "Key": "wave-file.wav"
        }
    }
}
```

**CallID**  
*Description* – `CallId` of participant in the `CallDetails`.  
*Allowed values* – A valid call ID.  
*Required* – No, if `ParticipantTag` is present.  
*Default value* – None.

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`.  
*Allowed values* – `LEG-A` or `LEG-B`.  
*Required* – No, if `CallId` is present.  
*Default value* – `ParticipantTag` of the invoked `callLeg`. Ignored if you specify `CallId`.

**PlaybackTerminator**  
*Description* – Terminates in-progress audio by using DTMF input from the user  
*Allowed values* – An array of the following values; “0”, ”1”, ”2”, ”3”, ”4”, ”5”, ”6”, ”7”, ”8”, ”9”, ”\$1”, ”\$1”  
*Required* – No  
*Default value* – None

**Repeat**  
*Description* – Repeats the audio the specified number of times  
*Allowed values* – An integer greater than zero  
*Required* – No  
*Default value* – 1

**AudioSource.Type**  
*Description* – Type of source for audio file.  
*Allowed values* – S3.  
*Required* – Yes.  
*Default value* – None.

**AudioSource.BucketName**  
*Description* – For S3 source types, the S3 bucket must belong to the same AWS account as the SIP application. The bucket must have access to the Amazon Chime SDK Voice Connector service principal, which is voiceconnector.chime.amazonaws.com.  
*Allowed values* – A valid S3 bucket for which Amazon Chime SDK has access to the `s3:GetObject` action.  
*Required* – Yes.  
*Default value* – None.

**AudioSource.key**  
*Description* – For S3 source types, the file name from the S3 bucket specified in the `AudioSource.BucketName` attribute.  
*Allowed values* – A valid audio file.  
*Required* – Yes.  
*Default value* – None.

The SIP media application tries to play the audio from the source URL. You can use raw, uncompressed PCM .wav files of no more than 50 MB in size. Amazon Chime SDK recommends 8 KHz mono.

When the last instruction in a dialplan is `PlayAudio` and the file finishes playback, or if a user stops playback with a key press, the application invokes the AWS Lambda function with the event shown in the following example.

```
{
    "SchemaVersion": "1.0",
    "Sequence": INTEGER,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "PlayAudio",
        "Parameters" : {
            "CallId": "call-id-1",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "valid-S3-bucket-name",
                "Key": "wave-file.wav",
         }           
     }
}
```

After a terminating digit stops the audio, it won't be repeated.

**Error handling**  
When the validation file contains errors, or an error occurs while running an action, the SIP media application calls an AWS Lambda function with the appropriate error code.


|  Error  |  Message  |  Reason  | 
| --- | --- | --- | 
|  `InvalidAudioSource`  |  The audio source parameter is invalid.  |  This error can happen for multiple reasons. For example, the SIP media application cannot access the file due to permission issues, or issues with the URL. Or, the audio file may fail validation due to format, duration, size, and so on.  | 
|  `SystemException`  |  System error while running action.  |  Another system error occurred while running the action.   | 
|  `InvalidActionParameter`  |  CallId or ParticipantTag parameter for action is invalid.  |  The action contains an invalid parameter.  | 

The following code example shows a typical invocation failure.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 2,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type": "PlayAudio",
        "Parameters" : {
            "CallId": "call-id-1",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file.wav"
            },
        },
        "ErrorType": "InvalidAudioSource",
        "ErrorMessage": "Audio Source parameter value is invalid."
    }
    "CallDetails": {
        ...
    }
}
```

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-bridging](https://github.com/aws-samples/amazon-chime-sma-bridging).
+ [https://github.com/aws-samples/amazon-chime-sma-call-forwarding](https://github.com/aws-samples/amazon-chime-sma-call-forwarding)
+ [https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications](https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications)
+ [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)
+ [https://github.com/aws-samples/amazon-chime-sma-update-call](https://github.com/aws-samples/amazon-chime-sma-update-call)

# PlayAudioAndGetDigits
<a name="play-audio-get-digits"></a>

Plays audio and gathers DTMF digits. If a failure occurs, such as a user not entering the correct number of DTMF digits, the action plays the "failure" audio and then replays the main audio until the SIP media application exhausts the number of attempts defined in the `Repeat` parameter.

You must play audio files from the S3 bucket. The S3 bucket must belong to the same AWS account as the SIP media application. In addition, you must give the `s3:GetObject` permission to the [ Amazon Chime SDK Voice Connector service principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), `voiceconnector.chime.amazonaws.com`. You can use the S3 console or the CLI to do that. 

The following code example shows a typical S3 bucket policy.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SMARead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*",
                "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333"
                }
            }
        }
    ]
}
```

------

The Audio Service reads and writes to your S3 bucket on behalf of your Sip Media Application. To avoid the [confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html), you can restrict S3 bucket access to a single SIP media application.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SMARead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*",
                "Condition": {
                "StringEquals": {
                    "aws:SourceAccount": "111122223333",
                    "aws:SourceArn": "arn:aws:chime:us-east-1:111122223333:sma/sip-media-application-id"
                }
            }
        }
    ]
}
```

------

The following example shows a typical `PlayAudioAndGetDigits` action. 

```
{
    "Type" : "PlayAudioAndGetDigits",
    "Parameters" : {
        "CallId": "call-id-1",
        "ParticipantTag": "LEG-A"      
        "InputDigitsRegex": "^\d{2}#$",
        "AudioSource": {
            "Type": "S3",
            "BucketName": "bucket-name",
            "Key": "audio-file-1.wav"
        },
        "FailureAudioSource": {
            "Type": "S3",
            "BucketName": "bucket-name",
            "Key": "audio-file-failure.wav"
        },
        "MinNumberOfDigits": 3,
        "MaxNumberOfDigits": 5,
        "TerminatorDigits": ["#"],        
        "InBetweenDigitsDurationInMilliseconds": 5000,
        "Repeat": 3,
        "RepeatDurationInMilliseconds": 10000
    }
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`  
*Allowed values* – `LEG-A` or `LEG-B`  
*Required* – No  
*Default value* – `ParticipantTag` of the invoked `callLeg` Ignored if you specify `CallId`

**InputDigitsRegex**  
*Description* – A regular expression pattern  
*Allowed values* – A valid regular expression pattern  
*Required* – No  
*Default value* – None

**AudioSource.Type**  
*Description* – Type of source for the audio file type  
*Allowed values* – An S3 bucket  
*Required* – Yes  
*Default value* – `"S3"`

**AudioSource.BucketName**  
*Description* – For S3 `AudioSource.Type` values, the S3 bucket must belong to the same AWS account as the SIP media application. The bucket S3 must have access to the [Amazon Chime SDK Voice Connector service principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), `voiceconnector.chime.amazonaws.com`.  
*Allowed values* – A valid S3 bucket for which Amazon Chime SDK has `s3:GetObject` actions access.  
*Required* – Yes  
*Default value* – None

**AudioSource.Key**  
*Description* – The key name of the audio object in the `AudioSource.BucketName` S3 bucket.  
*Allowed values* – Valid audio files  
*Required* – Yes  
*Default value* – None

**FailureAudioSource.Type**  
*Description* – The key name of the audio object in the `FailureAudioSource.BucketName` S3 bucket.  
*Allowed values* – S3  
*Required* – Yes  
*Default value* – None

**FailureAudioSource.BucketName**  
*Description* – For S3 source types, the S3 bucket must belong to the same AWS account as the SIP media application. The [Amazon Chime SDK Voice Connector service principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), `voiceconnector.chime.amazonaws.com`, must have access to the S3 bucket.  
*Allowed values* – A valid S3 bucket for which Amazon Chime SDK has `s3:GetObject` actions access.  
*Required* – Yes  
*Default value* – None

**FailureAudioSource.Key**  
*Description* – The key name of the audio object in the `FailureAudioSource.BucketName` S3 bucket.  
*Allowed values* – Valid audio files  
*Required* – Yes  
*Default value* – None

**MinNumberOfDigits**  
*Description* – The minimum number of digits to capture before timing out or playing "call failed" audio.  
*Allowed values* – >=0  
*Required* – No  
*Default value* – 0

**MaxNumberOfDigits**  
*Description* – The maximum number of digits to capture before stopping without a terminating digit.  
*Allowed values* – >`MinNumberOfDigits`  
*Required* – No  
*Default value* – 128

**TerminatorDigits**  
*Description* – Digits used to end input if the user enters less than the `MaxNumberOfDigits`  
*Allowed values* – Any one of these digits: 0123456789\$1\$1  
*Required* – No  
*Default value* – \$1

**InBetweenDigitsDurationInMilliseconds**  
*Description* – The wait time in milliseconds between digit inputs before playing `FailureAudio`.  
*Allowed values* – >0  
*Required* – No  
*Default value* – If not specified, defaults to the `RepeatDurationInMilliseconds` value.

**Repeat**  
*Description* – Total number of attempts to get digits  
*Allowed values* – >0  
*Required* – No  
*Default value* – 1

**RepeatDurationInMilliseconds**  
*Description* – Time in milliseconds to wait between `Repeat` attempts  
*Allowed values* – >0  
*Required* – Yes  
*Default value* – None

The SIP media application always invokes its AWS Lambda function after running the `PlayAudioAndGetDigits` action, with an `ACTION_SUCCESSFUL` or `ACTION_FAILED` invocation event type. When the application successfully gathers digits, it sets the `ReceivedDigits` value in the `ActionData` object. The following example shows the invocation event structure of that AWS Lambda function.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "PlayAudioAndGetDigits",
        "Parameters" : {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A",
            "InputDigitsRegex": "^\d{2}#$",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file-1.wav"
            },
            "FailureAudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file-failure.wav"
            },
            "MinNumberOfDigits": 3,
            "MaxNumberOfDigits": 5,
            "TerminatorDigits": ["#"],
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "Repeat": 3,
            "RepeatDurationInMilliseconds": 10000
        },
        "ErrorType": "InvalidAudioSource",
        "ErrorMessage": "Audio Source parameter value is invalid."
    },
        "ReceivedDigits": "1234"
    },
    "CallDetails": {
        ...
    }
}
```

**Error handling**  
When a validation error occurs, the SIP media application calls the AWS Lambda function with the corresponding error message. The following table lists the possible error messages.


|  Error  |  Message  |  Reason  | 
| --- | --- | --- | 
|  `InvalidAudioSource`  |  Audio source parameter value is invalid.  |  This error can happen for multiple reasons. For example, the SIP media application cannot access the file due to permission issues, or issues with the S3 bucket. Or, the audio file may fail validation due to duration, size, or unsupported format.  | 
|  `InvalidActionParameter`  |  `CallId` or `ParticipantTag` parameter for the action is invalid.  |  A `CallId`, `ParticipantTag`, or other parameter is not valid.  | 
|  `SystemException`  |  System error while running the action.  |  A system error occurred while running the action.  | 

When the action fails to collect the number of specified digits due to a timeout or too many retries, the SIP media application invokes the AWS Lambda function with the `ACTION_FAILED` invocation event type.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 4,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type": "PlayAudioAndGetDigits",
        "Parameters" : {
            "CallId": "call-id-1",
            "ParticipantTag": "LEG-A",
            "InputDigitsRegex": "^\d{2}#$",
            "AudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file-1.wav"
            },
            "FailureAudioSource": {
                "Type": "S3",
                "BucketName": "bucket-name",
                "Key": "audio-file-failure.wav"
            },
            "MinNumberOfDigits": 3,
            "MaxNumberOfDigits": 5,
            "TerminatorDigits": ["#"],
            "InBetweenDigitsDurationInMilliseconds": 5000,
            "Repeat": 3,
            "RepeatDurationInMilliseconds": 10000
        },
        "ErrorType": "InvalidAudioSource",
        "ErrorMessage": "Audio Source parameter value is invalid."
    }
    "CallDetails": {
        ...
    }
}
```

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-bridging](https://github.com/aws-samples/amazon-chime-sma-bridging).
+ [https://github.com/aws-samples/amazon-chime-sma-update-call](https://github.com/aws-samples/amazon-chime-sma-update-call)

# ReceiveDigits
<a name="listen-to-digits"></a>

When a user enters digits that match the regular expression pattern specified in this action, the SIP media application invokes the AWS Lambda function.

```
{
    "Type": "ReceiveDigits",
    "Parameters": {
        "CallId": "call-id-1",
        "ParticipantTag": "LEG-A",
        "InputDigitsRegex": "^\d{2}#$",
        "InBetweenDigitsDurationInMilliseconds": 1000, 
        "FlushDigitsDurationInMilliseconds": 10000
    }
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`  
*Allowed values* – `LEG-A` or `LEG-B`  
*Required* – No  
*Default value* – `ParticipantTag` of the invoked `callLeg` Ignored if you specify `CallId`

**InputDigitsRegex**  
*Description* – A regular expression pattern  
*Allowed values* – A valid regular expression pattern  
*Required* – Yes  
*Default value* – None

**InBetweenDigitsDurationInMilliseconds**  
*Description* – Interval between digits before checking to see if the input matches the regular expression pattern  
*Allowed values* – Duration in milliseconds  
*Required* – Yes  
*Default value* – None

**FlushDigitsDurationInMilliseconds**  
*Description* – Interval after which received DTMF digits are flushed and sent to the AWS Lambda function. If the SIP media application receives a new digit after the interval ends, the timer starts again.  
*Allowed values* – `InBetweenDigitsDurationInMilliseconds`  
*Required* – Yes  
*Default value* – None

The SIP media application discards DTMF digits for the duration of a call until it receives a new `ReceiveDigits` action. The `FlushDigitsDurationInMilliseconds` interval starts when the SIP media application receives the first DTMF digit. If the user enters the correct digits before the interval expires, the SIP media application invokes the AWS Lambda function described in [Receiving caller input for the Amazon Chime SDK PSTN audio service](case-4.md).

If the user input doesn't match the regular expression pattern, the SIP media application repeats the "failure" audio file message until the application exhausts the repeat count or the user inputs valid digits. 

See working examples on GitHub:
+ [https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications](https://github.com/aws-samples/amazon-chime-sma-outbound-call-notifications)
+ [https://github.com/aws-samples/amazon-chime-sma-on-demand-recording](https://github.com/aws-samples/amazon-chime-sma-on-demand-recording)
+ [https://github.com/aws-samples/amazon-chime-sma-update-call](https://github.com/aws-samples/amazon-chime-sma-update-call)

# RecordAudio
<a name="record-audio"></a>

Allows the SIP media application to record media from a given call ID. For example, a voice mail application and meeting-participant announcements. The application records until it reaches the duration that you set, or when a user presses one of the `RecordingTerminators`, or when the application detects silence. In those cases, the action tells your application to put the resulting media file into the specified S3 bucket. The S3 bucket must belong to the same AWS account as the SIP media application. In addition, the action must give `s3:PutObject` and `s3:PutObjectAcl` permission to the Amazon Chime SDK Voice Connector service principal, [Amazon Chime SDK Voice Connector service principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), `voiceconnector.chime.amazonaws.com`. 

**Note**  
Recordings made using this feature may be subject to laws or regulations regarding the recording of electronic communications. It is your and your end users’ responsibility to comply with all applicable laws regarding the recording, including properly notifying all participants in a recorded session or communication that the session or communication is being recorded, and obtaining their consent.

The following example gives the `s3:PutObject` and `s3:PutObjectAcl` permission to the Amazon Chime SDK Voice Connector service principal.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "SMARead",
            "Effect": "Allow",
            "Principal": {
                "Service": "voiceconnector.chime.amazonaws.com"
            },
            "Action": [                
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::bucket-name/*"
        }
    ]
}
```

------

The following example stops recording when the caller presses the pound key (\$1), or 10 seconds elapse with no activity, or the caller remains silent for 3 seconds, and it writes the resulting media file into the location defined by `RecordingDestination` parameter.

**Note**  
This example uses the `CallId` parameter. You can use the `ParticipantTag` parameter instead, but you can't use both.

```
{
    "Type": "RecordAudio",
    "Parameters": {
        "CallId": "call-id-1",
        "DurationInSeconds": "10",
        "SilenceDurationInSeconds": 3,
        "SilenceThreshold": 100,
        "RecordingTerminators": [
            "#"
        ],
        "RecordingDestination": {
            "Type": "S3",
            "BucketName": "valid-bucket-name",
            "Prefix": "valid-prefix-name"
        }
    }
}
```

**CallId**  
*Description* – `CallId` of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – No  
*Default value* – None

**ParticipantTag**  
*Description* – `ParticipantTag` of one of the connected participants in the `CallDetails`  
*Allowed values* – `LEG-A` or `LEG-B`  
*Required* – No  
*Default value* – `ParticipantTag` of the invoked `callLeg` Ignored if you specify `CallId`

**RecordingDestination.Type**  
*Description* – Type of destination. Only S3.  
*Allowed values* – S3  
*Required* – Yes  
*Default value* – None

**RecordingDestination.BucketName**  
*Description* – A valid S3 bucket name. The bucket must have access to the [Amazon Chime SDK Voice Connector service principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html), `voiceconnector.chime.amazonaws.com`.  
*Allowed values* – A valid S3 bucket for which Amazon Chime SDK has access to the `s3:PutObject` and `s3:PutObjectAcl` actions.  
*Required* – Yes  
*Default value* – None

****RecordingDestination.Prefix****  
*Description* – S3 prefix of recording file  
*Allowed values* – A valid prefix name containing up to 979 safe characters. For more information about safe characters, refer to [Safe characters](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html#object-key-guidelines-safe-characters) in the Amazon Simple Storage Service User Guide.  
*Required* – No  
*Default* – None. If not specified, the recording are saved to the root of the S3 bucket.

**DurationInSeconds**  
*Description* – The duration of the recording, in seconds  
*Allowed values* – >0  
*Required* – No  
*Default value* – None

****SilenceDurationInSeconds****  
*Description* – The duration of silence in seconds, after which the recording stops. If not specified, silence detection is disabled.  
*Allowed values* – [1;1000]  
*Required* – No  
*Default value* – 200

****SilenceThreshold****  
*Description* – Level of noise that is considered "silence." If you don't specify `SilenceDurationInSeconds`, this parameter is ignored.  

**Reference values (noise levels and thresholds to treat the noise as silence):**
+ 1—30dB or below, such as a quiet room
+ 100—40-50 dB, such as a whisper or quiet office
+ 200—60dB, such as a crowded office
+ 1000—75 dB, such as a loud person or music
*Allowed values* – [1;1000]  
*Required* – No  
*Default value* – 200

**RecordingTerminators**  
*Description* – Lists all the available recording terminators.  
*Allowed values* – An array of single digits and symbols from [123456789\$10\$1]  
*Required* – Yes  
*Default value* – None

## Handling ACTION\$1SUCCESSFUL events
<a name="handle-action-successful"></a>

When the recording ends, the Amazon Chime SDK SIP media application calls the AWS Lambda function and passes to it the ACTION\$1SUCCESSFUL event, along with the invocation results.

```
{
    "SchemaVersion": "1.0",
    "Sequence": INTEGER,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type" : "RecordAudio",
        "Parameters": {
           ...           
        },
        "RecordingDestination": {
            "Type": "S3",
            "BucketName": "valid-bucket-name",
            "Key": "valid-S3-key"              
        },
        "RecordingTerminatorUsed":"#"
    },
    "CallDetails": {
        ...
    }
}
```

The `ACTION_SUCCESSFUL` event contains `ActionData`, which contains these fields:

**Type**  
*Description* – The type of the action, `RecordAudio`.

**Parameters**  
*Description* – The parameters of the action.

**RecordingDestination.Type**  
*Description* – Type of destination. Only S3. 

**RecordingDestination.BucketName**  
*Description* – The S3 bucket that contains the recording file. 

**RecordingDestination.Key**  
*Description* – The S3 key of the recording file.

**RecordingTerminatorUsed**  
*Description* – The terminator used to stop recording—one of the terminators passed in the `RecordingTerminators` parameter. If the recording stops after reaching maximum duration (`DurationInSeconds`) or because of silence (`SilenceDurationInSeconds`), this key-value pair is not included in the output.

**Error handling**  
For validation errors, the SIP media application calls the AWS Lambda function with the appropriate error message. The following table lists the possible error messages.


|  Error  |  Message  |  Reason  | 
| --- | --- | --- | 
|  `InvalidActionParameter`  |  `CallId` or `ParticipantTag` parameter for action is invalid. `DurationInSeconds` parameter value is invalid. `SilenceDurationInSeconds` parameter value is invalid. `SilenceThreshold` parameter value is invalid. `RecordingDestination` parameter value is invalid. Error occurred while uploading recording to S3 bucket.  |  Any parameter is invalid.  | 
|  `SystemException`  |  System error while running an action.  |  Another type of system error occurred while running an action.  | 

## Handling ACTION\$1FAILED events
<a name="handle-action-failed"></a>

When the action fails to record the media on a call leg, the SIP media application invokes an AWS Lambda function with the `ACTION_FAILED` event type. See the following example.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 5,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type" : "RecordAudio",
        "Parameters": {
           ...           
        },
        "ErrorType": "InvalidActionParameter",
        "ErrorMessage": "RecordingDestination parameter value is invalid."
    },
    "CallDetails": {
        ...
    }
}
```

See a working example on GitHub: [https://github.com/aws-samples/amazon-chime-sma-bridging](https://github.com/aws-samples/amazon-chime-sma-bridging)

# SendDigits
<a name="send-digits"></a>

Send up to 50 dual tone multi-frequency (DTMF) digits on any leg of a call. The signals can include the following:
+ Numbers 0 thru 9
+ Special characters star (\$1) and pound (\$1)
+ Network control signals A, B, C, D
+ The comma character (,). This signal adds a 0.5 second delay between the previous and next signals.

**Topics**
+ [Using the SendDigits action](#send-digits-action)
+ [Handling ACTION\$1SUCCESSFUL events](#send-digit-success)
+ [Handling ACTION\$1FAILED events](#send-digit-fail)
+ [Call flow](#send-digits-call-flow)

## Using the SendDigits action
<a name="send-digits-action"></a>

The following example shows a typical `SendDigits` action:

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "SendDigits",
            "Parameters": {
                "CallId": "call-id-1", // required
                "Digits": ",,*1234,56,7890ABCD#", // required
                "ToneDurationInMilliseconds": 100 // optional
            }
        }
    ]
}
```

**CallId**  
*Description* – The `CallId` of a participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

**Digits**  
*Description* – The digits to be sent on the call leg that corresponds to the `CallId`  
*Allowed values* – 0-9, \$1, \$1, A, B, C, D, comma (,)  
*Required* – Yes  
*Default value* – None

**ToneDurationInMilliseconds**  
*Description* – The amount of time allowed, in milliseconds, to transmit each digit.  
*Allowed values* – Any integer between 50 and 24000  
*Required* – No  
*Default value* – 250

## Handling ACTION\$1SUCCESSFUL events
<a name="send-digit-success"></a>

The following example shows a typical `ACTION_SUCCESSFUL` event for the `SendDigits` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type": "SendDigits",
        "Parameters": {
            "Digits": "1,2A#",
            "ToneDurationInMilliseconds": 100,
            "CallId": "call-id-1"
        },  
    "CallDetails": { 
        ...
        }
    }
}
```

## Handling ACTION\$1FAILED events
<a name="send-digit-fail"></a>

The following example shows a typical `ACTION_FAILED` event for the `SendDigits` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData": {
        "Type": "SendDigits",
        "Parameters": {
            "Digits": "1,2A#",
            "ToneDurationInMilliseconds": 20000000,
            "CallId": "call-id-1"
        },
    "ErrorType": "InvalidActionParameter",
    "ErrorMessage": "ToneDuration parameter value is invalid."
    },
    "CallDetails": {
        ...
        }
    }
}
```

## Call flow
<a name="send-digits-call-flow"></a>

The following diagram shows the program flow for sending digits from a caller to a callee.

![\[Diagram showing the program flow of the SendDigits action.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/send-digits-1.png)


# Speak
<a name="speak"></a>

You can play speech on any call leg by providing text. You can use plain text or Speech Synthesis Markup Language (SSML). SSML provides more control over how the Amazon Chime SDK generates speech by adding pauses, emphasizing certain words, or changing the speaking style.

The Amazon Chime SDK uses the Amazon Polly service to convert text-to-speech. Amazon Polly allows you to choose between either the standard or neural engine for improved speech quality. Amazon Polly supports more than 20 languages and 60 voices to customize your application's user experience. The Amazon Chime SDK provides speech features at no charge, but you do pay for using Amazon Polly. See the Amazon Polly [pricing page](https://aws.amazon.com/polly/pricing/) or your billing dashboard for pricing information.

**Important**  
Use of Amazon Polly is subject to the [ AWS Service Terms ](https://aws.amazon.com/service-terms/), including the terms specific to the AWS Machine Learning and Artificial Intelligence Services.

**Topics**
+ [Using the Speak action](#speak-action)
+ [Handling ACTION\$1SUCCESSFUL events](#speak-action-success)
+ [Handling ACTION\$1FAILED events](#speak-action-fail)
+ [Program flows](#speak-flow)

## Using the Speak action
<a name="speak-action"></a>

The following example shows a typical use of the `Speak` action.

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "Speak",
            "Parameters": {
                "Text": "Hello, World!",        // required
                "CallId": "call-id-1",          // required
                "Engine": "neural",             // optional. Defaults to standard
                "LanguageCode": "en-US",        // optional
                "TextType": "text",             // optional
                "VoiceId": "Joanna"             // optional. Defaults to Joanna
            }
        }
    ]
}
```

**CallId**  
*Description* – The `CallId` of participant in the `CallDetails` of the Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

**Text**  
*Description* – Specifies the input text to synthesize into speech. If you specify `ssml` as the `TextType`, follow the SSML format for the input text.  
*Allowed values* – String  
*Required* – Yes  
*Default value* – None

**Engine**  
*Description* – Specifies the engine—standard or neural—to use when processing text for speech synthesis.  
*Allowed values* – standard \$1 neural  
*Required* – No  
*Default value* – standard

**LanguageCode**  
*Description* – Specifies the language code. Only necessary if using a bilingual voice. If you use a bilingual voice without a language code, the bilingual voice's default language is used.  
*Allowed values* – [ Amazon Polly language codes](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-LanguageCode)  
*Required* – No  
*Default value* – None

**TextType**  
*Description* – Specifies the type of input text, plain text or SSML. If an input type is not specified, plain text is used as the default. For more information about SSML, see [Generating Speech from SSML Documents](https://docs.aws.amazon.com/polly/latest/dg/ssml.html) in the *Amazon Polly Developer Guide*.  
*Allowed values* – ssml \$1 text  
*Required* – No  
*Default value* – None

**VoiceId**  
*Description* – Specifies the ID of voice you want to use.  
*Allowed values* – [Amazon Polly voice IDs](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-VoiceId)  
*Required* – No  
*Default value* – Joanna

## Handling ACTION\$1SUCCESSFUL events
<a name="speak-action-success"></a>

The following example shows a typical `ACTION_SUCCESSFUL` event for an action which synthesizes the text "Hello World" into speech, in English, using the Amazon Polly's `Joanna` voice.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
       "Type": "Speak",
       "Parameters": {
          "CallId": "call-id-1",          
          "Engine":  "neural",             
          "LanguageCode":  "en-US",        
          "Text": "Hello World",          
          "TextType":  "text",             
          "VoiceId":  "Joanna"        
       }
    },
    "CallDetails":{       
       ...
    }
}
```

## Handling ACTION\$1FAILED events
<a name="speak-action-fail"></a>

The following example shows a typical `ACTION_FAILED` event for the same event used in the previous example.

```
{
    "SchemaVersion": "1.0",
    "Sequence":2,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData":{
       "Type": "Speak",
       "Parameters": {
          "CallId": "call-id-1",          
          "Engine":  "neural",             
          "LanguageCode":  "en-US",        
          "Text": "Hello  World",          
          "TextType":  "text",             
          "VoiceId":  "Joanna"        
       },
       "ErrorType": "SystemException",
       "ErrorMessage": "System error while running  action"
    },
    "CallDetails":{       
       ...
    }
}
```

**Error handling**  
This table lists and describes the error messages thrown by the the `Speak` action.


| Error | Message | Reason | 
| --- | --- | --- | 
| `AccessDenied` | The `AWSServiceRoleForAmazonChimeVoiceConnector` service-linked role is not configured correctly. | The service-linked role used to make requests to Amazon Polly doesn't exist or is missing permissions. To resolve, see the steps in the [Using the Amazon Chime SDK Voice Connector service-linked role](speak-and-get-digits.md#speak-digits-policy) section | 
| `InvalidActionParameter` |   | There was an error validating the action parameters. See the [SynthesizeSpeech API](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech) in the *Amazon Polly Developer Guide* for more information about parameters. | 
| ActionExecutionThrottled | Amazon Polly is throttling the request to synthesize speech. | The request to Amazon Polly is returning a throttling exception. For more information about the Amazon Polly throttling limits, see [ https://docs.aws.amazon.com/polly/latest/dg/limits.html\$1limits-throttle ](https://docs.aws.amazon.com/polly/latest/dg/limits.html#limits-throttle). | 
| `MissingRequiredActionParameter` | `Text` is a required parameter. | There action parameters must have a `Text` value | 
| `MissingRequiredActionParameter` | `Text` is limited to 1,000 characters | The text exceeded the character limit. | 
| `SystemException` | System error while running action. | A system error occurred while running the action. | 

## Program flows
<a name="speak-flow"></a>

The following diagram shows the program flow that enables the `Speak` action for a caller. In this example, the caller hears text that 

![\[Diagram showing the program flow for enabling the Speak action for a caller.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/Speak1.png)


**In the diagram**  
Using a soft phone, a caller enters a number registered to a SIP media application. The application uses the SIP `INVITE` method and sends the caller a `Trying (100)` response. That indicates that the next-hop server received the call request. The SIP application then uses `INVITE` to contact the endpoint. Once the connection is established, the applications sends `Ringing (180)` response to the caller, and alerting begins. 

The SIP media application then sends a `NEW_INBOUND_CALL` event to the Lambda function, which responds with a `Speak` action that includes the caller's ID and the text that you want to convert into speech. The SIP application then sends a `200 (OK)` response to indicate that the call was answered. The protocol also enables the media. 

If the `Speak` action succeeds and converts the text to speech, it returns an `ACTION_SUCCESSFUL` event to the SIP media application, which returns the next set of actions. If the action fails, the SIP media application sends an `ACTION_FAILED` event to the Lambda function, which responds with a set of `Hangup` actions. The application hangs up the caller and returns a `HANGUP` event to the Lambda function, which takes no further actions. 



The following diagram shows the program flow than enables the `Speak` action for a callee.

![\[Diagram showing the program flow for enabling the Speak action for a callee. You can do this on any bridged call.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/Speak2.png)


**In the diagram**  
A caller enters a number registered to a SIP media application, and the application responds as described for the previous diagram. When the Lambda function receives the `NEW_INBOUND_CALL` event, it returns the [CallAndBridge](call-and-bridge.md) action to the SIP application. The application then uses the SIP `INVITE` method to send the `Trying (100)` and `Ringing (180)` responses to the callee. 

If the callee answers, the SIP media application recieves a `200 (OK)` response, and it sends the same response to the caller. That establishes media, and the SIP application sends an `ACTION_SUCCESSFUL` event for the [CallAndBridge](call-and-bridge.md) action to the Lambda function. The function then returns the Speak action and data to the SIP application, which converts 

# SpeakAndGetDigits
<a name="speak-and-get-digits"></a>

Play speech by providing text and gather dual tone multi-frequency (DTMF) digits from the user. The text can either be plain text or Speech Synthesis Markup Language (SSML)-enhanced text to provide more control over how the Amazon Chime SDK generates speech by adding pauses, emphasizing certain words, or changing the speaking style, among other supported SSML features. If a failure occurs, such as a user not entering the correct number of DTMF digits, the action plays the "failure" speech and then replays the main speech until the SIP media application exhausts the number of attempts defined in the `Repeat` parameter.

The Amazon Chime SDK uses Amazon Polly, a cloud service that converts text into lifelike speech, Amazon Polly provides both a standard and a neural engine for improved speech quality, more than 20 supported languages, and 60 voices. Amazon Polly provides speech features at no charge, but you do pay for using Amazon Polly. See the Amazon Polly [pricing page](https://aws.amazon.com/polly/pricing/) or your billing dashboard for pricing information.

**Important**  
Use of Amazon Polly is subject to the [AWS Service Terms ](https://aws.amazon.com/service-terms/), including the terms specific to the AWS Machine Learning and Artificial Intelligence Services.

**Topics**
+ [Using the SpeakAndGetDigits action](#speak-digits-action)
+ [Handling ACTION\$1SUCCESSFUL events](#speak-digits-success)
+ [Handling ACTION\$1FAILED events](#speak-digits-fail)
+ [Using the Amazon Chime SDK Voice Connector service-linked role](#speak-digits-policy)

## Using the SpeakAndGetDigits action
<a name="speak-digits-action"></a>

The following example shows a typical use of the `SpeakAndGetDigits` action:

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "SpeakAndGetDigits",
            "Parameters": {
                "CallId": "call-id-1",          // required
                "InputDigitsRegex": "^\d{2}#$", // optional
                "SpeechParameters": {
                    "Text": "Hello World",      // required
                    "Engine": "neural",         // optional. Defaults to standard
                    "LanguageCode": "en-US",    // optional
                    "TextType": "text",         // optional
                    "VoiceId": "Joanna"         // optional. Defaults to Joanna
                },
                "FailureSpeechParameters": {
                    "Text": "Hello World",      // required
                    "Engine": "neural",         // optional. Defaults to the Engine value in SpeechParameters
                    "LanguageCode": "en-US",    // optional. Defaults to the LanguageCode value in SpeechParameters
                    "TextType": "text",         // optional. Defaults to the TextType value in SpeechParameters
                    "VoiceId": "Joanna"         // optional. Defaults to the VoiceId value in SpeechParameters
                },
                "MinNumberOfDigits": 3,         // optional
                "MaxNumberOfDigits": 5,         // optional
                "TerminatorDigits": ["#"],      // optional
                "InBetweenDigitsDurationInMilliseconds": 5000,  // optional
                "Repeat": 3,                    // optional
                "RepeatDurationInMilliseconds": 10000           // required
            }
        }
    ]
}
```

**CallId**  
*Description* – The `CallId` of participant in the CallDetails of the Lambda function invocation.  
*Allowed values* – A valid `callID`  
*Required* – Yes  
*Default value* – No

**InputDigitsRegex**  
*Description* – A regular expression pattern to help ensure that users enter the correct digits and letters.  
*Allowed values* – A valid regular expression pattern  
*Required* – No  
*Default value* – None

**SpeechParameters.Engine**  
*Description* – Specifies the engine – standard or neural – to use when processing text for speech synthesis.  
*Allowed values* – `standard` \$1 `neural`  
*Required* – No  
*Default value* – Standard

**SpeechParameters.LanguageCode**  
*Description* – Specifies the language code. This is only necessary if using a bilingual voice. If a bilingual voice is used and no language code is specified, the bilingual voice's default language is used.  
*Allowed values* – [ Amazon Polly language codes](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-LanguageCode)  
*Required* – No  
*Default value* – None

**SpeechParameters.Text**  
*Description* – Specifies the input text. If you specify `ssml` as the `SpeechParameters.TextType`, you must follow the SSML format for the input text. For more information about SSML, see [Generating Speech from SSML Documents](https://docs.aws.amazon.com/polly/latest/dg/ssml.html) in the *Amazon Polly Developer Guide*.  
*Allowed values* – String  
*Required* – Yes  
*Default value* – None

**SpeechParameters.TextType**  
*Description* – Specifies the text format for `SpeechParameters.Text`. If not specified, `text` is used by default. For more information about SSML, see [Generating Speech from SSML Documents](https://docs.aws.amazon.com/polly/latest/dg/ssml.html) in the *Amazon Polly Developer Guide*.  
*Allowed values* – `ssml` \$1 `text`  
*Required* – No  
*Default value* – `text`

**SpeechParameters.VoiceId**  
*Description* – The ID of the Amazon Polly voice used to speak the text in `SpeechParameters.Text`.  
*Allowed values* – [Amazon Polly voice IDs](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-VoiceId)  
*Required* – No  
*Default value* – Joanna

**FailureSpeechParameters.Engine**  
*Description* – Specifies the engine – standard or neural – to use when processing the failure message used when the customer enters an invalid response for speech synthesis.  
*Allowed values* – `standard` \$1 `neural`  
*Required* – No  
*Default value* – The `SpeechParameters.Engine` value

**FailureSpeechParameters.LanguageCode**  
*Description* – Specifies the language code used when the customer enters an invalid response. Only necessary when using a bilingual voice. If you use bilingual voice without specifying a language code, the bilingual voice's default language is used.  
*Allowed values* – [ Amazon Polly language codes](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-LanguageCode)  
*Required* – No  
*Default value* – The `SpeechParameters.LanguageCode` value.

**FailureSpeechParameters.Text**  
*Description* – Specifies the input text spoken when the customer enters an invalid response. If you specify `ssml` as the `FailureSpeechParameters.TextType`, you must follow the SSML format for the input text.  
*Allowed values* – String  
*Required* – Yes  
*Default value* – None

**FailureSpeechParameters.TextType**  
*Description* – Specifies whether the input text specified in `FailureSpeechParameters.Text` is plain text or SSML. The default value is plain text. For more information, see [Generating Speech from SSML Documents](https://docs.aws.amazon.com/polly/latest/dg/ssml.html) in the *Amazon Polly Developer Guide*.  
*Allowed values* – `ssml` \$1 `text`  
*Required* – No  
*Default value* – The `SpeechParameters.Text` value

**FailureSpeechParameters.VoiceId**  
*Description* – The ID for the voice used to speak the string in `FailureSpeechParameters.Text`.  
*Allowed values* – [Amazon Polly voice IDs](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html#polly-SynthesizeSpeech-request-VoiceId)  
*Required* – Yes  
*Default value* – The `SpeechParameters.VoiceId` value

**MinNumberOfDigits**  
*Description* – The minimum number of digits to capture before timing out or playing the "call failed" message.  
*Allowed values* – Greater than or equal to zero  
*Required* – No  
*Default value* – 0

**MaxNumberOfDigits**  
*Description* – The maximum number of digits to capture before stopping without a terminating digit.  
*Allowed values* – Greater than `MinNumberOfDigits`  
*Required* – No  
*Default value* – 128

**TerminatorDigits**  
*Description* – Digit used to end input if the user enters less than the MaxNumberOfDigits  
*Allowed values* – Any one of: 0 1 2 3 4 5 6 7 8 9 \$1 or \$1  
*Required* – No  
*Default value* – \$1

**InBetweenDigitsDurationInMilliseconds**  
*Description* – The wait time in milliseconds between digit inputs before playing the failure speech.  
*Allowed values* – Greater than zero  
*Required* – No  
*Default value* – If not specified, defaults to the `RepeatDurationInMilliseconds` value

**Repeat**  
*Description* – Total number of attempts to get digits. If you omit this parameter, the default is one attempt to collect digits.  
*Allowed values* – Greater than zero  
*Required* – No  
*Default value* – 1

**RepeatDurationInMilliseconds**  
*Description* – Timeout in milliseconds for each attempt to get digits.  
*Allowed values* – Greater than zero  
*Required* – Yes  
*Default value* – None

## Handling ACTION\$1SUCCESSFUL events
<a name="speak-digits-success"></a>

The following example shows a typical `ACTION_SUCCESSFUL` event.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
            "Type":  "SpeakAndGetDigits",
            "Parameters": {
                "CallId": "call-id-1",          
                "InputDigitsRegex":  "^\d{2}#$", 
                "SpeechParameters": {
                    "Engine":  "neural",         
                    "LanguageCode": "en-US",    
                    "Text":  "Hello World",           
                    "TextType":  "text",         
                    "VoiceId": "Joanna"         
                },
                "FailureSpeechParameters": {
                    "Engine":  "neural",         
                    "LanguageCode":  "en-US",    
                    "Text":  "Hello World",           
                    "TextType": "text",         
                    "VoiceId": "Joanna"         
                },
                "MinNumberOfDigits": 3,         
                "MaxNumberOfDigits": 5,         
                "TerminatorDigits": ["#"],      
                "InBetweenDigitsDurationInMilliseconds": 5000,  
                "Repeat": 3,                    
                "RepeatDurationInMilliseconds": 10000           
            },
            "ReceivedDigits": "1234"
    },
    "CallDetails":{       
       ...
    }
}
```

## Handling ACTION\$1FAILED events
<a name="speak-digits-fail"></a>

The following example shows a typical `ACTION_FAILED` event.

```
{
    "SchemaVersion": "1.0",
    "Sequence":2,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData":{
            "Type":  "SpeakAndGetDigits",
            "Parameters": {
                "CallId": "call-id-1",          
                "InputDigitsRegex":  "^\d{2}#$", 
                "SpeechParameters": {
                    "Engine":  "neural",         
                    "LanguageCode": "en-US",    
                    "Text":  "Hello World",           
                    "TextType":  "text",         
                    "VoiceId": "Joanna"         
                },
                "FailureSpeechParameters": {
                    "Engine":  "neural",         
                    "LanguageCode":  "en-US",    
                    "Text":  "Hello World",          
                    "TextType": "text",        
                    "VoiceId": "Joanna"        
                },
                "MinNumberOfDigits": 3,      
                "MaxNumberOfDigits": 5,        
                "TerminatorDigits": ["#"],      
                "InBetweenDigitsDurationInMilliseconds": 5000,  
                "Repeat": 3,                    
                "RepeatDurationInMilliseconds": 10000         
            },
            "ErrorType":  "SystemException",
            "ErrorMessage":  "System error while running action"
    },
    "CallDetails":{       
       ...
    }
}
```

**Error handling**  
This table lists and describes the error messages thrown by the the `Speak` action.


| Error | Message | Reason | 
| --- | --- | --- | 
| `AccessDenied` | The `AWSServiceRoleForAmazonChimeVoiceConnector` role is not configured correctly. | The role used to make requests to Amazon Polly doesn't exist or is missing permissions. To resolve, see the steps in the [Using the Amazon Chime SDK Voice Connector service-linked role](#speak-digits-policy) section | 
| `InvalidActionParameter` |   | There was an error validating the action parameters. To review the available parameters for this action, and their options, see [SynthesizeSpeech](https://docs.aws.amazon.com/polly/latest/dg/API_SynthesizeSpeech.html) in the Amazon Polly Developer Guide. | 
| `MissingRequiredActionParameter` | `Text` is a required parameter. | The action parameters must have a `Text` value | 
| `MissingRequiredActionParameter` | `Text` is limited to 1,000 characters | The text exceeded the character limit. | 
| `SystemException` | System error while running action. | A system error occurred while running the action. | 

## Using the Amazon Chime SDK Voice Connector service-linked role
<a name="speak-digits-policy"></a>

You don't need to manually create a service-linked role for the `Speak` or `SpeakAndGetDigits` actions. When you create or update a SIP media application in the Amazon Chime SDK console, the AWS Command Line Interface, or the AWS API, the Amazon Chime SDK creates the service-linked role for you.

For more information, see [Using the Amazon Chime service-linked role](https://docs.aws.amazon.com/chime/latest/ag/using-service-linked-roles-stream.html) in the *Amazon Chime SDK Administrator Guide*.

# StartBotConversation
<a name="start-bot-conversation"></a>

The `StartBotConversation` action establishes a voice conversation between an end user and your Amazon Lex v2 bot. The user provides the required information to the bot. The bot then returns the information to the public switched telephone network (PSTN) Audio Lambda function, and the function performs the requested tasks.

For example, the bot can play an optional welcome message at the start of a conversation to briefly describe the task that the PSTN audio Lambda function can perform. The conversation goes back and forth between the user and the bot until the bot gathers the required information. Once the conversation ends, the Amazon Chime SDK invokes your PSTN audio Lambda function with an action success event, which contains the information gathered by the bot. Your PSTN audio Lambda function processes the information and performs the requested task.

The Audio Service provides life-like conversational interaction with your users. For example, users can interrupt the bot and answer a question before the audio prompt finishes. What's more, users can use any combination of voice and DTMF digits to provide information. The bot waits for the user to provide input before responding. You can configure how long the bot waits for the user to finish speaking before interpreting any speech input. The user can also instruct the bot to wait if they need time to retrieve additional information during a call, such as credit card numbers.

The `StartBotConversation` action uses Amazon Lex and Amazon Polly for the duration of the bot conversation. Standard Amazon Lex and Amazon Polly costs apply. For more pricing information, see the [Amazon Lex streaming conversation pricing](https://aws.amazon.com/lex/pricing/), and [Amazon Polly Pricing](https://aws.amazon.com/polly/pricing/) pages.

**Note**  
You can't run this action on a bridged call, or on a call that has joined an Amazon Chime SDK meeting.

**Important**  
Use of Amazon Lex and Amazon Polly is subject to the [AWS Service Terms ](https://aws.amazon.com/service-terms/), including the terms specific to the AWS Machine Learning and Artificial Intelligence Services.

**Topics**
+ [StartBotConversation syntax](#startbot-syntax)
+ [Using the StartBotConversation action](#using-startbot)
+ [Handling ACTION\$1SUCCESSFUL events](#bot-action-success)
+ [Handling ACTION\$1FAILED events](#bot-action-fail)
+ [Granting permissions to use a bot](#bot-permissions)
+ [Configuring voice and DTMF timeouts](#bot-timeouts)
+ [Using DTMF inputs during a conversation](#bot-dtmf)
+ [Billing and service quotas](#bot-billing)

## StartBotConversation syntax
<a name="startbot-syntax"></a>

The following example shows typical `StartBotConversation` syntax.

```
{
  "SchemaVersion": "1.0",
  "Actions":[
    {
      "Type": "StartBotConversation",
      "Parameters": {
        "CallId": "string",
        "ParticipantTag": "string",
        "BotAliasArn": "string",
        "LocaleId": "string",
        "Configuration": {
          "SessionState": {
             "SessionAttributes": {
                "string": "string" 
             },
             "DialogAction" : {
               "Type": "string"
             }
          },
          "WelcomeMessages": [
            {
              "Content": "string",
              "ContentType": "string" 
            }
          ]
        }
      }
    }
  ]
}
```

**CallId**  
*Description* – The `CallID` of a participant in the `CallDetails` of the AWS Lambda function invocation. The `StartBotConversation` action uses this ID as the bot's `SessionId`. All bot conversations that take place on a call share the same conversation session. You can modify the session state between your user and your bot by using the [Amazon Lex PutSession](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_runtime_PutSession.html) API. For more information, see [Managing sessions with the Amazon Lex v2 API](https://docs.aws.amazon.com/lexv2/latest/dg/using-sessions.html) in the *Amazon Lex Developer Guide*.  
*Allowed values* – A valid call ID.  
*Required* – No, if `ParticipantTag` is present.  
*Default value* – None.

**ParticipantTag**  
*Description* – The `ParticipantTag` of one of the connected participants in the `CallDetails`.  
*Allowed values* – `LEG-A`.  
*Required* – No, if `CallId` is present.  
*Default value* – `ParticipantTag` of the invoked `callLeg`. Ignored if you specify `CallDetails`.

**BotAliasArn**  
*Description* – The bot alias ARN of your Lex bot. You must create the bot in the same AWS Region as your PSTN audio application. A valid Amazon Lex bot alias has this format: `arn:aws:lex:region:awsAccountId:bot-alias/botId/botAliasId`, where *`region`* is the AWS Region where your bot resides. The `awsAccountId` is the AWS account ID in which your Amazon Lex bot is created. The `botId` value is the identifier assigned to the bot when you created it. You can find the bot ID in the Amazon Lex console on the **Bot details** page. The `botAliasId` is the identifier assigned to the bot alias when you created it. You can find the bot alias ID in the Amazon Lex console on the **Aliases** page.   
*Allowed values* – A valid bot ARN.  
*Required* –Yes.  
*Default value* –None.

**LocaleId**  
*Description* – The identifier of the locale that you used for your bot. For a list of locales and language codes, see [ Languages and locales supported by Amazon Lex](https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html).  
*Allowed values* – [ Languages and locales supported by Amazon Lex.](https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html)  
*Required* – No.  
*Default value* – `en_US`.

**Configuration**  
*Description* – The conversation configuration, including session state and welcome messages. The total size of the JSON string representation of the `Configuration` object is limited to 10 KB.  
*Allowed values* – `Configuration` object.  
*Required* – No.  
*Default value* – None.

**Configuration.SessionState**  
*Description* – The state of the user's session with Amazon Lex v2.  
*Allowed values* – `SessionState` object.  
*Required* – No.  
*Default value* – None.

**Configuration.SessionState.SessionAttributes**  
*Description* – A map of the key/value pairs that represent session-specific context information. This map contains application information passed between Amazon Lex v2 and a client application.  
*Allowed values* – String to string map.  
*Required* – No.  
*Default value* – None.

**Configuration.SessionState.DialogAction.Type**  
*Description* – The next action that the bot takes in its interactions with the user. Possible values:  
+ *Delegate* Amazon Lex v2 determines the next action.
+ *ElicitIntent* The next action elicits an intent from the user.
*Allowed values* – `Delegate` \$1 `ElicitIntent`.  
*Required* – No.  
*Default value* – None.

**Configuration.WelcomeMessages**  
*Description* – A list of messages to send to the user at the start of the conversation. If you set the `welcomeMessage` field, you must set the `DialogAction.Type` value to `ElicitIntent`.  
*Allowed values* – Message object  
*Required* – No.  
*Default value* – None.

**Configuration.WelcomeMessages.Content**  
*Description* – The welcome message text.  
*Allowed values* – String.  
*Required* – No.  
*Default value* – None.

**Configuration.WelcomeMessages.ContentType**  
*Description* – Indicates the welcome message type.  
*Allowed values* –` PlainText` \$1 `SSML`  
+ *PlainText* – The message contains plain UTF-8 text. 
+ *SSML* – The message contains text formatted for voice output.
*Required* – Yes.  
*Default value* – None.

## Using the StartBotConversation action
<a name="using-startbot"></a>

The following example shows a typical `StartBotConversation` action.

```
{
  "SchemaVersion": "1.0",
  "Actions":[
    {
      "Type": "StartBotConversation",
      "Parameters": {
        "CallId": "call-id-1",
        "BotAliasArn": "arn:aws:lex:us-east-1:123456789012:bot-alias/ABCDEFGHIH/MNOPQRSTUV",
        "LocaleId": "en_US",
        "Configuration": {
          "SessionState": {
             "SessionAttributes": {
                "mykey1": "myvalue1" 
             },
             "DialogAction" : {
               "Type": "ElicitIntent"
             }
          },
          "WelcomeMessages": [
            {
              "Content": "Welcome. How can I help you?",
              "ContentType": "PlainText" 
            }
          ]
        }
      }
    }
  ]
}
```

## Handling ACTION\$1SUCCESSFUL events
<a name="bot-action-success"></a>

The following example shows a typical `ACTION_SUCCESSFUL` event for the `StartBotConversation` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": number,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData":
    {
        "CallId": "string",
        "Type": "StartBotConversation",
        "Parameters": {
            // parameters provided in the StartBotConversation action.
        },
        "CallDetails": {
            // Information about the call associated with the AWS Lambda invocation.
        },
        "IntentResult": {
            "SessionId": "string",
            "SessionState": {
                "SessionAttributes": {
                    "string": "string"
                },
                "Intent": {
                    "Name": "string",
                    "Slots":  {
                        "string": {
                            "Value": {
                                "OriginalValue": "string",
                                "InterpretedValue": "string",
                                "ResolvedValues": ["string"]
                            },
                            "Values": []
                        }
                    },
                    "State": "string",
                    "ConfirmationState": "string"
                }
            },
            "Interpretations": [
                {
                    "NluConfidence": {
                        "Score": number
                    },
                    "Intent": {
                        "Name": "string",
                        "Slots": {
                            "string": {
                                "Value": {
                                    "OriginalValue": "string",
                                    "InterpretedValue": "string",
                                    "ResolvedValues": ["string"]
                                },
                                "Values": []
                            }
                        },
                        "State": "string",
                        "ConfirmationState": "string"
                    }
                }
            ]
        }
    }
}
```

**IntentResult**  
The result of the conversation between the user and the bot.

**SessionId**  
The identifier of the bot conversation session. When a user starts a conversation with your bot, Amazon Lex creates a session. A session encapsulates the information exchanged between your user and the bot. The `StartBotConversation` action uses the call ID as the bot's `SessionId`. You can modify the session state between your user and your bot by using the Lex [https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_PutSession.html](https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_PutSession.html) API. For more information, see [ Managing sessions with the Amazon Lex V2 API ](https://docs.aws.amazon.com/lexv2/latest/dg/using-sessions.html) in the *Amazon Lex Developer Guide*.

**SessionState**  
The state of the user’s Amazon Lex v2 session. 

**SessionState.SessionAttributes**  
Map of key/value pairs that represent session-specific context information. The map contains bot conversation information passed between the Lambda function attached to your bot and the PSTN audio Lambda function.

**Interpretations**  
A list of intents derived by Amazon Lex that may satisfy the a customer's utterance. The intent with the highest `NluConfidence` score becomes the Intent for the `SessionState`. 

**Interpretations.NluConfidence.Score**  
A score that indicates how confident Amazon Lex v2 is that an intent satisfies a user's intent. Ranges between 0.00 and 1.00. Higher scores indicate higher confidence. 

**Intent**  
The action the user wants to perform.

**Intent.Name**  
The name of the intent.

**Intent.Slots**  
A map of all of the slots for the intent. The name of the slot maps to the value of the slot. If a slot has not been filled, the value is null.

**Intent.Slots.Value**  
The value of the slot.

**Intent.Slots.Values**  
A list of one or more values that the user provided for the slot.

**Intent.Slots.Value.OriginalValue**  
The text of the user's reply, entered for the slot.

**Intent.Slots.Value.InterpretedValue**  
*Description* – The value that Amazon Lex v2 determines for the slot. The actual value depends on the bot's value selection strategy setting. You can choose to use the value entered by the user, or you can have Amazon Lex v2 choose the first value in the `resolvedValues` list.

**Intent.Slots.Value.ResolvedValues**  
A list of additional values that Amazon Lex v2 recognizes for the slot.

**Intent.State**  
*Description* – Fulfillment information for the intent. Possible values:  
+ `Failed` – The Lambda function failed to fulfill the intent.
+ `Fulfilled` – The Lambda function fulfilled the intent.
+ `ReadyForFulfillment` – The information for the intent is present, and your Lambdafunction can fulfill the intent. 

**Intent.ConfirmationState**  
*Description* – Indicates confirmation of the intent. Possible values:  
+ *Confirmed* – The Intent is fulfilled.
+ *Denied* – The user responded "no" to the confirmation prompt.
+ *None* – The user wasn't prompted for confirmation, or the user was prompted but didn't confirm or deny the prompt.

## Handling ACTION\$1FAILED events
<a name="bot-action-fail"></a>

The following example shows a typical `ACTION_FAILED` event for the `StartBotConversation` action.

```
{
    "SchemaVersion": "1.0",
    "Sequence": number,
    "InvocationEventType": "ACTION_FAILED",
    "ActionData":{
        "CallId": "string",
        "Type": "StartBotConversation",
        "Parameters": {
            // parameters provided in the StartBotConversation action
        },
        "ErrorType": "string",
        "ErrorMessage": "string"
    },
    "CallDetails":{
    }
}
```

**ErrorType**  
A string that uniquely identifies an error condition.

**ErrorMessage**  
A generic description of the error condition.

### Error codes
<a name="action-errors"></a>

The following table lists the error messages that a Lambda function can return in an `ACTION_FAILED` event.


| Error | Description | 
| --- | --- | 
|  `InvalidActionParameter` | One or more action parameters are invalid. The error message describes the invalid parameter. | 
| `SystemException` | A system error occurred while running an action. | 
| `ResourceNotFound` | A specified bot is not found. | 
| `ResourceAccessDenied` | Access to the bot is denied. | 
| `ActionExecutionThrottled` | Bot conversation service limit is exceeded. The error message describes the specific service limit exceeded. | 

## Granting permissions to use a bot
<a name="bot-permissions"></a>

The following example grants the Amazon Chime SDK permission to call the Amazon Lex [https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_StartConversation.html](https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_StartConversation.html) APIs. You must explicitly grant the Audio Service permission to use your bot. The condition block is required for service principals. The condition block must use the global context keys `AWS:SourceAccount` and `AWS:SourceArn`. The `AWS:SourceAccount` is your AWS account ID. The `AWS:SourceArn` is the resource ARN of the PSTN audio application that invokes the Lex bot.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowChimePstnAudioUseBot",
      "Effect": "Allow",
      "Principal": {
        "Service": "voiceconnector.chime.amazonaws.com"
      },
      "Action": "lex:StartConversation",
  "Resource": "arn:aws:lex:us-east-1:123456789012:bot-alias/botId/aliasId",
      "Condition": {
        "StringEquals": {
          "AWS:SourceAccount": "123456789012"
        },
        "ArnEquals": {
        "AWS:SourceArn": "arn:aws:voiceconnector:us-east-1:123456789012:sma/smaId"
        }
      }
    }
  ]
}
```

------

## Configuring voice and DTMF timeouts
<a name="bot-timeouts"></a>

You can configure the voice and DTMF timeouts when capturing user input. You can configure timeouts through session attributes when starting a conversation with a bot, and overwrite them in your Lex bot's Lambda function if necessary. Amazon Lex lets you set multiple slots for an intent or bots. Because you can specify that session attributes apply to the intent and slot level, you can specify that the attribute is set only when you're collecting a certain type of input. For example, you can specify a longer time-out when you're collecting an account number than when you're collecting a date. You can use wildcards in the session attribute key. 

For example, to set a voice timeout for all slots for all intents to 4000 milliseconds, you can provide a session attribute using: `x-amz-lex:start-timeout-ms:*:*` as the session attribute name and `4000` as the session attribute value. For more information, see [ Configuring timeouts for capturing user input ](https://docs.aws.amazon.com/lexv2/latest/dg/session-attribs-speech.htm) in the *Amazon Lex Developer Guide*. 

## Using DTMF inputs during a conversation
<a name="bot-dtmf"></a>

Amazon Lex bots support voice and keypad input during a conversation. The bots interpret keypad input as DTMF digits. You can prompt contacts to end their input with a pound key (\$1) and to cancel a conversation by using the star key (\$1). If you don't prompt customers to end their input with the pound key, Lex stops waiting for additional key presses after 5 seconds.

## Billing and service quotas
<a name="bot-billing"></a>

AWS bills you for the following costs:
+ Amazon Chime SDK usage for the call. For more information, see [Amazon Chime SDK pricing](https://aws.amazon.com/chime/chime-sdk/pricing/).
+ Amazon Lex usage for interpreting users' speech. For more information, see [Amazon Lex streaming conversation pricing](https://aws.amazon.com/lex/pricing/).
+ Amazon Polly usage for synthesizing text responses from your bot. For more information, see [ Amazon Polly Pricing](https://aws.amazon.com/polly/pricing/).

You also need to be aware of the following service quotas:
+ The Amazon Chime SDK has a service quota for the maximum number of Amazon Lex bots you can use with the PSTN audio [StartBotConversation](#start-bot-conversation) action. For more information, refer to [SIP trunking and voice quotas](https://docs.aws.amazon.com/general/latest/gr/chime-sdk.html#chm-sdk-pstn-quotas), in the *AWS General Reference*.
+ Amazon Lex has a service quota for the maximum number of concurrent voice conversations per Lex bot. You can contact the Amazon Lex service team for quota increases. For more information, see the Amazon Lex [Guidelines and quotas](https://docs.aws.amazon.com/lexv2/latest/dg/quotas.html) in the *Amazon Lex Developer Guide*.
+ Amazon Polly has a service quota for synthesizing text responses. You can contact the Amazon Polly service team for quota increases. For more information about Amazon Polly service quotas, see [Quotas in Amazon Polly](https://docs.aws.amazon.com/polly/latest/dg/limits.html), in the *Amazon Polly Developer Guide*.

# Using SIP headers in the Amazon Chime SDK PTSN audio service
<a name="sip-headers"></a>

You can now send and receive a User-To-User header, a Diversion header, and custom SIP headers in your AWS Lambda functions when you want to exchange call context information with your SIP infrastructure. 
+ The User-to-User (UUI) header can be used to send call control data. This data is inserted by the application initiating a session and used by the application accepting the session. It is not used for any basic SIP functionality. For example, you could use the UUI header in a call center to pass information between agents about a call.
+ The Diversion header is used to show from where the call was diverted and why. You can use this header to either see diversion information from other SIP agents, or pass it along.
+ Custom SIP Headers allow you to pass along any other information you want. For example, if you want to pass along an account id, you can create an X header called “X-Account-Id” and add this information.

You must prefix your custom SIP headers with `x-`. The headers are exposed in the AWS Lambda function and received as part of a `NEW_INBOUND_CALL` event during an inbound call. You can also include these headers in outbound call legs when triggering a [CallAndBridge](call-and-bridge.md) action or the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html) API.

The `Participants` section of a Lambda function contains the `SipHeaders` field. This field is available when you receive a custom header, or when you populate the `User-to-User` or `Diversion` header.

This example shows an expected response when an AWS Lambda invocation contains SIP headers.

```
{
    "SchemaVersion": "1.0",
    "Sequence": 3,
    "InvocationEventType": "ACTION_SUCCESSFUL",
    "ActionData": {
        "Type":"actionType",
        "Parameters":{
            // Parameters vary by actionType
        }
    },
    "CallDetails":{
        .....
        .....
        "Participants":[
            {
                "CallId": "call-id-1",
                "ParticipantTag": "LEG-A",
                ..... 
                "Status": "Connected"
                "SipHeaders": {
                    "X-Test-Value": "String",
                    "User-to-User": "616d617a6f6e5f6368696d655f636f6e6e6563745f696e746567726174696f6e;encoding=hex",
                    "Diversion": "sip:+11234567891@public.test.com;reason=unconditional"
                }
            },
            {
            "CallId": "call-id-2",
            "ParticipantTag": "LEG-B",
            .....
            "Status": "Connected"
            }
        ]
    }
}
```

The following example shows a successful [CallAndBridge](call-and-bridge.md) action, due to an invalid entry for the `SipHeaders` parameter. 

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "CallAndBridge",
            "Parameters":{
            "CallTimeoutSeconds": 30,
            "CallerIdNumber": "e164PhoneNumber", // required
            "RingbackTone": { // optional
                "Type": "S3",
                "BucketName": "s3_bucket_name",
                "Key": "audio_file_name"
            },
            "Endpoints":[
               {
                    "Uri":"e164PhoneNumber", // required
                    "BridgeEndpointType":"PSTN" // required
               }
            ],
            "SipHeaders": {
                "X-Test-Value": "String",
                "User-to-User": "616d617a6f6e5f6368696d655f636f6e6e6563745f696e746567726174696f6e;encoding=hex",
                "Diversion": "sip:+11234567891@public.test.com;reason=unconditional"
            }
         }
      }
   ]
}
```

The following example shows a failed [CallAndBridge](call-and-bridge.md) action caused by an invalid `SipHeaders` parameter.

```
{
    "SchemaVersion":"1.0",
    "Sequence":3,
    "InvocationEventType":"ACTION_FAILED",
    "ActionData":{
        "Type":"actionType",
        "Parameters":{
            // Parameters vary by Action Type
            "SipHeaders": {
                "X-AMZN": "String",
                "User-to-User": "616d617a6f6e5f6368696d655f636f6e6e6563745f696e746567726174696f6e;encoding=hex",
                "Diversion": "sip:+11234567891@public.test.com;reason=unconditional"
             },
        },
        "ErrorType": "InvalidActionParameter",
        "ErrorMessage": "Invalid SIP header(s) provided: X-AMZN"
   },
   "CallDetails":{
      .....
      "Participants":[
         {
            "CallId":"call-id-1",
            "ParticipantTag":"LEG-A",
            .....   
            "Status":"Connected"
         },
         {
            "CallId":"call-id-2",
            "ParticipantTag":"LEG-B",
            .....
            "Status":"Connected"
         }
      ]
   }
}
```

## Using the SipHeaders field
<a name="custom-headers"></a>

When you trigger the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html) API, the optional `SipHeaders` field allows you to pass custom SIP headers to an outbound call leg. Valid header keys must include one of the following: 
+ The `x-` prefix
+ The `User-to-User` header
+ The `Diversion` header

`X-AMZN` is a reserved header. If you use this header in an API call, it will fail. The headers can be a maximum length of 2048 characters. 

The following example shows a typical [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html) API in the command-line interface with the optional `SipHeaders` parameter.

```
create-sip-media-application-call
    --from-phone-number value // (string)
    --to-phone-number value // (string)
    --sip-media-application-id value // (string)
    --sip-headers // (map)
```

For more information, see [A Mechanism for Transporting User-to-User Call Control Information in SIP](https://datatracker.ietf.org/doc/html/rfc7433) and [Diversion Indication in SIP](https://datatracker.ietf.org/doc/html/rfc5806).

# Using call detail records in the Amazon Chime SDK PTSN audio service
<a name="attributes"></a>

Amazon Chime SDK administrators can configure Amazon Chime SDK Voice Connectors to store *call detail records* (CDRs). For more information about configuring Amazon Chime SDK Voice Connectors to store CDRs, see [Managing global settings in Amazon Chime SDK](https://docs.aws.amazon.com/chime-sdk/latest/ag/manage-global.html) in the *Amazon Chime SDK Administration Guide*.

Once you enable CDRs, after each call the SIP media application sends the records to a folder named **Amazon-Chime-SMADRs** in your S3 bucket.

The following table lists the attributes of a CDR, and shows their proper formatting. The records contain all the fields listed here for all calls.


|  Value  |  Description  | 
| --- | --- | 
|  `"AwsAccountId":"AWS-account-ID"`  |  The AWS account ID associated with the SIP media application that initiated the PSTN usage  | 
|  `"TransactionId":"transaction-ID" `  |  The transaction ID of the call  | 
|  `"CallId":"SIP-media-application-call-ID"`  |  The call ID of the participant for the associated usage  | 
|  `"VoiceConnectorId":"voice-connector-ID"`  |  Amazon Chime SDK Voice Connector ID UUID  | 
|  `"Status":"status"`  |  Status of the call (Completed, Failed)  | 
|  `"BillableDurationSeconds":"billable-duration-in-seconds"`  |  Billable duration of the call in seconds  | 
|  `"SchemaVersion":"schema-version"`  |  The CDR schema version  | 
|  `"SourcePhoneNumber":"12075550155"`  |  E.164 origination phone number  | 
| "SourcePhoneNumberName":"North Campus Reception" | The name assigned to the source phone number | 
|  `"DestinationPhoneNumber":"13605551214"`  |  E.164 destination phone number  | 
| "DestinationPhoneNumberName":"South Campus Reception" | The name assigned to the destination phone number | 
|  `"UsageType":"usage-type"`  |  Usage details of the line item in the Price List API  | 
|  `"ServiceCode":"service-code" `  |  The code of the service in the Price List API  | 
|  `"Direction":"direction"`  |  Direction of the call, `Outbound` or `Inbound`  | 
|  `"TimeStampEpochSeconds":"start-time-epochseconds"`  |  The timestamp of the record in epoch/Unix timestamp format  | 
|  `"Region":"AWS-region"`  |  AWS Region for the Amazon Chime SDK Voice Connector  | 
|  `"SipRuleId":"sip-rule-id"`  |  The ID of the sip rule that is triggered when a call reaches the PSTN audio service  | 
|  `"SipApplicationId":"sip-application-id"`  |  The ID of the SIP application that handles a call  | 
|  `"CallLegTriggerType":"trigger-type"`  |  The type of event that triggered a call  | 
|  `"BillableVoiceFocusSeconds":"billable-voice-focus-in-seconds"`  |  The billable amount of Voice Focus usage, in seconds  | 

# Understanding timeouts and retries for the Amazon Chime SDK PTSN audio service
<a name="timeouts"></a>

The PSTN audio service interacts with AWS Lambda functions synchronously. Applications wait 5 seconds for AWS Lambda functions to respond before retrying an invocation. If no response is received after 20 second the PSTN Audio service will issue a [hang up](unexpected-hangups.md). When a function returns an error with one of the 4*XX* status codes, then by default the SIP media application only retries the invocation once. If you run out of retries, calls terminate with the `480 Unavailable` error code. For more information about AWS Lambda errors, see [Troubleshoot invocation issues in AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-invocation.html). 

# Debugging and troubleshooting the Amazon Chime SDK PTSN audio service
<a name="debug-pstn"></a>

Use the following information to help you diagnose and fix common issues that you might encounter when working with the Amazon Chime SDK PSTN audio service.

**Topics**
+ [Checking the logs for the Amazon Chime SDK PTSN audio service](check-logs.md)
+ [Debugging unexpected hangups in the Amazon Chime SDK PTSN audio service](unexpected-hangups.md)
+ [Debugging unexpected ACTION\$1FAILED events](unexpected-action-fail.md)

# Checking the logs for the Amazon Chime SDK PTSN audio service
<a name="check-logs"></a>

If you're debugging a SIP media application, check the Cloudwatch logs for the AWS Lambda function associated with the application. 

Next, check the logs associated with the SIP media application. As needed, you can configure the SIP media application for logging. For more information, see [Using SIP media applications](https://docs.aws.amazon.com/chime-sdk/latest/ag/use-sip-apps.html) in the *Amazon Chime SDK Administrator Guide*. If you enable logging, you can find the logs on Cloudwatch, in the `/aws/ChimeSipMediaApplicationSipMessages/<SIP-media-application-Id>` log group.

# Debugging unexpected hangups in the Amazon Chime SDK PTSN audio service
<a name="unexpected-hangups"></a>

Complete the following troubleshooting actions if you experience unexpected hangups or error messages with AWS Lambda functions for the PSTN audio service:
+ Verify that your AWS Lambda policy grants the `lambda:InvokeFunction` permission to the [voiceconnector.chime.amazonaws.com](http://voiceconnector.chime.amazonaws.com/) service principal.
+ Check the logs for your AWS Lambda function to ensure that it's being successfully invoked.
+ If the logs show incoming events and returned actions, verify that you don't return a hangup action in when the AWS Lambda function is invoked.
+ Check the CloudWatch logs for your SIP media application. The following table lists some of the messages you may encounter.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/unexpected-hangups.html)

# Debugging unexpected ACTION\$1FAILED events
<a name="unexpected-action-fail"></a>

If you receive an unexpected `ACTION_FAILED` event, check the following:

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/unexpected-action-fail.html)

# Understanding VoiceFocus for the Amazon Chime SDK PTSN audio service
<a name="voice-focus"></a>

Enables you to apply Amazon Voice Focus noise suppression to inbound and outbound call legs on a public switched telephony network (PSTN) call. When you apply Amazon Voice Focus, it reduces background noise without impacting human speech. This can make the current speaker easier to hear.

To create inbound call legs, you use a [SIP rule](https://docs.aws.amazon.com/chime/latest/ag/manage-sip-applications.html) that invokes an AWS Lambda function with a `NewInboundCall` event. You can create outbound call legs by using the [CallAndBridge](call-and-bridge.md) action, or by using a [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplicationCall.html) API operation. For more information about Amazon Voice Focus, see [ How the Amazon Chime SDK's noise cancellation works](https://www.amazon.science/blog/how-amazon-chimes-challenge-winning-noise-cancellation-works).

 Amazon Voice Focus reduces unwanted, non-speech noises, including: 
+ **Environment noises**—wind, fans, running water
+ **Background noises**—lawnmowers, barking dogs
+ **Foreground noises**—typing, paper shuffling

**Note**  
When you use Amazon Voice Focus, AWS bills you for the active call minutes of each call leg and for each minute of SIP media application usage.

This example shows a typical `VoiceFocus` action.

```
{
    "SchemaVersion": "1.0",
    "Actions":[
        {
            "Type": "VoiceFocus",
            "Parameters": {
                "Enable": True|False,            // required
                "CallId": "call-id-1",           // required    
            }
        }
    ]
}
```

**Enable**  
*Description* – Enables or disables Amazon Voice Focus  
*Allowed values* – `True` \$1 `False`  
*Required* – Yes  
*Default value* – None

**CallId**  
*Description* – CallId of participant in the `CallDetails` of the AWS Lambda function invocation  
*Allowed values* – A valid call ID  
*Required* – Yes  
*Default value* – None

This example shows a successful `ACTION_SUCCESSFUL` event for the `VoiceFocus` action.

```
{
   "SchemaVersion": "1.0",
   "Sequence": 3,
   "InvocationEventType": "ACTION_SUCCESSFUL",
   "ActionData": {
      "Type": "VoiceFocus",
      "Parameters": {
         "Enable": True,
         "CallId": "call-id-1"
      }
   },
   "CallDetails":{
      .....
      .....
      "Participants":[
         {
            "CallId": "call-id-of-caller",
            .....   
            "Status": "Connected"
         },
         {
            "CallId": "call-id-of-callee",
            .....
            "Status": "Connected"
         }
      ]
   }
}
```

This example shows a typical `ACTION_FAILED` event for the `VoiceFocus` action.

```
{
   "SchemaVersion": "1.0",
   "Sequence":2,
   "InvocationEventType": "ACTION_FAILED",
      "ActionData":{
      "Type": "VoiceFocus",
      "Parameters": {
         "Enable": True,
         "CallId": "call-id-1"
      }
      },
      "ErrorType": "SystemException",
      "ErrorMessage": "System error while running action"
   },
   "CallDetails":{
      .....
      .....
      "Participants":[
         {
            "CallId": "call-id-of-caller",
            .....   
         }
      ]
   }
}
```

**Error handling**  
For security reasons, the PSTN audio actions have a limit of 5 call requests per second, per customer account (CPS). When call requests exceed the 5 CPS limit, the action returns an error message. This table lists the error messages returned by the `VoiceFocus` action.


| Error | Message | Reason | 
| --- | --- | --- | 
| `ActionExecutionThrottled` | Failed to run action. The maximum number of actions per second has been reached. | The number of Voice Focus action requests per second exceeded the system limit.  | 
| `MissingRequiredActionParameter` | Missing required action parameter. | Missing one or more of the required parameters while running the action. | 
| `SystemException` | System error while running action. | A system error occurred while running the action. | 

**Call flows**  
This diagram shows the call flow for enabling and disabling Amazon Voice Focus for a `CallAndBridge` action between two PSTN calls.

![\[The call flow when you enable or disable Amazon Voice focus for two bridged PSTN calls.\]](http://docs.aws.amazon.com/chime-sdk/latest/dg/images/voice_focus-pstn1.png)


For the outbound call leg, the AWS Lambda function enables Amazon Voice focus for the caller and returns a set of actions, including `CallAndBridge`. Once the call is bridged, the `VoiceFocus` action returns an `ACTION_SUCCESSFUL` event, and the Lambda function returns another set of events that enables Amazon Voice Focus for the person being called. That set of actions includes `VoiceFocus`, `Enable`, `True`, and the caller's ID. No further action is taken until the caller hangs up. The Lambda function then sends a `Hangup` action to the SIP media application. The application hangs up the person being called and sends a Hangup function back to the Lambda function, which takes no further actions.

# Amazon Chime SDK PSTN audio service glossary
<a name="chm-dg-glossary"></a>

\$1 [A](#a) \$1 [C](#c) \$1 [E](#e) \$1 [I](#i) \$1 [L](#l) \$1 [M](#m) \$1 [N](#n) \$1 [O](#o) \$1 [P](#p) \$1 [S](#s) \$1 [T](#t) \$1 [V](#v) \$1 

## A
<a name="a"></a>

**Action**  
In an AWS Lambda function, an action is an item that you want to run on a leg of a phone call, such as sending or receiving digits, joining a meeting, and so on. For more information about actions supported by the PSTN audio service, see [Supported actions for the Amazon Chime SDK PSTN audio service](specify-actions.md).

**AWS Lambda**  
A compute service that lets you run code for almost any type of application or backend service without provisioning or managing servers.

**AWS Lambda function**  
In the context of the PSTN audio service, a function run in response to data passed by a SIP media application, such as placing an outbound call. 

## C
<a name="c"></a>

**Call detail record**  
Data from Amazon Chime SDK Voice Connector calls, such as account IDs, source phone numbers, and destination countries. The records land as objects in an Amazon Simple Storage Service (S3) bucket in your account. For more information, see [Managing global settings in Amazon Chime SDK](https://docs.aws.amazon.com/chime-sdk/latest/ag/manage-global.html) in the *Amazon Chime SDK Administrator Guide*. For information about the record schema, see [Using call detail records in the Amazon Chime SDK PTSN audio service](attributes.md) in this guide.

**call ID**  
The ID assigned to the legs of all incoming calls.

**Call leg**  
A part of a call. In Amazon Chime SDK applications, calls can come from valid phone numbers, a PSTN, or Amazon Chime SDK Voice Connectors. For more information, see [Learn about using Amazon Chime SDK PSTN audio service call legs](call-architecture.md) in this guide. 

**Carrier**  
A company that provides mobile services. Short for **wireless carrier**.

**Amazon Chime**  
A unified communications and collaboration service provided by AWS.

**Amazon Chime SDK**  
A software development kit used by developers to add real-time media and communications to custom communication applications. 

## E
<a name="e"></a>

**E.164**  
The only accepted format for phone numbers in the PSTN audio service. An ITU-T recommendation, numbers use a 1-3 digit country code, followed by a maximum 12-digit subscriber number. For example: US: `+14155552671`, UK: `+442071838750 44`, Australia: `+61285993444`. 

**Endpoint**  
 A hardware device or software service, such as a phone or a unified communications application. 

**EventBridge**  
A serverless event bus service that allows you to connect your applications to data from a variety of sources.  
SIP media applications do not send data to EventBridge. For more information, see [Automating the Amazon Chime SDK with EventBridge](https://docs.aws.amazon.com/chime-sdk/latest/ag/automating-chime-with-cloudwatch-events.html) in the *Amazon Chime SDK Administrator Guide*.

## I
<a name="i"></a>

**IVR**  
Interactive Voice Response. A system that allows people to interact with a computer-operated phone system by voice recognition or touchtone keypads.

## L
<a name="l"></a>

**Leg**  
See [Call leg](#call-leg).

## M
<a name="m"></a>

**Media**  
The audio, video, or chat messages available for use during an Amazon Chime SDK meeting. A custom communications application can contain one or more of each media type.

**Media Pipeline**  
A mechanism for streaming and capturing audio, video, messages, and events during an Amazon Chime SDK meeting. For more information, see [Creating Amazon Chime SDK media pipelines](media-pipelines.md) in this guide.

## N
<a name="n"></a>

**Number portability**  
The ability to move phone numbers between phone carriers or unified communication systems. 

## O
<a name="o"></a>

**Origination**  
The process of receiving a call from a PSTN and handing that call off to a VoIP endpoint. 

## P
<a name="p"></a>

**Participant tag**  
An identifier assigned to each call participant, `LEG-A` or `LEG-B`.

**Policy**  
Amazon Chime SDK requires the following types of policies:  
+ **IAM user policy** – A policy that defines the permissions for Identity and Access Management users. 
+ **Meeting policy** – A policy that enables one user to control another user’s computer when sharing screens during a meeting, and enables the option for meeting attendees to join meetings by receiving a phone call from Amazon Chime SDK.

**PSTN**  
Public Switched Telephone Network. The infrastructure and services that provide phone calling capabilities.

**PSTN audio service**  
An Amazon Chime SDK service that enables developers to add audio capabilities to their communication solutions.

## R
<a name="r"></a>

**Routing**  
Apps created using the Amazon Chime SDK use one or more types of routing:  
+ **Network routing** – The process of of selecting a path for traffic in a network, or between or across multiple networks.
+ **Interactions routing** – The process of ensuring that a call goes to the correct recipient or endpoint. 
+ **Call routing** – A call management feature that queues and distributes inbound calls to predefined recipients or endpoints.

## S
<a name="s"></a>

**SBC**  
Session border controller. A network element deployed to protect SIP based voice over Internet Protocol (VoIP) networks.

**Sequence**  
The sequence of events that invoke an AWS Lambda function. Each time a function is invoked during a call, the sequence is incremented.

**Service limit/service quota**  
The maximum number of resources, such as meetings, audio streams, or content shares, allowed by the Amazon Chime SDK For more information, see [Audio](meetings-sdk.md#audio) in this guide.

**SIP**  
Session Initiation Protocol, a signaling protocol used to initiate, maintain, and terminate real-time sessions that include any combination of voice, video, and messaging applications. For more information, see [SIP: Session Initiation Protocol](https://www.rfc-editor.org/rfc/rfc3261.html).

**SIP headers**  
Parameters in AWS Lambda functions that contain call control data, plus other data such as user account IDs.

**SIP media application**  
A managed object that passes values from a SIP rule to a target AWS Lambda function. Developers can call the [https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplication.html](https://docs.aws.amazon.com/chime-sdk/latest/APIReference/API_voice-chime_CreateSipMediaApplication.html) API to create SIP media applications, but they must have administrative permissions to do so.

**SIP rule**  
A managed object that passes phone numbers for Amazon Chime SDK Voice Connector URIs to a target SIP media application.

**SIP trunk**  
See [Amazon Chime SDK Voice Connector](#voice-connector).

**SMA**  
See SIP media application.

**SMA ID**  
See SIP media application.

## T
<a name="t"></a>

**Telco**  
A telecommunications service provider.

**Termination**  
The process of ending a call.

**Transaction**  
A call that contains one or more call legs. For more information, see [Learn about using Amazon Chime SDK PSTN audio service call legs](call-architecture.md) in this guide.

**Transaction ID**  
The ID of a transaction that contains multiple call legs. For more information, see [Learn about using Amazon Chime SDK PSTN audio service call legs](call-architecture.md) in this guide.

## V
<a name="v"></a>

**Amazon Chime SDK Voice Connector**  
An object that provides provides Session Initiation Protocol (SIP) trunking service for phone systems. Administrators use the Amazon Chime SDK administrative console to create an manage Voice Connectors. For more information, see [Managing Amazon Chime SDK Voice Connectors](https://docs.aws.amazon.com/chime-sdk/latest/ag/voice-connectors.html) in the *Amazon Chime SDK Administrator Guide*.

**Amazon Chime SDK Voice Connector group**  
A wrapper that contains multiple Voice Connectors from different AWS Regions. Groups allow incoming calls to fail over across Regions, which creates a fault-tolerant mechanism. For more information, see [Managing Amazon Chime SDK Voice Connector groups](https://docs.aws.amazon.com/chime-sdk/latest/ag/voice-connector-groups.html) in the *Amazon Chime SDK Administrator Guide*.