> ## 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.

# 将 CloudScript 操作与 PlayStream 结合使用

> 解释由 PlayStream 操作触发的 CloudScript 处理程序内部可用的上下文数据，以及如何使用它来驱动 PlayFab 服务器逻辑。

当 CloudScript 处理程序从 PlayStream 操作启动时，该处理程序可以访问有关它为何运行的更多数据 - *上下文* - 你可以使用它来驱动服务器端逻辑。

本教程将引导你了解上下文中可用的所有内容以及如何在 CloudScript 处理程序中使用它。

## CloudScript 基础知识

充分利用 CloudScript 的关键在于知道如何使用可用的输入 – 即处理程序的 args 和 context。

例如，这是入门 CloudScript 中的 `helloWorld` 示例，在所有新创建的游戏中作为版本 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` 传入的参数，并使用该键的值作为执行的调试日志信息中返回的文本的一部分。

## 上下文输入参数

但是，也可以由 PlayStream 中的事件调用 CloudScript，通过规则 (**Automation**->**Rules**)、分段进入/退出操作 (**Players**->**Segments**) 或任务服务 (**Automation**->**Tasks**)。

当你这样做时，传递给函数的上下文提供了执行适当操作所需的所有信息。

要阅读 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 调用的情况下，上下文包含 3 个元素，可用于驱动服务器权威处理程序的逻辑。

1. 有 `playStreamEvent`，你可以在上面的示例代码中看到。`playStreamEvent` 包含触发处理程序的完整事件作为 JSON 对象，具有你在 [PlayStream 事件文档](/services/playfab/api-references/events) 中看到的所有参数。例如，如果你在游戏中设置了一个规则，对任何 `player_logged_in event` 调用 `handlePlayStreamEventAndProfile`，则 `playStreamEvent.EventName` 将为 `player_logged_in` 等等（[这里是该事件的完整参数集](/services/playfab/api-references/events/PlayerIdentity/player-logged-in)）。

2. 接下来是 `playerProfile`，也在前面的示例中显示。它包含有关触发事件的玩家的信息。你可以在此处找到配置文件参数的所有详细信息，但除其他外，它包含你游戏中玩家的完整统计信息集，以及你分配给玩家的任何自定义标记，以便你可以使用该数据进行丰富的决策。

3. 上下文的最后一个元素是 `triggeredByTask`。与前两个不同（前两个在使用规则和分段进入/退出触发器时设置），`triggeredByTask` 仅在处理程序作为任务的结果（无论是手动还是定时）运行时才适用。它只包含两个参数：

* **Name** – 你在创建任务时为其指定的唯一名称。

* **ID** – PlayFab 为你的任务自动生成的唯一标识符。

对于针对用户分段运行的任务，你也将拥有 `playerProfile`，但不会有 `playStreamEvent`。

对于一个仅针对你的游戏运行但 *没有* 任何分段的任务，将不会有 `playerProfile`，因为其意图是运行更通用的东西，比如为事件设置一些游戏数据。

因此 *name* 是你在处理程序的代码流中要使用的元素，以确定要采取的适当操作。

## PlayStream 加 CloudScript

在许多方面，由 PlayStream 操作触发的 CloudScript 处理程序具有比通过直接调用 `ExecuteCloudScript` 触发的处理程序更多的潜在功能，因为通过上下文提供了丰富的数据集。

这使你能够在发布后使用 *更多* 逻辑来更新处理程序，这些逻辑利用了你最初没有预料到的事件或玩家配置文件的元素，*无需* 以任何方式更新你的客户端代码。

此外，我们将在 PlayFab 服务的未来更新中继续对玩家配置文件进行添加，这将为服务器端逻辑提供 *更多* 选项。


## Related topics

- [排行榜与 PlayStream 和遥测](/zh-CN/services/playfab/community/leaderboards/leaderboards-with-playstream-and-telemetry.md)
- [使用 PlayStream 和遥测的统计信息](/zh-CN/services/playfab/player-progression/statistics/statistics-with-playstream-and-telemetry.md)
- [操作和规则快速入门](/zh-CN/services/playfab/data-analytics/acting-data/action-rules-quickstart.md)
- [玩家细分配置](/zh-CN/services/playfab/player-progression/player-data/player-segment-configuration.md)
- [将 Experiments 与其他 PlayFab 服务集成](/zh-CN/services/playfab/live-service-management/game-configuration/experiments/experiments-other-services.md)
