# Use case sample: Wish players a happy new year

> Send a push notification to all users on January 1st at 00:00:00 UTC wishing them a happy new year.

This sample demonstrates how to set up a schedule to send a push notification to all users wishing them a happy new year at 00:00:00 UTC on January 1st

> **Note:**
>
> You can only use [push messages](/cloud-code/modules/how-to-guides/push-messages.md) with Cloud Code modules.

## Prerequisites

You must first create a service account with required access roles and configure the [UGS CLI](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/install-the-cli/).

### Authenticate using a Service Account

Before you can call the Scheduling and Triggers services, you must authenticate using a Service Account.

1. Navigate to the [Unity Dashboard](https://cloud.unity.com).
2. Select **Administration** > **Service Accounts**.
3. Select the **New** button and enter a name and description for the Service Account.
4. Select **Create**.

Add Product roles and create a key:

1. Select **Manage product roles**.
2. Add the following roles to the Service Account:
   * From the LiveOps dropdown, select **Triggers Configuration Editor**, **Triggers Configuration Viewer**, **Scheduler Configuration Editor** and **Scheduler Configuration Viewer** .
   * From the Admin dropdown, select **Unity Environments Viewer**.
3. Select **Save**.
4. Select **Add Key**.
5. Encode the **Key ID** and **Secret key** using base64 encoding. The format is “key\_id:secret\_key”. Note this value down.

For more information, refer to [Authentication](../../authentication).

### Configure the UGS CLI

Follow the steps below to get stated with the UGS CLI:

1. [Install the UGS CLI](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/install-the-cli/).

2. Configure your Project ID and Environment as such:
   `ugs config set project-id <your-project-id>`
   `ugs config set environment-name <your-environment-name>`

3. Authenticate using the Service account you created earlier. Refer to [Get Authenticated](https://services.docs.unity.com/guides/ugs-cli/latest/general/get-started/get-authenticated/).

## Set up Cloud Code

Define a module endpoint that sends a push notification to the player whose score was beaten.

Create a `WishHappyNewYear` module function with contents as below:

```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Unity.Services.CloudCode.Apis;
using Unity.Services.CloudCode.Core;
using Unity.Services.CloudCode.Shared;

namespace WishHappyNewYear;

public class HappyNewYear
{
    private readonly ILogger<HappyNewYear> _logger;

    public HappyNewYear(ILogger<HappyNewYear> logger)
    {
        _logger = logger;
    }

    [CloudCodeFunction("SendProjectMessage")]
    public async Task SendProjectMessage(IExecutionContext context, IPushClient pushClient, string message, string messageType)
    {
        try
        {
            await pushClient.SendProjectMessageAsync(context, message, messageType);
        }
        catch (ApiException e)
        {
            _logger.LogError("Failed to send project message. Error: {Error}",  e.Message);
            throw new Exception($"Failed to send project message. Error: {e.Message}");
        }
    }

}

public class ModuleConfig : ICloudCodeSetup
{
    public void Setup(ICloudCodeConfig config)
    {
        config.Dependencies.AddSingleton<IPushClient>(PushClient.Create());

    }
}
```

Deploy the module.

Refer to [Deploying Hello World](/cloud-code/scripts/getting-started.md#deploying-hello-world) to learn how to deploy a module.

> **Note:**
>
> If you are deploying the module using the UGS CLI, don't forget to add additional Service Account role of `Cloud Code Editor`.

## Schedule an event

After you have defined your Cloud Code module, you can create a schedule to send a push notification to all users
wishing them a happy new year at 00:00:00 UTC on January 1st.

Run the `new-file` command to create a schedule configuration locally:

```bash
ugs scheduler new-file schedule-config
```

Update the `schedule-config.sched` file with the following configuration:

```json
{
  "$schema": "https://ugs-config-schemas.unity3d.com/v1/schedules.schema.json",
  "Configs": {
    "wish-happy-new-year": {
      "EventName": "send-announcement",
      "Type": "one-time",
      "Schedule": "2025-01-01T00:00:00Z",
      "PayloadVersion": 1,
      "Payload": "{\"message\": \"Happy New Year!\", \"messageType\": \"HappyNewYear\"}"
    }
  }
}
```

Deploy the configuration using the UGS CLI tool:

```bash
ugs deploy schedule-config.sched
```

The correct response is similar to the following:

```text
Deployed:
    schedule-config.sched
```

## Configure a trigger

To connect your Cloud Code module to the scheduler event, create a trigger.
The trigger executes the Cloud Code module when the event is fired at 00:00:00 UTC on January 1st.

Run the `new-file` command to create a trigger configuration locally:

```bash
ugs triggers new-file triggers-config
```

Update the `triggers-config.tr` file with the following configuration:

```json
{
  "$schema": "https://ugs-config-schemas.unity3d.com/v1/triggers.schema.json",
  "Configs": [
    {
      "Name": "happy-new-year",
      "EventType": "com.unity.services.scheduler.send-announcement.v1",
      "ActionUrn": "urn:ugs:cloud-code:WishHappyNewYear/SendProjectMessage",
      "ActionType": "cloud-code"
    }
  ]
}
```

Deploy the configuration using the UGS CLI tool:

```bash
ugs deploy triggers-config.tr
```

You should get a response similar to the following:

```text
Deployed:
    triggers-config.tr
```

Now you have a trigger that executes your Cloud Code module function when the scheduler event is fired at 00:00:00 UTC on January 1st.

## Validate the result

To validate the result, set up a Unity project that subscribes to push messages.

> **Note:**
>
> To test the event, you might want change the timestamp in the `one-time` field to a closer time.

### Prerequisites

To subscribe to push messages, you must first install the Cloud Code SDK and link your [Unity Gaming Services project](/cloud/projects.md) to the Unity Editor.

#### Link project

Link your [Unity Gaming Services project](/cloud/projects.md) with the Unity Editor. You can find your UGS project ID in the [Unity Dashboard](https://cloud.unity.com).

1. In the Unity Editor, select **Edit** > **Project Settings** > **Services**.

2. Link your project.

* If your project doesn't have a Unity project ID:

1. Select **Create a Unity Project ID** > **Organizations**, then select an organization from the dropdown menu.
2. Select **Create project ID**.

* If you have an existing Unity project ID:

1. Select **Use an existing Unity project ID**.
2. Select an organization and a project from the dropdown menus.
3. Select **Link project ID**.

Your Unity Project ID appears, and the project is now linked to Unity services. You can also access your project ID in a Unity Editor script using `UnityEditor.CloudProjectSettings.projectId`.

#### SDK installation

To install the latest Cloud Code package for Unity Editor:

1. In the Unity Editor, open **Window** > **Package Manager**.
2. In the Package Manager, select the **Unity Registry** list view.
3. Search for `com.unity.services.cloudcode`, or locate the Cloud Code package in the list.
4. Select the package, then click **Install**.

> **Note:**
>
> Check [Unity - Manual: Package Manager window](https://docs.unity3d.com/Manual/upm-ui.html) to familiarize yourself with the Unity Package Manager interface.

> **Note:**
>
> Subscribing to messages is available with Cloud Code SDK version 2.4.0+.

### Create a `Monobehaviour` script

Set up a `Monobehaviour` script to subscribe to project-level messages.

Refer to [Send push messages](/cloud-code/modules/how-to-guides/push-messages.md) for more information.

You can use the sample code below for your `MonoBehaviour` script:

```csharp
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Unity.Services.Authentication;
using Unity.Services.CloudCode;
using Unity.Services.CloudCode.Subscriptions;
using Unity.Services.Core;
using UnityEngine;

namespace CloudCode
{
	public class CloudCodePushExample : MonoBehaviour
	{
    	async void Start()
        {
            await UnityServices.InitializeAsync();
            await AuthenticationService.Instance.SignInAnonymouslyAsync();
            Debug.Log(AuthenticationService.Instance.PlayerId);
            await SubscribeToProjectMessages();
        }

        // This method creates a subscription to project messages and logs out the messages received,
        // the state changes of the connection, when the player is kicked and when an error occurs.
        Task SubscribeToProjectMessages()
        {
            var callbacks = new SubscriptionEventCallbacks();
            callbacks.MessageReceived += @event =>
            {
                Debug.Log(DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
                Debug.Log($"Got project subscription Message: {JsonConvert.SerializeObject(@event, Formatting.Indented)}");
            };
            callbacks.ConnectionStateChanged += @event =>
            {
                Debug.Log($"Got project subscription ConnectionStateChanged: {JsonConvert.SerializeObject(@event, Formatting.Indented)}");
            };
            callbacks.Kicked += () =>
            {
                Debug.Log($"Got project subscription Kicked");
            };
            callbacks.Error += @event =>
            {
                Debug.Log($"Got project subscription Error: {JsonConvert.SerializeObject(@event, Formatting.Indented)}");
            };
            return CloudCodeService.Instance.SubscribeToProjectMessagesAsync(callbacks);
        }
}
```

You should encounter a push message sent when the module runs in the Unity Editor:

```yaml
Got project subscription Message:
  {
    "data_base64": <BASE64-ENCODED-DATA>,
    "time": "2023-09-27T16:01:46.468321794Z",
    "message": "Happy new year!",
    "specversion": "1.0",
    "id": <ID>,
    "source": "https://cloud-code.service.api.unity.com",
    "type": "com.unity.services.cloud-code.push.v1",
    "projectid": <PROJECT-ID>,
    "environmentid": <ENVIRONMENT-ID>,
    "correlationid": <CORRELATION-ID>,
    "messagetype": "announcement",
  }
```
