

# Getting Started with Amazon IVS Chat
<a name="getting-started-chat"></a>

Amazon Interactive Video Service (IVS) Chat is a managed, live-chat feature to go alongside your live video streams. (IVS Chat also can be used without a video stream.) You can create chat rooms and enable chat sessions between your users.

Amazon IVS Chat lets you focus on building customized chat experiences alongside live video. You don't need to manage infrastructure or develop and configure components of your chat workflows. Amazon IVS Chat is scalable, secure, reliable, and cost effective.

Amazon IVS Chat works best to facilitate messaging between participants of a live-video stream with a beginning and an end. 

The rest of this document takes you through the steps to build your first chat application using Amazon IVS Chat.

**Examples:** The following demo apps are available (three sample clients apps and a backend server app for token creation):
+ [Amazon IVS Chat Web Demo](https://github.com/aws-samples/amazon-ivs-chat-web-demo)
+ [Amazon IVS Chat for Android Demo](https://github.com/aws-samples/amazon-ivs-chat-for-android-demo)
+ [Amazon IVS Chat for iOS Demo](https://github.com/aws-samples/amazon-ivs-chat-for-ios-demo)
+ [Amazon IVS Chat Demo Backend](https://github.com/aws-samples/amazon-ivs-chat-web-demo/tree/main/serverless)

**Important:** Chat rooms that have no new connections or updates for 24 months are automatically deleted.

**Topics**
+ [Step 1: Do Initial Setup](getting-started-chat-create-account.md)
+ [Step 2: Create a Chat Room](getting-started-chat-create-room.md)
+ [Step 3: Create a Chat Token](getting-started-chat-auth.md)
+ [Step 4: Send and Receive Your First Message](getting-started-chat-send-and-receive.md)
+ [Step 5: Check Your Service-Quota Limits (Optional)](getting-started-chat-check-service-quota.md)

# Step 1: Do Initial Setup
<a name="getting-started-chat-create-account"></a>

Before proceeding, you must:

1. Create an AWS account.

1. Set up root and administrative users.

1. Set up AWS IAM (Identity and Access Management) permissions. Use the policy specified below.

For specific steps for all the above, see [Getting Started with IVS Low-Latency Streaming](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started.html) in the *Amazon IVS User Guide*. **Important**: In "Step 3: Set Up IAM Permissions," use this policy for IVS Chat:

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

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
      {
         "Effect": "Allow",
         "Action": [
            "ivschat:CreateChatToken",
            "ivschat:CreateLoggingConfiguration",
            "ivschat:CreateRoom",
            "ivschat:DeleteLoggingConfiguration",
            "ivschat:DeleteMessage",
            "ivschat:DeleteRoom",
            "ivschat:DisconnectUser",
            "ivschat:GetLoggingConfiguration",
            "ivschat:GetRoom",
            "ivschat:ListLoggingConfigurations",
            "ivschat:ListRooms",
            "ivschat:ListTagsForResource",
            "ivschat:SendEvent",
            "ivschat:TagResource",
            "ivschat:UntagResource",
            "ivschat:UpdateLoggingConfiguration",
            "ivschat:UpdateRoom"
          ],
          "Resource": "*"
      },
      {
         "Effect": "Allow",
         "Action": [
            "servicequotas:ListServiceQuotas",
            "servicequotas:ListServices",
            "servicequotas:ListAWSDefaultServiceQuotas",
            "servicequotas:ListRequestedServiceQuotaChangeHistoryByQuota",
            "servicequotas:ListTagsForResource",
            "cloudwatch:GetMetricData",
            "cloudwatch:DescribeAlarms"
         ],
         "Resource": "*"
      },
      {
         "Effect": "Allow",
         "Action": [
            "logs:CreateLogDelivery",
            "logs:GetLogDelivery",
            "logs:UpdateLogDelivery",
            "logs:DeleteLogDelivery",
            "logs:ListLogDeliveries",
            "logs:PutResourcePolicy",
            "logs:DescribeResourcePolicies",
            "logs:DescribeLogGroups",
            "s3:PutBucketPolicy",
            "s3:GetBucketPolicy",
            "iam:CreateServiceLinkedRole",
            "firehose:TagDeliveryStream"
         ],
         "Resource": "*"
      }
   ]
}
```

------

# Step 2: Create a Chat Room
<a name="getting-started-chat-create-room"></a>

An Amazon IVS chat room has configuration information associated with it (e.g., maximum message length).

The instructions in this section show you how to use the console or AWS CLI to set up chat rooms (including optional setup for reviewing messages and/or logging messages) and create rooms.

# Console Instructions for Creating an IVS Chat Room
<a name="create-room-console"></a>

These steps are divided into phases, starting with initial room setup and ending with final room creation.

Optionally, you can set up a room so messages are reviewed. For example, you can update message content or metadata, deny messages to prevent them from being sent, or let the original message through. This is covered in [Set Up to Review Room Messages (Optional)](#create-room-console-review-messages).

Also optionally, you can set up a room so that messages are logged. For example, if you have messages being sent to a chat room, you can log them to an Amazon S3 bucket, Amazon CloudWatch, or Amazon Kinesis Data Firehose. This is covered in [Set Up to Log Messages (Optional)](#create-room-console-log-messages).

## Initial Room Setup
<a name="create-room-console-setup"></a>

1. Open the [Amazon IVS Chat console](https://console.aws.amazon.com/ivs/chat). 

   (You also can access the Amazon IVS console through the [AWS Management Console](https://console.aws.amazon.com/).)

1. From the navigation bar, use the **Select a Region** drop-down to choose a region. Your new room will be created in this region.

1. In the **Get started** box (top right), choose **Amazon IVS Chat Room**. The **Create room** window appears.  
![\[Creating a Chat Room.\]](http://docs.aws.amazon.com/ivs/latest/ChatUserGuide/images/Chat_Create_Room.png)

1. Under **Setup**, optionally specify a **Room name**. Room names are not unique, but they provide a way for you to distinguish rooms other than the room ARN (Amazon Resource Name).

1. Under **Setup > Room configuration**, either accept the **Default configuration**, or select **Custom configuration **and then configure the **Maximum message length** and/or **Maximum message rate**.

1. If you want to review messages, continue with [Set Up to Review Room Messages (Optional)](#create-room-console-review-messages) below. Otherwise, skip that (i.e., accept **Message Review Handler > Disabled**) and proceed directly to [Final Room Creation](#create-room-console-final).

## Set Up to Review Room Messages (Optional)
<a name="create-room-console-review-messages"></a>

1. Under **Message Review Handler**, select **Handle with AWS Lambda**. The **Message Review Handler** section expands to show additional options.

1. Configure the **Fallback result** to **Allow** or **Deny** the message if the handler does not return a valid response, encounters an error, or exceeds the timeout period.

1. Specify your existing **Lambda function** or use **Create Lambda function** to create a new function.

   The lambda function must be in the same AWS account and the same AWS regions as the chat room. You should give the Amazon Chat SDK service permission to invoke your lambda resource. The resource-based policy will be automatically created for the lambda function you selected. For more information about permissions, see [Resource-Based Policy for Amazon IVS Chat](security-iam.md#security-chat-policy-examples).

## Set Up to Log Messages (Optional)
<a name="create-room-console-log-messages"></a>

1. Under **Message logging**, select **Automatically log chat messages**. The **Message logging** section expands to show additional options. You can either add an existing logging configuration to this room or create a new logging configuration by selecting **Create logging configuration**.

1. If you choose an existing logging configuration, a dropdown menu appears and shows all logging configurations that you already created. Select one from the list and your chat messages automatically will log to this destination.

1. If you choose **Create logging configuration**, a modal window appears which allows you to create and customize a new logging configuration.

   1. Optionally specify a **Logging configuration name**. Logging-configuration names, like room names, are not unique, but they provide a way for you to distinguish logging configurations other than the logging configuration ARN.

   1. Under **Destination**, select **CloudWatch log group**, **Kinesis firehose delivery stream**, or **Amazon S3 bucket** to choose the destination for your logs.

   1. Depending on your Destination, select the option to create a new or use an existing **CloudWatch log group**, **Kinesis firehose delivery stream**, or **Amazon S3 bucket**.

   1. After reviewing, choose **Create** to create a new logging configuration with a unique ARN. This automatically attaches the new logging configuration to the chat room.

## Final Room Creation
<a name="create-room-console-final"></a>

1. After reviewing, choose **Create chat room** to create a new chat room with a unique ARN.

# CLI Instructions for Creating an IVS Chat Room
<a name="create-room-cli"></a>

This document takes you through the steps involved in creating an Amazon IVS chat room using the AWS CLI.

## Creating a Chat Room
<a name="create-room-cli-chat-room"></a>

Creating a chat room with the AWS CLI is an advanced option and requires that you first download and configure the CLI on your machine. For details, see the [AWS Command Line Interface User Guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html).

1. Run the chat `create-room` command and pass in an optional name:

   ```
   aws ivschat create-room --name test-room
   ```

1. This returns a new chat room:

   ```
   {  
      "arn": "arn:aws:ivschat:us-west-2:123456789012:room/g1H2I3j4k5L6",
      "id": "string",
      "createTime": "2021-06-07T14:26:05-07:00",
      "maximumMessageLength": 200, 
      "maximumMessageRatePerSecond": 10,
      "name": "test-room",
      "tags": {},
      "updateTime": "2021-06-07T14:26:05-07:00"
   }
   ```

1. Note the `arn` field. You will need this to create a client token and connect to a chat room.

## Setting Up a Logging Configuration (Optional)
<a name="create-room-cli-logging"></a>

As with creating a chat room, setting up a logging configuration with the AWS CLI is an advanced option and requires that you first download and configure the CLI on your machine. For details, see the [AWS Command Line Interface User Guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html).

1. Run the chat `create-logging-configuration` command and pass in an optional name and a destination configuration pointing to an Amazon S3 bucket by name. This Amazon S3 bucket must exist before creating the logging configuration. (For details on creating an Amazon S3 bucket, see [Amazon S3 Documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html).)

   ```
   aws ivschat create-logging-configuration \
      --destination-configuration s3={bucketName=demo-logging-bucket} \
      --name "test-logging-config"
   ```

1. This returns a new logging configuration:

   ```
   {
      "Arn": "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ",
      "createTime": "2022-09-14T17:48:00.653000+00:00",
      "destinationConfiguration": { 
         "s3": {"bucketName": "demo-logging-bucket"}
      },
      "id": "ABcdef34ghIJ",
      "name": "test-logging-config",
      "state": "ACTIVE",
      "tags": {},
      "updateTime": "2022-09-14T17:48:01.104000+00:00"
   }
   ```

1. Note the `arn` field. You need this to attach the logging configuration to the chat room.

   1. If you are creating a new chat room, run the `create-room` command and pass the logging-configuration `arn`:

      ```
      aws ivschat create-room --name test-room \ 
      --logging-configuration-identifiers \
      "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"
      ```

   1. If you are updating an existing chat room, run the `update-room` command and pass the logging-configuration `arn`:

      ```
      aws ivschat update-room --identifier \
      "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6" \
      --logging-configuration-identifiers \
      "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"
      ```

# Step 3: Create a Chat Token
<a name="getting-started-chat-auth"></a>

For a chat participant to connect to a room and start sending and receiving messages, a chat token must be created. Chat tokens are used to authenticate and authorize chat clients.

This diagram illustrates the workflow for creating an IVS chat token:

![\[Authenticate and authorize your clients for your newly created chat room.\]](http://docs.aws.amazon.com/ivs/latest/ChatUserGuide/images/Chat_Getting_Started_Auth.png)


As shown above, a client application asks your server-side application for a token, and the server-side application calls CreateChatToken using an AWS SDK or [SigV4](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html) signed requests. Since AWS credentials are used to call the API, the token should be generated in a secure server-side application, not the client-side application.

A backend server application that demonstrates token generation is available at [Amazon IVS Chat Demo Backend](https://github.com/aws-samples/amazon-ivs-chat-web-demo/tree/main/serverless).

*Session duration* refers to how long an established session can remain active before it is automatically closed. That is, the session duration is how long the client can remain connected to the chat room before a new token must be generated and a new connection must be established. Optionally, you can specify session duration during token creation.

Each token can be used only once to establish a connection for an end user. If a connection is closed, a new token must be created before a connection can be re-established. The token itself is valid until the token-expiration timestamp included in the response.

When an end user wants to connect to a chat room, the client should ask the server application for a token. The server application creates a token and passes it back to the client. Tokens should be created for end users on demand.

To create a chat auth token, follow the instructions below. When you create a chat token, use the request fields to pass data about the chat end user and the end user’s messaging capabilities; for details, see [CreateChatToken](https://docs.aws.amazon.com//ivs/latest/ChatAPIReference/API_CreateChatToken.html) in the *IVS Chat API Reference*.

## AWS SDK Instructions
<a name="auth-sdk"></a>

Creating a chat token with the AWS SDK requires that you first download and configure the SDK on your application. Below are instructions for the AWS SDK using JavaScript.

**Important:** This code must be executed on the server side and its output passed to the client.

**Prerequisite:** To use the code sample below, you need to load the AWS JavaScript SDK into your application. For details, see [Getting started with the AWS SDK for JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started.html).

```
async function createChatToken(params) {
  const ivs = new AWS.Ivschat();
  const result = await ivs.createChatToken(params).promise();
  console.log("New token created", result.token);
}
/*
Create a token with provided inputs. Values for user ID and display name are 
from your application and refer to the user connected to this chat session.
*/
const params = {
  "attributes": {
    "displayName": "DemoUser",
  }",
  "capabilities": ["SEND_MESSAGE"],
  "roomIdentifier": "arn:aws:ivschat:us-west-2:123456789012:room/g1H2I3j4k5L6",
  "userId": 11231234
};
createChatToken(params);
```

## CLI Instructions
<a name="auth-cli"></a>

Creating a chat token with the AWS CLI is an advanced option and requires that you first download and configure the CLI on your machine. For details, see the [AWS Command Line Interface User Guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html). Note: generating tokens with the AWS CLI is good for testing purposes, but for production use, we recommend that you generate tokens on the server side with the AWS SDK (see instructions above).

1. Run the `create-chat-token` command along with room identifier and user ID for the client. Include any of the following capabilities: `"SEND_MESSAGE"`, `"DELETE_MESSAGE"`, `"DISCONNECT_USER"`. (Optionally, include session duration (in minutes) and/or custom attributes (metadata) about this chat session. These fields are not shown below.)

   ```
   aws ivschat create-chat-token --room-identifier "arn:aws:ivschat:us-west-2:123456789012:room/g1H2I3j4k5L6" --user-id "11231234" --capabilities "SEND_MESSAGE"
   ```

1. This returns a client token:

   ```
   {
     "token": "abcde12345FGHIJ67890_klmno1234PQRS567890uvwxyz1234.abcd12345EFGHI67890_jklmno123PQRS567890uvwxyz1234abcde12345FGHIJ67890_klmno1234PQRS567890uvwxyz1234abcde",
     "sessionExpirationTime": "2022-03-16T04:44:09+00:00",
     "tokenExpirationTime": "2022-03-16T03:45:09+00:00"
   }
   ```

1. Save this token. You will need this to connect to the chat room and send or receive messages. You will need to generate another chat token before your session ends (as indicated by `sessionExpirationTime`).

# Step 4: Send and Receive Your First Message
<a name="getting-started-chat-send-and-receive"></a>

Use your chat token to connect to a chat room and send your first message. Sample JavaScript code is provided below. IVS client SDKs also are available: see [Chat SDK: Android Guide](chat-sdk-android.md), [Chat SDK: iOS Guide](chat-sdk-ios.md), and [Chat SDK: JavaScript Guide](chat-sdk-js.md).

**Regional service:** The sample code below refers to your "supported region of choice." Amazon IVS Chat offers regional endpoints that you can use to make your requests. For the Amazon IVS Chat Messaging API, the general syntax of a regional endpoint is:
+ wss://edge.ivschat.<region-code>.amazonaws.com

For example, wss://edge.ivschat.us-west-2.amazonaws.com is the endpoint in the US West (Oregon) region. For a list of supported regions, see the Amazon IVS Chat information on the [Amazon IVS page](https://docs.aws.amazon.com/general/latest/gr/ivs.html) in the *AWS General Reference*.

```
/*
1. To connect to a chat room, you need to create a Secure-WebSocket connection
using the client token you created in the previous steps. Use one of the provided 
endpoints in the Chat Messaging API, depending on your AWS region.
*/
const chatClientToken = "GENERATED_CHAT_CLIENT_TOKEN_HERE";
const socket = "wss://edge.ivschat.us-west-2.amazonaws.com"; // Replace “us-west-2” with supported region of choice.
const connection = new WebSocket(socket, chatClientToken);

/*
2. You can send your first message by listening to user input 
in the UI and sending messages to the WebSocket connection.
*/
const payload = {
  "Action": "SEND_MESSAGE",
  "RequestId": "OPTIONAL_ID_YOU_CAN_SPECIFY_TO_TRACK_THE_REQUEST",
  "Content": "text message",
  "Attributes": {
    "CustomMetadata": "test metadata"
  }
}
connection.send(JSON.stringify(payload));

/*
3. To listen to incoming chat messages from this WebSocket connection 
and display them in your UI, you must add some event listeners.
*/
connection.onmessage = (event) => {
  const data = JSON.parse(event.data);
  displayMessages({
    display_name: data.Sender.Attributes.DisplayName,
    message: data.Content,
    timestamp: data.SendTime
  });
}

function displayMessages(message) {
  // Modify this function to display messages in your chat UI however you like.
  console.log(message);
}

/*
4. Delete a chat message by sending the DELETE_MESSAGE action to the WebSocket 
connection. The connected user must have the "DELETE_MESSAGE" permission to 
perform this action.
*/

function deleteMessage(messageId) {
  const deletePayload = {
    "Action": "DELETE_MESSAGE",
    "Reason": "Deleted by moderator",
    "Id": "${messageId}"
  }
  connection.send(deletePayload);
}
```

Congratulations, you are all set\$1 You now have a simple chat application that can send or receive messages.

# Step 5: Check Your Service-Quota Limits (Optional)
<a name="getting-started-chat-check-service-quota"></a>

Your chat rooms will scale along with your Amazon IVS live stream, to enable all your viewers to engage in chat conversations. However, all Amazon IVS accounts have limits on the number of concurrent chat participants and the rate of message delivery. 

*Ensure that your limits are adequate and request an increase if needed, especially if you are planning a large streaming event*. For details, see [Service Quotas (Low-Latency Streaming)](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/service-quotas.html), [Service Quotas (Real-Time Streaming)](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/service-quotas.html), and [Service Quotas (Chat)](service-quotas.md).