

# Amazon IVS 聊天功能入門
<a name="getting-started-chat"></a>

Amazon Interactive Video Service (IVS) Chat 是一種受管的伴隨即時影片串流的即時聊天功能。(IVS 聊天功能也可以在沒有影片串流的情況下使用。) 您可以建立聊天室並啟用使用者之間的聊天工作階段。

Amazon IVS 聊天功能可讓您專注於打造伴隨即時影片的自訂聊天體驗。您無需管理基礎設施，或開發和設定聊天工作流程的元件。Amazon IVS 聊天功能可擴展、安全、可靠且具有成本效益。

Amazon IVS 聊天功能最適合在有頭有尾的即時影片串流中，方便參與者之間的訊息傳遞。

本文件的其餘部分將引導您使用 Amazon IVS 聊天功能建置您的第一個聊天應用程式。

**範例:**可使用以下示範 (三個範例用戶端應用程式以及用於建立字符的後端伺服器應用程式)：
+ [Amazon IVS 聊天功能網頁試用版](https://github.com/aws-samples/amazon-ivs-chat-web-demo)
+ [Amazon IVS 聊天功能 Android 試用版](https://github.com/aws-samples/amazon-ivs-chat-for-android-demo)
+ [Amazon IVS 聊天功能 iOS 試用版](https://github.com/aws-samples/amazon-ivs-chat-for-ios-demo)
+ [Amazon IVS 聊天功能後端試用版](https://github.com/aws-samples/amazon-ivs-chat-web-demo/tree/main/serverless)

**重要：**24 個月沒有新連線或更新的聊天室將被自動刪除。

**Topics**
+ [步驟 1：執行初始設定](getting-started-chat-create-account.md)
+ [步驟 2：建立聊天室](getting-started-chat-create-room.md)
+ [步驟 3：建立聊天字符](getting-started-chat-auth.md)
+ [步驟 4：傳送和接收第一條訊息](getting-started-chat-send-and-receive.md)
+ [步驟 5：檢查服務配額限制 (選用)](getting-started-chat-check-service-quota.md)

# 步驟 1：執行初始設定
<a name="getting-started-chat-create-account"></a>

繼續進行之前，您必須：

1. 建立 AWS 帳戶。

1. 設定根使用者和管理使用者。

1. 設定 AWS IAM (Identity and Access Management) 許可。使用下面指定的政策。

如需上述各項的具體步驟，請參閱 *Amazon IVS 使用者指南*中的 [IVS 低延遲串流入門](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started.html)。**重要事項**：在「步驟 3：設定 IAM 許可」中，請將此政策用於 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": "*"
      }
   ]
}
```

------

# 步驟 2：建立聊天室
<a name="getting-started-chat-create-room"></a>

Amazon IVS 聊天室具有與之關聯的組態資訊 (例如，最大訊息長度)。

本節中的指示說明如何使用主控台或 AWS CLI 設定聊天室 (包括檢閱訊息和/或記錄訊息的選用設定) 以及建立聊天室。

# 建立 IVS 聊天室的主控台說明
<a name="create-room-console"></a>

這些步驟分為幾個舞台，從初始聊天室設定開始，到最後建立聊天室結束。

您可以選擇對聊天室進行設定以便審查訊息。例如，您可以更新訊息內容或中繼資料、拒絕訊息以阻止它們被傳送，或者讓原始訊息能夠傳遞。這在[設定以審查聊天室訊息 (選用)](#create-room-console-review-messages) 中進行了介紹。

同時，您可以選擇對聊天室進行設定，以便記錄訊息。例如，如果您有訊息傳送至聊天室，您可以將其記錄至 Amazon S3 儲存貯體、Amazon CloudWatch 或 Amazon Kinesis Data Firehose。這在[設定以記錄訊息 (選用)](#create-room-console-log-messages) 中進行了介紹。

## 初始聊天室設定
<a name="create-room-console-setup"></a>

1. 開啟 [Amazon IVS 聊天功能主控台](https://console.aws.amazon.com/ivs/chat)。

   (您也可以透過 [AWS 管理主控台](https://console.aws.amazon.com/)來存取 Amazon IVS 主控台。)

1. 從導覽列中，使用 **Select a Region** (選擇區域) 下拉式清單選擇區域。將會在此區域中建立您的新聊天室。

1. 在 **Get started** (開始使用) 方塊 (右上角) 中，選擇 **Amazon IVS Chat Room** (Amazon IVS 聊天室)。**Create room** (建立聊天室) 視窗隨即出現。  
![\[建立聊天室。\]](http://docs.aws.amazon.com/zh_tw/ivs/latest/ChatUserGuide/images/Chat_Create_Room.png)

1. 在 **Setup** (設定) 下，可選擇指定 **Room name** (聊天室名稱)。聊天室名稱不是唯一的，但它們可讓您區分聊天室 ARN (Amazon 資源名稱) 以外的聊天室。

1. 在 **Setup > Room configuration** (設定 > 聊天室組態) 下，要麼接受 **Default configuration** (預設組態)，要麼選取 **Custom configuration** (自訂組態) 然後設定 **Maximum message length** (最大訊息長度) 和/或 **Maximum message rate** (最大訊息速率)。

1. 如果您想對訊息進行審查，請繼續下面的[設定以審查聊天室訊息 (選用)](#create-room-console-review-messages) 步驟。否則，略過該步驟 (即，接受 **Message Review Handler > Disabled** (訊息審查處理常式 > 停用)) 並直接進行 [Final Room Creation](#create-room-console-final) (最終聊天室建立)。

## 設定以審查聊天室訊息 (選用)
<a name="create-room-console-review-messages"></a>

1. 在 **Message Review Handler** (訊息審查處理常式) 下，選取 **Handle with AWS Lambda** (使用 AWS Lambda 處理)。**Message Review Handler** (訊息審查處理常式) 區段會展開以顯示額外選項。

1. 設定 **Fallback result** (後援結果)，指示當處理常式未傳回有效回應、遇到錯誤或超過逾時期限時，要 **Allow** (允許) 或是 **Deny** (拒絕) 訊息。

1. 指定現有的 **Lambda function** (Lambda 函數) 或使用 **Create Lambda function** (建立 Lambda 函數) 建立一個新的函數。

   所使用的 Lambda 函數必須和聊天室位於相同的 AWS 區域和 AWS 帳戶中。您應該授予 Amazon 聊天開發套件服務叫用 lambda 資源的許可。系統將為您選取的 lambda 函數自動建立以資源為基礎的政策。如需許可的相關詳細資訊，請參閱適用於 [Amazon IVS 聊天功能的資源型政策](security-iam.md#security-chat-policy-examples)。

## 設定以記錄訊息 (選用)
<a name="create-room-console-log-messages"></a>

1. 在 **Message logging** (訊息記錄) 下，選取 **Automatically log chat messages** (自動記錄聊天訊息)。**Message logging** (訊息記錄) 區段會展開以顯示額外選項。您可以將現有的記錄組態新增至此聊天室，或選取 **Create logging configuration** (建立記錄組態) 來建立新的記錄組態。

1. 如果您選擇現有的記錄組態，則會出現下拉式功能表，其中會顯示您已建立的所有記錄組態。請從清單中選取一個記錄組態，您的聊天訊息將自動記錄到此目的地。

1. 如果您選擇 **Create logging configuration** (建立記錄組態)，則會出現強制回應視窗，讓您建立和自訂新的記錄組態。

   1. 選擇性指定 **Logging configuration name** (記錄組態名稱)。記錄組態名稱 (例如聊天室名稱) 並非唯一，但可讓您區分記錄組態 ARN 以外的記錄組態。

   1. 在**目的地**下，選取 **CloudWatch 日誌群組**、**Kinesis Firehose 交付串流**或 **Amazon S3 儲存貯體**，以選擇日誌的目的地。

   1. 請根據自己的目的地，選取建立新的選項或使用現有的 **CloudWatch log group** (CloudWatch 日誌群組)、**Kinesis firehose delivery stream** (Kinesis Firehose交付串流) 或 **Amazon S3 bucket** (Amazon S3 儲存貯體)。

   1. 審查後，選擇 **Create** (建立) 建立具有唯一 ARN 的新記錄組態。這會自動將新的記錄組態附加至聊天室。

## 最終聊天室建立
<a name="create-room-console-final"></a>

1. 審查後，選擇 **Create chat room** (建立聊天室) 建立一個具有唯一 ARN 的新聊天室。

# 建立 IVS 聊天室的 CLI 說明
<a name="create-room-cli"></a>

本文件將逐步介紹使用 AWS CLI 建立 Amazon IVS 聊天室所涉及的步驟。

## 建立聊天室
<a name="create-room-cli-chat-room"></a>

使用 AWS CLI 建立聊天室是進階選項，需要您先在機器上下載並設定 CLI。如需詳細資訊，請參閱《[AWS 命令列介面使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)》。

1. 執行聊天 `create-room` 命令並傳入選用名稱：

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

1. 這將傳回一個新的聊天室：

   ```
   {  
      "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. 記下 `arn` 欄位的內容。您將需要它來建立用戶端符記並連線至該聊天室。

## 設定記錄組態 (選用)
<a name="create-room-cli-logging"></a>

與建立聊天室一樣，使用 AWS CLI 設定記錄組態是一個進階選項，需要您先在電腦上下載並設定 CLI。如需詳細資訊，請參閱《[AWS 命令列介面使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)》。

1. 執行聊天 `create-logging-configuration` 命令，並傳遞選用名稱和依名稱指向 Amazon S3 儲存貯體的目的地組態。此 Amazon S3 儲存貯體必須存在，才能建立記錄組態。(如需建立 Amazon S3 儲存貯體的詳細資訊，請參閱 [Amazon S3 文件](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. 這將傳回新的記錄組態：

   ```
   {
      "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. 記下 `arn` 欄位的內容。您需要用此資料將記錄組態附加至聊天室。

   1. 若要建立新的聊天室，請執行 `create-room` 命令並傳遞記錄組態 `arn`：

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

   1. 若要更新現有的聊天室，請執行 `update-room` 命令並傳遞記錄組態 `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"
      ```

# 步驟 3：建立聊天字符
<a name="getting-started-chat-auth"></a>

聊天參與者要連線至聊天室並開始傳送及接收訊息，必須先建立聊天字符。聊天字符的功用在於驗證及授權聊天用戶端。

此圖表說明建立 IVS 聊天字符的工作流程：

![\[為新建立的聊天室驗證和授權用戶端。\]](http://docs.aws.amazon.com/zh_tw/ivs/latest/ChatUserGuide/images/Chat_Getting_Started_Auth.png)


如上所示，用戶端應用程式會向您的伺服器端應用程式索取字符，伺服器端應用程式會使用 AWS 開發套件或 [Sigv4](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html) 簽署的請求呼叫 CreateChatToken。由於我們使用 AWS 憑證呼叫 API，因此應在安全的伺服器端應用程式中產生字符，而不是在用戶端應用程式中產生。

可產生字符的試用版後端伺服器應用程式請到 [Amazon IVS 聊天功能後端試用版](https://github.com/aws-samples/amazon-ivs-chat-web-demo/tree/main/serverless)下載。

*工作階段持續時間*是指已建立的工作階段在自動關閉之前，維持作用中狀態的時間。即，工作階段持續時間是用戶端在必須產生新符記並建立新連線之前可以保持連線至聊天室的時間。建立字符的過程中，您可以選擇指定工作階段的持續時間。

每個字符只能為一名最終使用者建立連線一次。如果連線關閉，則必須建立新字符，才能重新建立連線。字符的有效期限以回應中的字符過期時間戳記為準。

最終使用者想連線至聊天室時，用戶端應向伺服器應用程式索取字符。伺服器應用程式會建立字符，並將字符傳遞回用戶端。最終使用者一旦提出需求，即應為其建立字符。

若要建立聊天驗證字符，請依以下指示操作。建立聊天字符時，請使用請求欄位傳遞聊天最終使用者和最終使用者傳訊功能的相關資料；如需詳細資訊，請參閱 *IVS 聊天功能 API 參考資料*中的 [CreateChatToken](https://docs.aws.amazon.com//ivs/latest/ChatAPIReference/API_CreateChatToken.html)。

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

若要使用 AWS 開發套件建立聊天字符，您必須先在應用程式上下載並設定開發套件。以下是使用 JavaScript 之 AWS SDK 的說明。

**重要：**此程式碼必須在伺服器端執行，再將其輸出傳遞給用戶端。

**必要條件**：若要使用以下程式碼範例，您需要將 AWS JavaScript SDK 載入應用程式中。如需詳細資訊，請參閱 [適用於 JavaScript 的 AWS SDK 入門](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 說明
<a name="auth-cli"></a>

使用 AWS CLI 建立聊天符記是進階選項，需要您先在機器上下載並設定 CLI。如需詳細資訊，請參閱《[AWS 命令列介面使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)》。注意：使用 AWS CLI 產生符記適合在測試時使用，但對於生產用途，我們建議您使用 AWS 開發套件在伺服器端產生符記 (請參閱上述說明)。

1. 執行 `create-chat-token` 命令並使用用戶端的聊天室識別符和使用者 ID。納入任何這些功能：`"SEND_MESSAGE"`、`"DELETE_MESSAGE"`、`"DISCONNECT_USER"`。(您還可以選擇設定工作階段持續時間 (以分鐘為單位) 和/或有關此聊天工作階段的自訂屬性 (中繼資料)。這些欄位未在下面顯示。)

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

1. 這將傳回一個用戶端符記：

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

1. 儲存此符記。您將需要它來連線至聊天室以及傳送或接收訊息。您需要在工作階段結束 (由 `sessionExpirationTime` 指示) 前產生另一個聊天符記。

# 步驟 4：傳送和接收第一條訊息
<a name="getting-started-chat-send-and-receive"></a>

使用您的聊天字符連線至聊天室，並傳送您的第一條訊息。下面提供了 JavaScript 程式碼範例。您也可使用 IVS 用戶端 SDK：請參閱[聊天 SDK：Android 版指南](chat-sdk-android.md)、[聊天 SDK：iOS 版指南](chat-sdk-ios.md)和[聊天 SDK：JavaScript 版指南](chat-sdk-js.md)。

**區域服務：**下面的程式碼範例參考您「所選擇的受支援區域」。Amazon IVS 聊天功能提供區域性端點，您可以用來提出請求。對於Amazon IVS 聊天功能訊息 API，區域端點的一般語法為：
+ wss://edge.ivschat.<區域代碼>.amazonaws.com

例如，wss://edge.ivschat.us-west-2.amazonaws.com 是位於美國西部 (奧勒岡) 區域的端點。如需支援的區域清單，請參閱 *AWS 一般參考*中的 [Amazon IVS 頁面](https://docs.aws.amazon.com/general/latest/gr/ivs.html)上的 Amazon IVS 聊天功能資訊。

```
/*
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);
}
```

恭喜您！所有步驟均已完成！您現在擁有了一個可以傳送或接收訊息的簡便的聊天應用程式。

# 步驟 5：檢查服務配額限制 (選用)
<a name="getting-started-chat-check-service-quota"></a>

您的聊天室將與您的 Amazon IVS 即時串流功能一起擴展，以使所有觀衆能夠參與聊天對話。但是，所有 Amazon IVS 帳戶對並行聊天參與者的數量和訊息傳遞速率都有限制。

*確保您的限制足夠，並在需要時請求增加，特別是當您正在規劃大型串流事件時*。如需詳細資訊，請參閱 [Service Quotas (低延遲串流)](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/service-quotas.html)、[Service Quotas (即時串流)](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/service-quotas.html) 和 [Service Quotas (聊天功能)](service-quotas.md)。