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

# Using CloudScript actions with PlayStream

> Explains the context data available inside a CloudScript handler triggered by a PlayStream action, and how to use it to drive PlayFab server logic.

CloudScript 핸들러가 PlayStream 작업에서 실행되면, 그 핸들러는 실행되는 이유에 대한 더 많은 데이터인 *context*에 액세스할 수 있으며, 이를 사용하여 서버 측 로직을 구동할 수 있습니다.

이 튜토리얼에서는 컨텍스트에서 사용할 수 있는 모든 것과 이를 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 입력 매개 변수

그러나 규칙(**Automation**->**Rules**), 세그먼트 진입/이탈 작업(**Players**->**Segments**), 또는 Task Service(**Automation**->**Tasks**)를 통해 PlayStream의 이벤트 결과로 CloudScript를 호출하는 것도 가능합니다.

그렇게 하면 함수에 전달되는 컨텍스트는 적절한 조치를 취하는 데 필요한 모든 정보를 제공합니다.

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`는 핸들러를 트리거한 완전한 이벤트를 [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`입니다. Rules와 Segment Enter/Exit 트리거를 사용할 때 설정되는 처음 두 요소와 달리, `triggeredByTask`는 수동이든 타이머든 태스크의 결과로 핸들러가 실행되는 경우에만 적용됩니다. 여기에는 두 개의 매개 변수만 포함됩니다.

* **Name** – 태스크를 만들 때 지정한 고유 이름.

* **ID** – PlayFab이 태스크에 대해 자동으로 생성한 고유 식별자.

사용자 세그먼트에 대해 실행되는 태스크의 경우 `playerProfile`도 있지만 `playStreamEvent`는 없습니다.

그리고 세그먼트 *없이* 단순히 게임에 대해 실행되는 태스크의 경우, 이벤트에 대한 타이틀 데이터 설정 같은 더 일반적인 것을 실행하는 것이 목적이므로 `playerProfile`은 없습니다.

따라서 *name*은 취해야 할 적절한 작업을 결정하기 위해 핸들러의 코드 흐름에서 사용하고 싶은 요소가 됩니다.

## PlayStream + CloudScript

여러 면에서 PlayStream 작업에 의해 트리거되는 CloudScript 핸들러는 `ExecuteCloudScript` 호출을 통해 직접 트리거되는 핸들러보다 더 큰 잠재적 기능을 가지고 있습니다. 컨텍스트를 통해 풍부한 데이터 세트가 제공되기 때문입니다.

이를 통해 원래 예상하지 못했던 이벤트나 플레이어 프로필의 요소를 활용하는 *더 많은* 로직으로 출시 후 핸들러를 업데이트할 수 있으며, 클라이언트 코드를 어떤 식으로든 업데이트할 필요가 *없습니다*.

또한 PlayFab 서비스의 향후 업데이트에서 플레이어 프로필에 계속 추가할 것이며, 이는 서버 측 로직에 대해 훨씬 *더 많은* 옵션을 제공할 것입니다.


## Related topics

- [PlayFab CloudScript using Azure Functions](/ko/services/playfab/live-service-management/service-gateway/automation/cloudscript-af/index.md)
- [player_triggered_action_executed_cloudscript](/ko/services/playfab/api-references/events/CloudScript/player-triggered-action-executed-cloudscript.md)
- [사용자 지정 CloudScript 작성](/ko/services/playfab/live-service-management/service-gateway/automation/cloudscript/writing-custom-cloudscript.md)
- [Actions & Rules quickstart](/ko/services/playfab/data-analytics/acting-data/action-rules-quickstart.md)
- [PlayStream 및 Telemetry와 함께 사용하는 통계](/ko/services/playfab/player-progression/statistics/statistics-with-playstream-and-telemetry.md)
