> ## 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) をどのように扱うかを知ることです。

たとえば、以下は、すべての新しく作成されたタイトルで Revision 1 として読み込まれるスタート CloudScript の `helloWorld` の例です (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 入力パラメーター

ただし、Rule (**Automation** -> **Rules**)、Segment Enter/Exit Action (**Players** -> **Segments**)、または Task Service (**Automation** -> **Tasks**) を介した PlayStream 内のイベントの結果として CloudScript を呼び出すこともできます。

その場合、関数に渡される context は、適切なアクションを取るために必要なすべての情報を提供します。

PlayStream イベントの仕組みの基本について読むには、ブログ [Introducing PlayStream](https://blog.playfab.com/blog/introducing-playstream/) を参照してください。PlayStream イベントの種類とそのプロパティのリストについては、[PlayFab API リファレンス](/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` には、[PlayStream イベント ドキュメント](/services/playfab/api-references/events) にあるすべてのパラメーターと共に、ハンドラーをトリガーした完全なイベントが JSON オブジェクトとして含まれます。たとえば、タイトルで任意の `player_logged_in event` に対して `handlePlayStreamEventAndProfile` を呼び出すルールを設定した場合、`playStreamEvent.EventName` は `player_logged_in` などになります ([そのイベントのパラメーターの完全なセットはこちら](/services/playfab/api-references/events/PlayerIdentity/player-logged-in))。

2. 次に、前の例にも示されている `playerProfile` があります。これには、イベントをトリガーしたプレイヤーに関する情報が含まれます。プロファイル パラメーターの詳細はここで見つかりますが、他の情報の中でも、タイトル内のプレイヤーの完全な統計セット、およびプレイヤーに割り当てたカスタム タグが含まれるため、そのデータを豊富な意思決定に使用できます。

3. コンテキストの最後の要素は `triggeredByTask` です。Rule および Segment Enter/Exit トリガーを使用する際に設定される最初の 2 つとは異なり、`triggeredByTask` はハンドラーがタスクの結果として (手動またはタイマーで) 実行されている場合にのみ適用されます。パラメーターは 2 つだけです:

* **Name** - タスクを作成したときに指定した一意の名前。

* **ID** - PlayFab が自動的に生成したタスクの一意の識別子。

ユーザー セグメントに対して実行されるタスクの場合は、`playerProfile` もありますが、`playStreamEvent` はありません。

セグメントなしでゲームに対して単に実行されるタスクの場合、意図はイベントのタイトル データを設定するなど、より一般的なものを実行することであるため、`playerProfile` はありません。

したがって、*name* は、実行する適切なアクションを決定するためにハンドラーのコード フローで使用する要素です。

## PlayStream と CloudScript の組み合わせ

多くの点で、PlayStream アクションによってトリガーされる CloudScript ハンドラーは、`ExecuteCloudScript` への直接呼び出しによってトリガーされるものよりもさらに多くの潜在的な機能を持っています。コンテキストを介して提供される豊富なデータ セットがあるためです。

これにより、当初予期していなかったイベントやプレイヤー プロファイルの要素を活用する *より多くの* ロジックでハンドラーを起動後に更新でき、クライアント コードを更新する必要は *ありません*。

さらに、PlayFab サービスの将来の更新でプレイヤー プロファイルへの追加を継続し、サーバー サイド ロジックのための *さらに多くの* オプションを提供します。


## Related topics

- [カスタム CloudScript の作成](/ja-jp/services/playfab/live-service-management/service-gateway/automation/cloudscript/writing-custom-cloudscript.md)
- [アクションとルールのクイックスタート](/ja-jp/services/playfab/data-analytics/acting-data/action-rules-quickstart.md)
- [PlayFab の PlayStream イベント モデル リファレンス](/ja-jp/services/playfab/api-references/events/index.md)
- [player_triggered_action_executed_cloudscript](/ja-jp/services/playfab/api-references/events/CloudScript/player-triggered-action-executed-cloudscript.md)
- [PlayStream および Telemetry を使用したリーダーボード](/ja-jp/services/playfab/community/leaderboards/leaderboards-with-playstream-and-telemetry.md)
