Notifications
Overview
AccelByte Cloud's Notification service enables administrators or publishers to send text-based notifications to players. Notifications can be sent from service to service or from service to the client application. Notifications are sent using REST API and are relayed through a WebSocket connection, to ensure that they've been received in real-time. The main features of our Notification service are listed below.
Freeform and Template notification types allow you to control the content of your notifications. Freeform notifications can be used for ad-hoc cases where the publishers need to send a notification instantly to their players. Templated notifications include draft and localization features that are suitable for more planned use cases, such as game updates or promotional announcements.
Notification Topics can group notifications of similar types to keep them organized.
Permissions
Permissions are used to grant access to specific resources within our services. Make sure your account has the following permissions before you attempt to manage notification in the Admin Portal.
Usage | Resource | Action |
---|---|---|
Create a Notification Topic | ADMIN:NAMESPACE:{namespace}:NOTIFICATION | Create |
Send a Freeform Notification to a User | ADMIN:NAMESPACE:{namespace}:NOTIFICATION | Create |
Create a Notification Template | ADMIN:NAMESPACE:{namespace}:NOTIFICATION | Create |
Send a Templated Notification | ADMIN:NAMESPACE:{namespace}:NOTIFICATION | Create |
Permissions work slightly differently depending on whether they are assigned to IAM Clients or Roles assigned to users. For more information, read the Authentication and Authorization documentation.
Manage Notifications in the Admin Portal
The Admin Portal gives community managers and game admins an easy way to manage players' notifications.
Create a Notification Topic
To create or maintain notification topics in the Admin Portal, follow the steps below.
In the Game Management section of the Admin Portal, go to the Push Notifications section and click the Topics menu. Then click the New Topic button to add a new topic.
The Add New Topic form will appear. Fill in the required fields as seen below.
Topic. The new topic that you wanted to set
Description. The Description of the new topic that you're gonna create.
The newly created topic will be visible in the Notification Topics panel. You can view and edit the topic by clicking the Edit button or delete the topic by clicking the Delete button.
Send a Freeform Notification
By default, sending freeform notifications to individual players from the Admin Portal utilizes synchronous notification. This means that the targeted player must be online to retrieve the message. However, the broadcast feature does not require the player to be online as it sends the message to all players in a namespace, regardless of online status.
On the Template page of the Admin Portal, click the Send Freeform button.
In the Send Freeform window, select which type of user you are going to send the template to. If you select Single User, you need to input the target player's User ID. If you select All User, the notification will be delivered to all players in the selected namespace.
Type Choose Single User or All User for sending a freeform notification. If you choose a single user, you need to input a specific user id from the player.
Topic You can choose any topic if you want. Topic is the one that you created before from the topic panel. it depends on your game logic to handle the notification.
Notification Message What message that you want to send to the player. It can be a new update message, new event message, banned user, and other stuff that depends on what your game logic is.
Once completed, click the Send button to send the notification template or click the Cancel button to cancel the process.
Create a Notification Template
Template notifications utilize an asynchronous method to send a notification to either a single-player or to all players. To send a templated notification, create a template by following the steps below.
On the Templates page of the Admin Portal, click the New Template button.
Fill in the Add New Template form with the required fields.
Input the template's name in the Template field with the appropriate format.
Select the template's Language from the dropdown menu.
Input the Notification Message.
Click the Add button. The newly created template will appear on the Notification Templates page.
On the Templates page, you can choose your newly created template and click the View button to open the Template Localization page.
Here you can create a draft of the notification message before you publish it.
After you have created a template for your notification, you are ready to send templated notifications to players.
Send a Templated Notification
On the Template page of the Admin Portal, click the Send Template button.
In the Send Template window, select which type of player you are going to send the notification to. If you select Single User, you need to input the player's User ID. If you select All User, the notification will be delivered to all players in the selected namespace.
When you're done, click the Send button to send the notification or click the Cancel button to cancel the process.
Implement Notifications with the Client SDKs
Notifications can be retrieved either synchronously or asynchronously.
Retrieve Synchronous Notifications
To retrieve a synchronous notification using the SDK, you need to add the notification delegate.
- Unreal Engine
- Unity
const auto NotificationDelegate = AccelByte::Api::Lobby::FMessageNotif::CreateLambda([](const FAccelByteModelsNotificationMessage& Result)
{
UE_LOG(LogTemp, Log, TEXT("There is an incoming notification."));
UE_LOG(LogTemp, Log, TEXT("From: %s \nTo: %s\nTopic: %s"), *Result.From, *Result.To, *Result.Topic);
UE_LOG(LogTemp, Log, TEXT("Notification: %s"), *Result.Payload);
});
AccelByte::FRegistry::Lobby.SetMessageNotifDelegate(NotificationDelegate);
AccelByte::FRegistry::Lobby.Connect();
public static void OnReceiveNotification(Result<Notification> result)
{
Debug.Log(result.IsError);
Debug.Log(“There is an incoming notification.”);
Debug.Log(result.Value.payload);
}
public static void Main(string[] args)
{
var lobby = AccelBytePlugin.GetLobby();
lobby.OnNotification += OnReceiveNotification;
lobby.Connect();
}
You can also filter notifications by topic.
- Unreal Engine
- Unity
const auto NotificationDelegate = AccelByte::Api::Lobby::FMessageNotif::CreateLambda([](const FAccelByteModelsNotificationMessage& Result)
{
UE_LOG(LogTemp, Log, TEXT("There is an incoming notification."));
if(Result.Topic == “INGAME”)
{
UE_LOG(LogTemp, Log, TEXT("Game notification: %s"), *result.Payload);
}
Else if(Result.Topic == “EVENT”)
{
UE_LOG(LogTemp, Log, TEXT("Event notification: %s"), *result.Payload);
}
});
public static void OnReceiveNotification(Result<Notification> result)
{
Debug.Log(result.IsError);
Debug.Log(“There is an incoming notification.”);
switch(result.Value.topic){
case “INGAME” : Debug.Log(“Game notification: “ + result.Value.payload); break;
case “EVENT” : Debug.Log(“Event notification: “ + result.Value.payload); break;
}
}
Retrieve Asynchronous Notifications
To retrieve an asynchronous notification, just call the get asynchronous function and all stored notifications will be sent to your notification delegate.
- Unreal Engine
- Unity
AccelByte::FRegistry::Lobby.GetAllAsyncNotification();
lobby.PullAsyncNotifications(result =>
{
Debug.Log(result.IsError);
});
Connect Custom Services to Notifications using the Server SDKs
SDK Initialization
Before using the Cloud Notifications service from the SDK, you will need to initialize your server-side SDK to ensure you are authorized and able to perform create, read, update, and delete actions.
Golang SDK Initialization
Before using the Notifications service from the Golang SDK, you will need to initialize the SDK by following the steps below:
Create your OAuth Client and assign the necessary permissions to access the Notifications service.
Initialize the service using the following function:
- Golang
notificationService := &service.NotificationServiceWebsocket{
Client: &repository.ConfigRepositoryImpl{},
TokenRepository: &repository.TokenRepositoryImpl{},
ConnectionManager: &utils.ConnectionManagerImpl{},
}
Once completed, you can use the Golang SDK to create, read, update, and delete Notifications from your serverless app.
Python SDK Initialization
Before using the Notifications service from the Python SDK, you will need to initialize the SDK by following the steps below:
Create your OAuth Client and assign the necessary permissions to access the Notifications service.
Once completed, you can use the Python SDK to create, read, update, and delete Notifications from your serverless app.
.NET (C#) SDK Initialization
Use following .NET namespaces:
using AccelByte.Sdk.Api.Lobby;
using AccelByte.Sdk.Api.Lobby.WSModel;
The Lobby WebSocket service works slightly differently to other AccelByte services. Before using the Lobby WebSocket service, you will need to create a LobbyService object.
LobbyService lobby = new LobbyService(sdk.Configuration);
lobby.OnReceiveError = (eMessage) =>
{
is_error = true;
//handle if error occurs here
};
Once completed, you can connect and listen to the Lobby WebSocket service.
Task connectTask = lobby.Connect(false);
connectTask.Wait();
Task listenTask = Task.Run(() => lobby.Listen());
Java SDK Initialization
Before usin
WebSocket Setup
Some of the features in the Notifications service use WebSocket to enable the connection. Make sure you've set up WebSocket using our CLI. Once you've set up the CLI, you can use the GetNotificationMessage() wrapper to initialize the Notification service from the Lobby service.
Send a Freeform Notification
Use the following function to send a freeform notification:
- Golang
- Python
- C#
- Java
err := notificationService.FreeFormNotification(input)
if err != nil {
return err
}
return nil
from accelbyte_py_sdk.api.lobby import free_form_notification
from accelbyte_py_sdk.api.lobby.models import ModelFreeFormNotificationRequest
result, error = free_form_notification(
body=ModelFreeFormNotificationRequest.create(
message="<message>",
topic="<topic>",
)
)
if error:
print(error)
Notification wLobbyNotification = new Notification(sdk);
ModelFreeFormNotificationRequest notifBody = new ModelFreeFormNotificationRequest()
{
Topic = "csharpsdk_test",
Message = "This is integration test for CSharp Server SDK."
};
wLobbyNotification.FreeFormNotification(FreeFormNotification.Builder
.Build(notifBody, sdk.Namespace));
ModelFreeFormNotificationRequest notifBody = ModelFreeFormNotificationRequest.builder()
.topic(topic)
.message(message)
.build();
wLobbyNotification.freeFormNotification(FreeFormNotification.builder()
.namespace(namespace)
.body(notifBody)
.build());
Receive Parsed Web Socket Messages
Use the following function to receive a parsed websocket message from the server:
- Golang
- Python
- Java
//messageHandler is callback function how to handle incoming ws message
var messageHandler = func(dataByte []byte) {
message, err := parser.UnmarshalResponse(dataByte)
if err != nil {...}
// print all incoming message type
logrus.Infof("Message type: %v", message.Type())
marshal, err := json.Marshal(message)
if err != nil {...}
// print all incoming message content
logrus.Infof("Message content: %v", string(marshal))
// if you want to specify the message type and write logic for each of it
switch message.Type() {
case model.TypeNotificationMessage:
notificationMsg := message.(model.NotificationMessage)
logrus.Infof("Notification is coming from %s to %s", notificationMsg.From, notificationMsg.To)
case model.TypeKickResponse:
kickMessage := message.(model.KickResponse)
logrus.Infof("Message id is: %s", kickMessage.MessageID)
}
}
async def receive_and_send_formatted_web_socket_messages():
from accelbyte_py_sdk.core import get_access_token, get_base_url
from accelbyte_py_sdk.core import WebsocketsWSClient
base_url, error = get_base_url()
if error:
exit(1)
access_token, error = get_access_token()
if error:
exit(1)
client = WebsocketsWSClient(
uri=base_url,
access_token=access_token
)
# 1 Register a listener for received web socket messages.
client.listeners.append(on_receive)
await client.connect()
async def on_receive(message: str):
from accelbyte_py_sdk.api.lobby.wss_models import parse_wsm
# 2. Parse received web socket message.
result, error = parse_wsm(message)
if error:
print(error)
final String request_id = GenerateRandomId(64);
final CountDownLatch response = new CountDownLatch(1);
final Map<String,String> parsedResponseWSM = new HashMap<>();
WebSocketListener listener = new WebSocketListener() {
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
if (response.getCount() > 0) {
parsedResponseWSM .putAll(net.accelbyte.sdk.core.util.Helper.parseWSM(text));
response.countDown();
}
}
};
OkhttpWebSocketClient ws = OkhttpWebSocketClient.create(
new DefaultConfigRepository(),
DefaultTokenRepository.getInstance(),
listener);
String requestMessage = PartyCreateRequest.builder()
.id(requestId)
.build()
.toWSM();
ws.sendMessage(requestMessage);
response.await(10, TimeUnit.SECONDS);
Retrieve Offline Notifications using Web Socket
Use the following function to retrieve an offline notification:
- Golang
- Python
- Java
err := notificationService.GetNotificationMessage()
if err != nil {
return err
}
return nil
from accelbyte_py_sdk.core import get_access_token, get_base_url
from accelbyte_py_sdk.core import WebsocketsWSClient
# Full list of accepted web socket lobby messages are in 'accelbyte_py_sdk.api.lobby.wss_models'.
from accelbyte_py_sdk.api.lobby.wss_models import OfflineNotificationRequest
base_url, error = get_base_url()
if error:
exit(1)
access_token, error = get_access_token()
if error:
exit(1)
client = WebsocketsWSClient(
uri=base_url,
access_token=access_token
)
await client.connect()
# 1. Create an instance of the desired web socket message type.
offline_notification_request = OfflineNotificationRequest()
# 2. Format then send the web socket message.
# Can only be done after 'await client.connect()'.
await client.send(offline_notification_request.to_wsm())
final String request_id = GenerateRandomId(64);
final CountDownLatch response = new CountDownLatch(1);
final StringBuilder responseMessage = new StringBuilder();
WebSocketListener listener = new WebSocketListener() {
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
if (response.getCount() > 0) {
responseMessage.append(text);
response.countDown();
}
}
};
OkhttpWebSocketClient ws = OkhttpWebSocketClient.create(
new DefaultConfigRepository(),
DefaultTokenRepository.getInstance(),
listener);
String requestMessage = OfflineNotificationRequest.builder()
.id(requestId)
.build()
.toWSM();
ws.sendMessage(requestMessage);
response.await(10, TimeUnit.SECONDS);
Send a create party request message
Use the following function to send a party request message:
- C#
- Java
lobby.OnPartyCreateResponse = (PartyCreateResponse resp) =>
{
is_response_received = true;
//create party response
};
Task sendTask = lobby.SendPartyCreateRequest(new PartyCreateRequest()
{
Id = request_id
}, 0);
sendTask.Wait();
When you are finished, disconnect from the Lobby WebSocket service.
Task disconnectTask = lobby.Disconnect();
disconnectTask.Wait();
final String request_id = GenerateRandomId(64);
final CountDownLatch response = new CountDownLatch(1);
final StringBuilder responseMessage = new StringBuilder();
WebSocketListener listener = new WebSocketListener() {
@Override
public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
if (response.getCount() > 0) {
responseMessage.append(text);
response.countDown();
}
}
};
OkhttpWebSocketClient ws = OkhttpWebSocketClient.create(
new DefaultConfigRepository(),
DefaultTokenRepository.getInstance(),
listener);
String requestMessage = PartyCreateRequest.builder()
.id(requestId)
.build()
.toWSM();
ws.sendMessage(requestMessage);
response.await(10, TimeUnit.SECONDS);
Related Concepts
- See the API Reference to learn more about Notification services.
- Golang test case files
- Python test case files
- .NET (C#) test case files
- Java test case files