> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 搭配 PlayStream 使用 CloudScript 動作

> 說明由 PlayStream 動作觸發的 CloudScript 處理常式內可用的內容資料，以及如何使用它來推動 PlayFab 伺服器邏輯。

當 CloudScript 處理常式是從 PlayStream 動作啟動時，該處理常式可以存取更多關於其執行原因的資料 (也就是*內容*)，您可以使用這些資料來推動伺服器端邏輯。

本教學課程將逐步說明內容中有哪些可用資料，以及如何在 CloudScript 處理常式中加以運用。

## CloudScript 基本概念

充分發揮 CloudScript 效用的關鍵，在於了解如何使用您可用的輸入，也就是處理常式的 args 和 context。

例如，以下是入門 CloudScript 中的 `helloWorld` 範例，在所有新建立的遊戲中都會載入為 Revision 1 (也可在我們的 GitHub 上取得，[如下所示](https://github.com/PlayFab/CloudScriptSamples/tree/master/BasicSample))。

```javascript theme={null}
// This is a CloudScript function.
// "args" is set to the value of the "FunctionParameter" parameter of the ExecuteCloudScript API.
// "context" contains additional information when the CloudScript function is called from a PlayStream action.
handlers.helloWorld = function (args, context) {

    // The pre-defined "currentPlayerId" variable is initialized to the PlayFab ID of the player logged-in on the game client.
    // CloudScript handles authenticating the player automatically.
    var message = "Hello " + currentPlayerId + "!";

    // You can use the "log" object to write out debugging statements. It has
    // three functions corresponding to logging level: debug, info, and error. These functions
    // take a message string and an optional object.
    log.info(message);
    var inputValue = null;
    if (args != null && args != undefined)
    {
        inputValue = args.inputValue;
    }
    log.debug("helloWorld:", { input: inputValue });

    // The value you return from a CloudScript function is passed back
    // to the game client in the ExecuteCloudScript API response, along with any log statements
    // and additional diagnostic information, such as any errors returned by API calls or external HTTP
    // requests. They are also included in the optional player_executed_cloudscript PlayStream event
    // generated by the function execution.
    return { messageValue: message };
}
```

此範例示範透過 [ExecuteCloudScript](xref:titleid.playfabapi.com.client.server-sidecloudscript.executecloudscript) 從用戶端呼叫 CloudScript 的常見使用案例。它會檢查以索引鍵 `inputValue` 傳入的引數，並將該索引鍵的值作為執行之偵錯記錄資訊所傳回文字的一部分。

## context 輸入參數

不過，也可以透過規則 (**Automation**->**Rules**)、區段進入/離開動作 (**Players**->**Segments**) 或工作服務 (**Automation**->**Tasks**)，因應 PlayStream 中的事件而呼叫 CloudScript。

當您這樣做時，傳入函式的 context 會提供您採取適當動作所需的所有資訊。

若要了解 PlayStream 事件運作方式的基本概念，請參閱我們的部落格文章 [Introducing PlayStream](https://blog.playfab.com/blog/introducing-playstream/)；如需 PlayStream 事件類型及其屬性的清單，請參閱我們的 [PlayFab API 參考](/zh-TW/services/playfab/api-references)。

若要檢視此動作，請查看同一個範例 CloudScript 中的 `handlePlayStreamEventAndProfile` 處理常式。

```javascript theme={null}
// This is a simple example of a function that is called from a
handlers.handlePlayStreamEventAndProfile = function (args, context) {

    // The event that triggered the action.
    // For a list of event types, see our PlayFab API documentation.
    var psEvent = context.playStreamEvent;

    // The profile data of the player associated with the event
    var profile = context.playerProfile;

    // Post data about the event to an external API
    var content = JSON.stringify({user: profile.PlayerId, event: psEvent.EventName});
    var response = http.request('https://httpbin.org/status/200', 'post', content, 'application/json', null, true);

    return { externalAPIResponse: response };
}
```

在由 PlayStream 觸發的 CloudScript 呼叫中，context 包含 3 個元素，可用來推動您以伺服器為權威之處理常式的邏輯。

1. 首先是 `playStreamEvent`，您可以在上方的範例程式碼中看到它。`playStreamEvent` 以 JSON 物件的形式包含觸發處理常式的完整事件，其中包含您在 [PlayStream 事件文件](/zh-TW/services/playfab/api-references/events)中看到的所有參數。例如，如果您在遊戲中設定了一個規則，在任何 `player_logged_in event` 上呼叫 `handlePlayStreamEventAndProfile`，則 `playStreamEvent.EventName` 會是 `player_logged_in`，依此類推 ([這是該事件的完整參數集](/zh-TW/services/playfab/api-references/events/PlayerIdentity/player-logged-in))。

2. 接下來是 `playerProfile`，也顯示在先前的範例中。其中包含觸發事件之玩家的相關資訊。您可以在這裡找到設定檔參數的所有詳細資料，除此之外，它還包含玩家在您遊戲中的完整統計資料集，以及您指派給玩家的任何自訂標籤，讓您可以使用這些資料進行豐富的決策。

3. context 的最後一個元素是 `triggeredByTask`。前兩個元素是在使用規則和區段進入/離開觸發程序時設定的，而 `triggeredByTask` 則不同，它僅適用於處理常式因工作 (無論是手動或依計時器) 而執行的情況。它只包含兩個參數：

* **Name**：您在建立工作時為其指定的唯一名稱。

* **ID**：PlayFab 為您的工作自動產生的唯一識別碼。

對於針對使用者區段執行的工作，您也會有 `playerProfile`，但不會有 `playStreamEvent`。

而對於只是針對您的遊戲執行、*沒有*任何區段的工作，則不會有 `playerProfile`，因為其目的是執行更一般性的作業，例如為活動設定某些遊戲資料。

因此，*name* 是您會想在處理常式的程式碼流程中使用的元素，用來判斷要採取的適當動作。

## PlayStream 加上 CloudScript

在許多方面，由 PlayStream 動作觸發的 CloudScript 處理常式，比直接透過呼叫 `ExecuteCloudScript` 觸發的處理常式具有更多潛在功能，因為 context 提供了豐富的資料集。

這讓您能夠在發行後以*更多*邏輯更新處理常式，運用您原本未預期到的事件或玩家設定檔元素，而*不需要*以任何方式更新用戶端程式碼。

此外，我們將在 PlayFab 服務的未來更新中持續新增玩家設定檔的內容，為伺服器端邏輯提供*更多*選項。


## Related topics

- [搭配 PlayStream 和遙測使用統計資料](/zh-TW/services/playfab/player-progression/statistics/statistics-with-playstream-and-telemetry.md)
- [排行榜與 PlayStream 和 Telemetry](/zh-TW/services/playfab/community/leaderboards/leaderboards-with-playstream-and-telemetry.md)
- [動作與規則快速入門](/zh-TW/services/playfab/data-analytics/acting-data/action-rules-quickstart.md)
- [玩家區段設定](/zh-TW/services/playfab/player-progression/player-data/player-segment-configuration.md)
- [搭配實體事件使用 PlayStream](/zh-TW/services/playfab/data-analytics/ingest-data/playstream-with-entity-events.md)
