Function Reference #

The code runtime built into the server includes a module with functions to implement various logic and custom behavior, enabling you to define authoritative code and conditions on input received by clients. Learn more about it in the Server Framework Basics documentation.

This page lists all functions available within Nakama and their respective parameters, with corresponding code samples for each. If you haven’t already, see the documentation on using the server framework.

Writing custom SQL is discouraged in favor of using the built-in features of the Storage Engine. If custom SQL is needed for your use case, please contact Heroic Labs before proceeding.
The creation of custom tables is strongly discouraged.

Accounts #

AccountDeleteId #

Delete an account by user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDUser ID for the account to be deleted. Must be valid UUID.
recorded bool REQUIREDfalseWhether to record this deletion in the database.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
if err := nk.AccountDeleteId(ctx, "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592", false); err != nil {
    logger.WithField("err", err).Error("Delete account error.")
}

AccountExportId #

Export account information for a specified user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDUser ID for the account to be exported. Must be valid UUID.
Returns
NameDescription
export stringAccount information for the provided user ID, in JSON format.
error errorAn optional error value if an error occurred.
1
2
3
if err := nk.AccountExportId(ctx, "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"); err != nil {
    logger.WithField("err", err).Error("Export account error.")
}

AccountGetId #

Fetch account information by user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDUser ID to fetch information for. Must be valid UUID.
Returns
NameDescription
account *api.AccountAll account information including wallet, device IDs and more.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
account, err := nk.AccountGetId(ctx, "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592")
if err != nil {
    logger.WithField("err", err).Error("Get accounts error.")
    return
}
logger.Info("Wallet is: %v", account.Wallet)

AccountsGetId #

Fetch information for multiple accounts by user IDs.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userIds []string REQUIREDArray of user IDs to fetch information for. Must be valid UUID.
Returns
NameDescription
account []*api.AccountAn array of accounts.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
userIDs := []string{"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
accounts, err := nk.AccountsGetId(ctx, userIDs)
if err != nil {
    logger.WithField("err", err).Error("Get accounts error.")
    return
}

for _, account := range accounts {
    logger.Info("Wallet is: %v", account.Wallet)
}

AccountUpdateId #

Update an account by user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDUser ID for which the information is to be updated. Must be valid UUID.
metadata map[string]interface REQUIREDThe metadata to update for this account.
username string REQUIREDUsername to be set. Must be unique. Use "" if it is not being updated.
displayName string REQUIREDDisplay name to be updated. Use "" if it is not being updated.
timezone string REQUIREDTimezone to be updated. Use "" if it is not being updated.
location string REQUIREDLocation to be updated. Use "" if it is not being updated.
language string REQUIREDLang tag to be updated. Use "" if it is not being updated.
avatarUrl string REQUIREDUser's avatar URL. Use "" if it is not being updated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
userID := "4ec4f126-3f9d-11e7-84ef-b7c182b36521" // Some user ID.
username := ""
metadata := make(map[string]interface{})
displayName := ""
timezone := ""
location := ""
langTag := ""
avatarUrl := ""
if err := nk.AccountUpdateId(ctx, userID, username, metadata, displayName, timezone, location, langTag, avatarUrl); err != nil {
    logger.WithField("err", err).Error("Account update error.")
}

Authenticate #

AuthenticateApple #

Authenticate user and create a session token using an Apple sign in token.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
token string REQUIREDApple sign in token.
username string REQUIREDThe user's username. If left empty, one is generated.
create bool REQUIREDCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateApple(ctx, "some-oauth-access-token", "username", true)
if err != nil {
logger.WithField("err", err).Error("Authenticate apple error.")
}

AuthenticateCustom #

Authenticate user and create a session token using a custom authentication managed by an external service or source not already supported by Nakama.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDCustom ID to use to authenticate the user. Must be between 6-128 characters.
username stringThe user's username. If left empty, one is generated.
create bool REQUIREDCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateCustom(ctx, "48656C6C6F20776F726C64", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate custom error.")
}

AuthenticateDevice #

Authenticate user and create a session token using a device identifier.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDDevice ID to use to authenticate the user. Must be between 1-128 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateDevice(ctx, "48656C6C6F20776F726C64", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate device error.")
}

AuthenticateEmail #

Authenticate user and create a session token using an email address and password.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
email string REQUIREDEmail address to use to authenticate the user. Must be between 10-255 characters.
password string REQUIREDPassword to set. Must be longer than 8 characters.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateEmail(ctx, "email@example.com", "48656C6C6F20776F726C64", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate email error.")
}

AuthenticateFacebook #

Authenticate user and create a session token using a Facebook account token.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
token string REQUIREDFacebook OAuth or Limited Login (JWT) access token.
import bool REQUIREDWhether to automatically import Facebook friends after authentication.
username stringThe user's username. If left empty, one is generated.
create bool REQUIREDCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateFacebook(ctx, "some-oauth-access-token", true, "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate facebook error.")
}

AuthenticateFacebookInstantGame #

Authenticate user and create a session token using a Facebook Instant Game.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
playerInfo string REQUIREDFacebook Player info.
username stringThe user's username. If left empty, one is generated.
create bool REQUIREDCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateFacebookInstantGame(ctx, "player-info", true, "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate facebook error.")
}

AuthenticateGameCenter #

Authenticate user and create a session token using Apple Game Center credentials.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
playerId string REQUIREDPlayerId provided by GameCenter.
bundleId string REQUIREDBundleId of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
username stringThe user's username. If left empty, one is generated.
create bool REQUIREDCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateGameCenter(ctx, playerID, bundleID, timestamp, salt, signature, publicKeyUrl, username, create)
if err != nil {
    logger.WithField("err", err).Error("Authenticate game center error.")
}

AuthenticateGoogle #

Authenticate user and create a session token using a Google ID token.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
token string REQUIREDGoogle OAuth access token.
username string REQUIREDThe user's username. If left empty, one is generated.
create bool REQUIREDCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateGoogle(ctx, "some-id-token", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate google error.")
}

AuthenticateSteam #

Authenticate user and create a session token using a Steam account token.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
token string REQUIREDSteam token.
username stringThe user's username. If left empty, one is generated.
create booltrueCreate user if one didn't exist previously.
Returns
NameDescription
userID stringThe user ID of the authenticated user.
username stringThe username of the authenticated user.
create boolValue indicating if this account was just created or already existed.
error errorAn optional error value if an error occurred.
1
2
3
4
userid, username, created, err := nk.AuthenticateSteam(ctx, "steam-token", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Authenticate steam error.")
}

AuthenticateTokenGenerate #

Generate a Nakama session token from a user ID.

Parameters
NameDefaultDescription
userId string REQUIREDUser ID to use to generate the token.
username stringThe user's username. If left empty, one is generated.
expiresAt intUTC time in seconds when the token must expire. Defaults to server configured expiry time.
vars map[string]stringExtra information that will be bundled in the session token.
Returns
NameDescription
token stringThe Nakama session token.
validity int64The period for which the token remains valid.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
token, validity, err := nk.AuthenticateTokenGenerate("user_id", "username", 0)
if err != nil {
    logger.WithField("err", err).Error("Authenticate token generate error.")
    return
}
logger.Info("Session token: %q, valid for %v seconds", token, validity)

LinkApple #

Link Apple authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
token string REQUIREDApple sign in token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkApple(ctx, "some-oauth-access-token", "userId")
if err != nil {
	logger.WithField("err", err).Error("Link apple error.")
}

LinkCustom #

Link custom authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
customId string REQUIREDCustom ID to be linked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkCustom(ctx, "48656C6C6F20776F726C64","customId")
if err != nil {
    logger.WithField("err", err).Error("Link custom error.")
}

LinkDevice #

Link device authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
deviceId string REQUIREDDevice ID to be linked to the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkDevice(ctx, "48656C6C6F20776F726C64", "deviceId")
if err != nil {
    logger.WithField("err", err).Error("Link device error.")
}

LinkEmail #

Link email authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
email string REQUIREDAuthentication email to be linked to the user.
password string REQUIREDPassword to set. Must be longer than 8 characters.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkEmail(ctx, "userId", "email@example.com", "password", )
if err != nil {
    logger.WithField("err", err).Error("Link email error.")
}

LinkFacebook #

Link Facebook authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
username stringIf left empty, one is generated.
token string REQUIREDFacebook OAuth or Limited Login (JWT) access token.
importFriends bool REQUIREDWhether to automatically import Facebook friends after authentication.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkFacebook(ctx, "userId", "some-oauth-access-token", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Link facebook error.")
}

LinkFacebookInstantGame #

Link Facebook Instant Game authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
signedPlayerInfo string REQUIREDFacebook player info.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkFacebookInstantGame(ctx, "player-info", "userId")
if err != nil {
    logger.WithField("err", err).Error("Link facebook error.")
}

LinkGameCenter #

Link Apple Game Center authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
playerId string REQUIREDPlayer ID provided by Game Center.
bundleId string REQUIREDBundle ID of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkGameCenter(ctx, userID, playerID, bundleID, timestamp, salt, signature, publicKeyUrl)
if err != nil {
    logger.WithField("err", err).Error("Link game center error.")
}

LinkGoogle #

Link Google authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
token string REQUIREDGoogle OAuth access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkGoogle(ctx, "userId", "some-id-token")
if err != nil {
    logger.WithField("err", err).Error("Link google error.")
}

LinkSteam #

Link Steam authentication to a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be linked.
username stringIf left empty, one is generated.
token string REQUIREDSteam access token.
importFriends bool REQUIREDWhether to automatically import Steam friends after authentication.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.LinkSteam(ctx, "userId", "steam-token", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Link steam error.")
}

UnlinkApple #

Unlink Apple authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDApple sign in token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkApple(ctx, "some-oauth-access-token", "userId")
if err != nil {
logger.WithField("err", err).Error("Unlink apple error.")
}

UnlinkCustom #

Unlink custom authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
customId string REQUIREDCustom ID to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkCustom(ctx, "48656C6C6F20776F726C64","customId")
if err != nil {
    logger.WithField("err", err).Error("Unlink custom error.")
}

UnlinkDevice #

Unlink device authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
deviceId string REQUIREDDevice ID to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkDevice(ctx, "48656C6C6F20776F726C64", "deviceId")
if err != nil {
    logger.WithField("err", err).Error("Unlink device error.")
}

UnlinkEmail #

Unlink email authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
email string REQUIREDEmail to be unlinked from the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkEmail(ctx, "userId", "email@example.com", "password", )
if err != nil {
    logger.WithField("err", err).Error("Unlink email error.")
}

UnlinkFacebook #

Unlink Facebook authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDFacebook OAuth or Limited Login (JWT) access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkFacebook(ctx, "userId", "some-oauth-access-token", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Unlink facebook error.")
}

UnlinkFacebookInstantGame #

Unlink Facebook Instant Game authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
playerInfo string REQUIREDFacebook player info.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkFacebookInstantGame(ctx, "player-info", "userId")
if err != nil {
    logger.WithField("err", err).Error("Unlink facebook error.")
}

UnlinkGameCenter #

Unlink Apple Game Center authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
playerId string REQUIREDPlayer ID provided by Game Center.
bundleId string REQUIREDBundle ID of your app on iTunesConnect.
timestamp int REQUIREDTimestamp at which Game Center authenticated the client and issued a signature.
salt string REQUIREDA random string returned by Game Center authentication on client.
signature string REQUIREDA signature returned by Game Center authentication on client.
publicKeyUrl string REQUIREDA URL to the public key returned by Game Center authentication on client.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkGameCenter(ctx, userID, playerID, bundleID, timestamp, salt, signature, publicKeyUrl)
if err != nil {
    logger.WithField("err", err).Error("Unlink game center error.")
}

UnlinkGoogle #

Unlink Google authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDGoogle OAuth access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkGoogle(ctx, "userId", "some-id-token")
if err != nil {
    logger.WithField("err", err).Error("Unlink google error.")
}

UnlinkSteam #

Unlink Steam authentication from a user ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be unlinked.
token string REQUIREDSteam access token.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.UnlinkSteam(ctx, "userId", "steam-token", "username", true)
if err != nil {
    logger.WithField("err", err).Error("Unlink steam error.")
}

Chat #

ChannelIdBuild #

Create a channel identifier to be used in other runtime calls. Does not create a channel.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
senderId string REQUIREDUserID of the message sender (when applicable). An empty string defaults to the system user.
target string REQUIREDCan be the room name, group identifier, or another username.
chanType runtime.ChannelType REQUIREDThe type of channel, either Room (1), Direct (2), or Group (3).
Returns
NameDescription
channelId stringThe generated ID representing a channel.
error errorAn optional error value if an error occurred.
1
2
3
4
channelId, err := nk.ChannelIdBuild(ctx, "senderId", "roomname", 1)
if err != nil {
	logger.WithField("err", err).Error("Channel build error.")
}

ChannelMessageRemove #

Remove a message on a realtime chat channel.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
channelId string REQUIREDThe ID of the channel to remove the message on.
messageId string REQUIREDThe ID of the message to remove.
senderId stringThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername stringThe username of the user who sent this message. If left empty, it will be assumed that it is a system message.
persist bool REQUIREDWhether to record this in the channel history.
Returns
NameDescription
channelMessageRemove *rtapi.ChannelMessageAckMessage removed ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'.
error errorAn optional error value if an error occurred.

ChannelMessageSend #

Send a message on a realtime chat channel.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
channelId string REQUIREDThe ID of the channel to send the message on.
content map[string]interface REQUIREDMessage content.
senderId stringThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername stringThe username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persist bool REQUIREDWhether to record this message in the channel history.
Returns
NameDescription
channelMessageSend *rtapi.ChannelMessageAckMessage sent ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
channelID := "<ChannelId>"
content := map[string]interface{}{
	"message": "Hello",
}
senderID := "<SenderId>"
senderUsername := "<SenderUsername>"
persist := true
ack, err := nk.ChannelMessageSend(ctx, channelID, content, senderID, senderUsername, persist)
if err != nil {
	logger.Debug("%v created at %v", ack.MessageId, ack.CreateTime)
	return err
}

ChannelMessagesList #

List messages from a realtime chat channel.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
channelId string REQUIREDThe ID of the channel to list messages from.
limit int REQUIREDThe number of messages to return per page.
forward bool REQUIREDWhether to list messages from oldest to newest, or newest to oldest.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
channelMessageList []*rtapi.ChannelMessageMessages from the specified channel.
nextCursor stringCursor for the next page of messages, if any.
prevCursor stringCursor for the previous page of messages, if any.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
channelID := "<ChannelId>"
limit := 100
forward := true

list, err := nk.ChannelMessagesList(ctx, channelID, limit, forward)
if err != nil {
	logger.WithField("err", err).Error("Channel message list error.")
}
for _, m := range list.Messages {
	logger.info("Message: %+v", v)
}

ChannelMessageUpdate #

Update a message on a realtime chat channel.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
channelId string REQUIREDThe ID of the channel to send the message on.
messageId string REQUIREDThe ID of the message to update.
content map[string]interface REQUIREDMessage content.
senderId stringThe UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsername stringThe username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persist bool REQUIREDWhether to record this message in the channel history.
Returns
NameDescription
channelMessageUpdate *rtapi.ChannelMessageAckMessage updated ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
channelID := "<ChannelId>"
messageID := "<MessageId>"
content := map[string]interface{}{
	"message": "Hello",
}
senderID := "<SenderId>"
senderUsername := "<SenderUsername>"
persist := true
ack, err := nk.ChannelMessageUpdate(ctx, channelID, messageID, content, senderID, senderUsername, persist)
if err != nil {
	logger.Debug("%v updated at %v", ack.MessageId, ack.UpdateTime)
	return err
}

Events #

Event #

Generate an event.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
evt *api.Event REQUIREDThe event to be generated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
evt := &api.Event{
    Name:       "event_name"
    Properties: map[string]string{
        "my_key": "my_value",
    },
    External:   true,
}
if err := nk.Event(ctx, evt); err != nil {
    // Handle error.
}

Friends #

FriendsAdd #

Add friends to a user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user to whom you want to add friends.
username string REQUIREDThe name of the user to whom you want to add friends.
ids []string REQUIREDThe IDs of the users you want to add as friends.
usernames []string REQUIREDThe usernames of the users you want to add as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
username := "username"
userIDs := [] string {
  "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}
usernames := [] string {
  "newfriend1",
  "newfriend2"
}

friends, err := nk.FriendsAdd(ctx, userID, username, userIDs, usernames)
if err != nil {
  logger.WithField("err", err).Error("nk.FriendsAdd error.")
  return
}

FriendsBlock #

Block friends for a user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user for whom you want to block friends.
username string REQUIREDThe name of the user for whom you want to block friends.
ids []string REQUIREDThe IDs of the users you want to block as friends.
usernames []string REQUIREDThe usernames of the users you want to block as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
username := "username"
userIDs := [] string {
  "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}
usernames := [] string {
  "exfriend1",
  "exfriend2"
}

friends, err := nk.FriendsBlock(ctx, userID, username, userIDs, usernames)
if err != nil {
  logger.WithField("err", err).Error("nk.FriendsBlock error.")
  return
}

FriendsDelete #

Delete friends from a user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user from whom you want to delete friends.
username string REQUIREDThe name of the user from whom you want to delete friends.
ids []string REQUIREDThe IDs of the users you want to delete as friends.
usernames []string REQUIREDThe usernames of the users you want to delete as friends.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
username := "username"
userIDs := [] string {
  "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}
usernames := [] string {
  "exfriend1",
  "exfriend2"
}

friends, err := nk.FriendsDelete(ctx, userID, username, userIDs, usernames)
if err != nil {
  logger.WithField("err", err).Error("nk.FriendsDelete error.")
  return
}

FriendsList #

List all friends, invites, invited, and blocked which belong to a user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user whose friends, invites, invited, and blocked you want to list.
limit int REQUIREDThe number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
state intThe state of the friendship with the user. If unspecified this returns friends in all states for the user.
cursor string REQUIREDPagination cursor from previous result. Set to "" to start fetching from the beginning.
Returns
NameDescription
friends []*api.FriendThe user information for users that are friends of the current user.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
limit := 100
state := 0
cursor := ""

friends, err := nk.FriendsList(ctx, userID, limit, &state, cursor)
if err != nil {
  logger.WithField("err", err).Error("nk.FriendsList error.")
  return
}

for _, friend := range friends {
    // States are: friend(0), invite_sent(1), invite_received(2), blocked(3)
    logger.Info("Friend username %s has state %d", friend.GetUser().Username, friend.GetState())
}

FriendsOfFriendsList #

List friends of friends.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user whose friends of friends you want to list.
limit int REQUIREDThe number of friends of friends to retrieve in this page of results. No more than 100 limit allowed per result.
cursor string REQUIREDPagination cursor from previous result. Set to "" to start fetching from the beginning.
Returns
NameDescription
friends []*api.FriendThe user information for users that are friends of friends the current user.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
limit := 20
cursor := ""

friends, err := nk.FriendsOfFriendsList(ctx, userID, limit, cursor)
if err != nil {
  logger.WithField("err", err).Error("nk.FriendsOfFriendsList error.")
  return
}

Groups #

GroupCreate #

Setup a group with various configuration settings. The group will be created if they don't exist or fail if the group name is taken.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID to be associated as the group superadmin.
name string REQUIREDGroup name, must be unique.
creatorId stringThe user ID to be associated as creator. If not set or nil/null, system user will be set.
langTag stringGroup language.
description stringGroup description, can be left empty as nil/null.
avatarUrl stringURL to the group avatar, can be left empty as nil/null.
open boolfalseWhether the group is for anyone to join, or members will need to send invitations to join.
metadata map[string]interfaceCustom information to store for this group. Can be left empty as nil/null.
maxCount int REQUIRED100Maximum number of members to have in the group.
Returns
NameDescription
createGroup *api.GroupThe groupId of the newly created group.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
metadata:= map[string] interface {} {
    "my_custom_field": "some value",
}

userID:= "dcb891ea-a311-4681-9213-6741351c9994"
creatorID:= "dcb891ea-a311-4681-9213-6741351c9994"
name:= "Some unique group name"
description:= "My awesome group."
langTag:= "en"
open:= true
avatarURL:= "url://somelink"
maxCount:= 100

group, err:= nk.GroupCreate(ctx, userID, name, creatorID, langTag, description, avatarURL, open, metadata, maxCount)
if err != nil {
    logger.WithField("err", err).Error("Group create error.")
}

GroupDelete #

Delete a group.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
groupId string REQUIREDThe ID of the group to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
groupID:= "f00fa79a-750f-11e7-8626-0fb79f45ff97"
if group, err:= nk.GroupDelete(ctx, groupID);
err != nil {
    logger.WithField("err", err).Error("Group delete error.")
}

GroupsGetId #

Fetch one or more groups by their ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
groupIds []string REQUIREDAn array of strings of the IDs for the groups to get.
Returns
NameDescription
getGroups []*api.GroupAn array of groups with their fields.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"

groups, err:= nk.GroupsGetId(ctx, [] string {
    groupID
})
if err != nil {
    logger.WithField("err", err).Error("Groups get by ID error.")
    return
}

GroupsGetRandom #

Fetch one or more groups randomly.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
count int REQUIREDThe number of groups to fetch.
Returns
NameDescription
users []*api.GroupA list of group record objects.
error errorAn optional error value if an error occurred.

GroupsList #

Find groups based on the entered criteria.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
name stringSearch for groups that contain this value in their name. Cannot be combined with any other filter.
langTag stringFilter based upon the entered language tag.
members intSearch by number of group members.
open boolFilter based on whether groups are Open or Closed.
limit intReturn only the required number of groups denoted by this limit value.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
groups []*api.GroupA list of groups.
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
groupName := "Heroic"
langTag := "en"
members := 10
open := true
limit := 100
cursor := ""

list, cursor, err := nk.GroupsList(ctx, groupName, langTag, &members, &open, limit, cursor)

if err != nil {
    logger.WithField("err", err).Error("Group list error.")
} else {
    for _, g:= range list {
        logger.Info("ID %s - open? %b cursor: %s", g.Id, g.Open, cursor)
    }
}

GroupUpdate #

Update a group with various configuration settings. The group which is updated can change some or all of its fields.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
groupId string REQUIREDThe ID of the group to update.
userId string REQUIREDUser ID calling the update operation for permission checking. Set as empty string to enact the changes as the system user.
name string REQUIREDGroup name, can be empty if not changed.
creatorId string REQUIREDThe user ID to be associated as creator. Can be empty if not changed.
langTag string REQUIREDGroup language. Empty if not updated.
description string REQUIREDGroup description, can be left empty if not updated.
avatarUrl string REQUIREDURL to the group avatar, can be left empty if not updated.
open bool REQUIREDWhether the group is for anyone to join or not.
metadata map[string]interface REQUIREDCustom information to store for this group. Use nil if field is not being updated.
maxCount int REQUIREDMaximum number of members to have in the group. Use 0, nil/null if field is not being updated.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
metadata:= map[string] interface {} { // Add whatever custom fields you want.
    "my_custom_field": "some value",
}

groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
description:= "An updated description."

if err:= nk.GroupUpdate(ctx, groupID, nil, "", "", "", description, "", true, metadata, 0);
err != nil {
    logger.WithField("err", err).Error("Group update error.")
}

GroupUserJoin #

Join a group for a particular user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
groupId string REQUIREDThe ID of the group to join.
userId string REQUIREDThe user ID to add to this group.
username string REQUIREDThe username of the user to add to this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userID:= "9a51cf3a-2377-11eb-b713-e7d403afe081"
username:= "myusername"

if err:= nk.GroupUserJoin(ctx, groupID, userID, username);
err != nil {
    logger.WithField("err", err).Error("Group user join error.")
}

GroupUserLeave #

Leave a group for a particular user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
groupId string REQUIREDThe ID of the group to leave.
userId string REQUIREDThe user ID to remove from this group.
username string REQUIREDThe username of the user to remove from this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userID:= "9a51cf3a-2377-11eb-b713-e7d403afe081"
username:= "myusername"

if err:= nk.GroupUserLeave(ctx, groupID, userID, username);
err != nil {
    logger.WithField("err", err).Error("Group user leave error.")
}

GroupUsersAdd #

Add users to a group.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
groupId string REQUIREDThe ID of the group to add users to.
userIds []string REQUIREDTable array of user IDs to add to this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userIDs:= [] string {
    "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}

if err:= nk.GroupUsersAdd(ctx, groupID, userIDs);
err != nil {
    logger.WithField("err", err).Error("Group users add error.")
}

GroupUsersBan #

Ban users from a group.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
groupId string REQUIREDThe ID of the group to ban users from.
userIds []string REQUIREDTable array of user IDs to ban from this group.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userIDs:= [] string {
    "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}

if err:= nk.GroupUsersBan(ctx, groupID, userIDs);
err != nil {
    logger.WithField("err", err).Error("Group users ban error.")
}

GroupUsersDemote #

Demote users in a group.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
groupId string REQUIREDThe ID of the group whose members are being demoted.
userIds []string REQUIREDTable array of user IDs to demote.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userIds:= [] string {
    "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}

if err:= nk.GroupUsersDemote(ctx, groupID, userIDs);
err != nil {
    logger.WithField("err", err).Error("Group users demote error.")
}

GroupUsersKick #

Kick users from a group.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
groupId string REQUIREDThe ID of the group to kick users from.
userIds []string REQUIREDTable array of user IDs to kick.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userIds:= [] string {
    "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}

if err:= nk.GroupUsersKick(ctx, groupID, userIds);
err != nil {
    logger.WithField("err", err).Error("Group users kick error.")
}

GroupUsersList #

List all members, admins and superadmins which belong to a group. This also lists incoming join requests.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
groupId string REQUIREDThe ID of the group to list members for.
limit int REQUIREDReturn only the required number of users denoted by this limit value.
state int REQUIREDReturn only the users matching this state value, '0' for superadmins for example.
cursor string REQUIREDPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"

groupUserList, err:= nk.GroupUsersList(ctx, groupID)
if err != nil {
    logger.WithField("err", err).Error("Group users list error.")
    return
}

for _, member:= range groupUserList {
    // States are => 0: Superadmin, 1: Admin, 2: Member, 3: Requested to join
    logger.Info("Member username %s has state %d", member.GetUser().Username, member.GetState())
}

GroupUsersPromote #

Promote users in a group.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
groupId string REQUIREDThe ID of the group whose members are being promoted.
userIds []string REQUIREDTable array of user IDs to promote.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:= "dcb891ea-a311-4681-9213-6741351c9994"
userIDs:= [] string {
    "9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"
}

if err:= nk.GroupUsersPromote(ctx, groupID, userIDs);
err != nil {
    logger.WithField("err", err).Error("Group users promote error.")
}

UserGroupsList #

List all groups which a user belongs to and whether they've been accepted or if it's an invite.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user to list groups for.
limit int REQUIREDThe maximum number of entries in the listing.
state intThe state of the user within the group. If unspecified this returns users in all states.
cursor string REQUIREDPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
cursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any). Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
userID:= "dcb891ea-a311-4681-9213-6741351c9994"

groups, err:= nk.UserGroupsList(ctx, userID)
if err != nil {
    logger.WithField("err", err).Error("User groups list error.")
    return
}

for _, group:= range groups {
    logger.Printf("User has state %d in group %s.", group.GetState(), group.GetGroup().Name)
}

Leaderboards #

LeaderboardCreate #

Setup a new dynamic leaderboard with the specified ID and various configuration settings. The leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
leaderboardID string REQUIREDThe unique identifier for the new leaderboard. This is used by clients to submit scores.
authoritative bool REQUIREDfalseMark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly.
sortOrder string REQUIREDThe sort order for records in the leaderboard. Possible values are "asc" or "desc".
operator string REQUIREDThe operator that determines how scores behave when submitted. Possible values are "best", "set", or "incr".
resetSchedule string REQUIREDThe cron format used to define the reset schedule for the leaderboard. This controls when a leaderboard is reset and can be used to power daily/weekly/monthly leaderboards.
metadata map[string]interface REQUIREDThe metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game.
enableRanks bool REQUIREDWhether to enable rank values for the leaderboard.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
authoritative := false
sortOrder := "desc"
operator := "best"
resetSchedule := "0 0 * * 1"
metadata := map[string]interface{}{
	"weather_conditions": "rain",
}
enableRanks = false // Set to true to enable rank computation on leaderboard records.

if err := nk.LeaderboardCreate(ctx, id, authoritative, sortOrder, operator, resetSchedule, metadata, enableRanks); err != nil {
	logger.WithField("err", err).Error("Leaderboard create error.")
}

LeaderboardDelete #

Delete a leaderboard and all scores that belong to it.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the leaderboard to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
if err := nk.LeaderboardDelete(ctx, id); err != nil {
	logger.WithField("err", err).Error("Leaderboard delete error.")
}

LeaderboardList #

Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.

Parameters
NameDefaultDescription
limit int REQUIREDReturn only the required number of leaderboards denoted by this limit value.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
leaderboardList *api.LeaderboardListA list of leaderboard results and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
limit := 100 // Number to list per page.
cursor := ""
list, err := nk.LeaderboardList(ctx, limit, cursor)
if err != nil {
	logger.WithField("err", err).Error("Leaderboard list error.")
} else {
	for _, l := range list.Leaderboards {
		logger.Info("ID %s - can enter? %b", l.Id, l.CanEnter)
	}
}

LeaderboardRanksDisable #

Disable a leaderboard rank cache freeing its allocated resources. If already disabled is a NOOP.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe leaderboard id.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
err := nk.LeaderboardRanksDisable(ctx, id)
if err != nil {
	logger.WithField("err", err).Error("Leaderboard ranks disable error.")
}

LeaderboardRecordDelete #

Remove an owner's record from a leaderboard, if one exists.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the leaderboard to delete from.
owner string REQUIREDThe owner of the score to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "4c2ae592-b2a7-445e-98ec-697694478b1c"

if err := nk.LeaderboardRecordDelete(ctx, id, ownerID); err != nil {
	logger.WithField("err", err).Error("Leaderboard record delete error.")
}

LeaderboardRecordsHaystack #

Fetch the list of leaderboard records around the owner.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe ID of the leaderboard to list records for.
ownerId string REQUIREDThe owner ID around which to show records.
limit int REQUIREDReturn only the required number of leaderboard records denoted by this limit value. Between 1-100.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
expiry int REQUIREDTime since epoch in seconds. Must be greater than 0.
Returns
NameDescription
leaderboardRecordsHaystack *api.LeaderboardRecordListA list of leaderboard records and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "4c2ae592-b2a7-445e-98ec-697694478b1c"
limit := 10
expiry := 3600
records, err := nk.LeaderboardRecordsHaystack(ctx, id, ownerID, limit, expiry)
if err != nil {
	logger.WithField("err", err).Error("Leaderboard record haystack error.")
} else {
	for _, r := range records {
		logger.Info("Leaderboard: %s, score: %d, subscore: %d", r.GetLeaderboardId(), r.Score, r.Subscore)
	}
}

LeaderboardRecordsList #

List records on the specified leaderboard, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured leaderboard sort order.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the leaderboard to list.
owners []string REQUIREDArray of owners to filter to.
limit int REQUIREDThe maximum number of records to return (Max 10,000).
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiry int REQUIREDRecords with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
NameDescription
records []*api.LeaderboardRecordA page of leaderboard records.
ownerRecords []*api.LeaderboardRecordA list of owner leaderboard records (empty if the owners input parameter is not set).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerIDs := []string{}
limit := 10
cursor := ""
expiry := int64(0)

records, ownerRecords, prevCursor, nextCursor, err := nk.LeaderboardRecordsList(ctx, id, ownerIDs, limit, cursor, expiry)
if err != nil {
	logger.WithField("err", err).Error("Leaderboard record list error.")
}

LeaderboardRecordsListCursorFromRank #

Build a cursor to be used with leaderboardRecordsList to fetch records starting at a given rank. Only available if rank cache is not disabled for the leaderboard.

Parameters
NameDefaultDescription
leaderboardID string REQUIREDThe unique identifier of the leaderboard.
rank int REQUIREDThe rank to start listing leaderboard records from.
overrideExpiry int REQUIREDRecords with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
NameDescription
leaderboardListCursor stringA string cursor to be used with leaderboardRecordsList.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
rank := int64(1)
expiry := int64(0)
cursor, err := nk.LeaderboardRecordsListCursorFromRank(ctx, id, rank, expiry)
if err != nil {
	logger.WithField("err", err).Error("Leaderboard record list cursor from rank error.")
}

LeaderboardRecordWrite #

Use the preconfigured operator for the given leaderboard to submit a score for a particular user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the leaderboard to submit to.
owner string REQUIREDThe owner of this score submission.
username string REQUIREDThe owner username of this score submission, if it's a user.
score int REQUIREDThe score to submit.
subscore intA secondary subscore parameter for the submission.
metadata map[string]interfaceThe metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
overrideOperator *int REQUIREDAn override operator for the new record. The accepted values include: 0 (no override), 1 (best), 2 (set), 3 (incr), 4 (decr). Passing nil is the same as passing a pointer to 0 (no override), which uses the default leaderboard operator.
Returns
NameDescription
record *api.LeaderboardRecordThe newly created leaderboard record.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "4c2ae592-b2a7-445e-98ec-697694478b1c"
username := "02ebb2c8"
score := int64(10)
subscore := int64(0)
metadata := map[string]interface{}{
	"weather_conditions": "rain",
}
overrideOperator := new(int) // Optional operator to override the one set in the leaderboard. nil or 0 means no override

if record, err := nk.LeaderboardRecordWrite(ctx, id, ownerID, username, score, subscore, metadata, overrideOperator); err != nil {
	logger.WithField("err", err).Error("Leaderboard record write error.")
}

LeaderboardsGetId #

Fetch one or more leaderboards by ID.

Parameters
NameDefaultDescription
ids []string REQUIREDThe table array of leaderboard ids.
Returns
NameDescription
leaderboardsGet []*api.LeaderboardThe leaderboard records according to ID.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
leaderboardIDs := []string{
	"3ea5608a-43c3-11e7-90f9-7b9397165f34",
	"447524be-43c3-11e7-af09-3f7172f05936",
}
leaderboards, err := nk.LeaderboardsGetId(ctx, leaderboardIDs)
if err != nil {
	logger.WithField("err", err).Error("Leaderboards get error.")
}

Matches #

MatchCreate #

Create a new authoritative realtime multiplayer match running on the given runtime module name. The given params are passed to the match's init hook.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
module string REQUIREDThe name of an available runtime module that will be responsible for the match. This was registered in InitModule.
params map[string]interface REQUIREDAny value to pass to the match init hook.
Returns
NameDescription
matchId stringThe match ID of the newly created match. Clients can immediately use this ID to join the match.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Assumes you've registered a match with initializer.RegisterMatch("some.folder.module", ...)
modulename:= "some.folder.module"
params:= map[string] interface {} {
    "some": "data",
}

matchID, err:= nk.MatchCreate(ctx, modulename, params)
if err != nil {
    return "", err
}

MatchGet #

Get information on a running match.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe ID of the match to fetch.
Returns
NameDescription
match *api.MatchInformation for the running match.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
matchId:= "52f02f3e-5b48-11eb-b182-0f5058adfcc6"

match, err:= nk.MatchGet(ctx, matchId)
if err != nil {
    return "", err
}

MatchList #

List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
limit int100The maximum number of matches to list.
authoritative boolfalseSet true to only return authoritative matches, false to only return relayed matches.
label string REQUIREDA label to filter authoritative matches by. Default "" means any label matches.
minSize int REQUIREDInclusive lower limit of current match participants.
maxSize int REQUIREDInclusive upper limit of current match participants.
query string REQUIREDAdditional query parameters to shortlist matches.
Returns
NameDescription
match []*api.MatchA list of matches matching the parameters criteria.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// List at most 10 matches, not authoritative, and that
// have between 2 and 4 players currently participating.
limit:= 10
isAuthoritative:= false
label:= ""
minSize:= 2
maxSize:= 4

matches, err:= nk.MatchList(ctx, limit, isAuthoritative, label, minSize, maxSize, "")
if err != nil {
    logger.WithField("err", err).Error("Match list error.")
} else {
    for _, match:= range matches {
        logger.Info("Found match with id: %s", match.GetMatchId())
    }
}

MatchSignal #

Allow the match handler to be sent a reservation signal to mark a user ID or session ID into the match state ahead of their join attempt and eventual join flow. Called when the match handler receives a runtime signal.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDContext object represents information about the match and server for information purposes.
id string REQUIREDThe user ID or session ID to send a reservation signal for.
data string REQUIREDAn arbitrary input supplied by the runtime caller of the signal.
Returns
NameDescription
data stringArbitrary data to return to the runtime caller of the signal. May be a string or nil.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
matchId := "52f02f3e-5b48-11eb-b182-0f5058adfcc6"
data := "<Data>"
result, err := nk.MatchSignal(ctx, matchId, data)

if err != nil {
    logger.WithField("err", err).Error("Match signal error.")
} else {
    logger.Info("Match signal result: %s", result)
}

Metrics #

MetricsCounterAdd #

Add a custom metrics counter.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics counter.
tags map[string]string REQUIREDThe metrics tags associated with this counter.
delta int REQUIREDValue to update this metric with.
Returns
NameDescription
1
2
3
4
5
name := "metricName"
tags := make map([string]string) // Metrics tags for this counter.
delta := 100

nk.MetricsCounterAdd(name, tags, delta)

MetricsGaugeSet #

Add a custom metrics gauge.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics gauge.
tags map[string]string REQUIREDThe metrics tags associated with this gauge.
value float REQUIREDValue to update this metric with.
Returns
NameDescription
1
2
3
4
5
name := "metricName"
tags := make map([string]string) // Metrics tags for this gauge.
value := 3.14

nk.MetricsGaugeSet(name, tags, value)

MetricsTimerRecord #

Add a custom metrics timer.

Parameters
NameDefaultDescription
name string REQUIREDThe name of the custom metrics timer.
tags map[string]string REQUIREDThe metrics tags associated with this timer.
value time.Duration REQUIREDValue to update this metric with.
Returns
NameDescription
1
2
3
4
5
name := "metricName"
tags := make map([string]string) // Metrics tags for this gauge.
value := 100000000000

nk.MetricsTimerRecord(name, tags, value)

Notifications #

NotificationsDelete #

Delete one or more in-app notifications.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
notifications []*runtime.NotificationDelete REQUIREDA list of notifications to be deleted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
notificationID := "a042c19c-2377-11eb-b7c1-cfafae11cfbc"

notifications := {
    {userID = userID, notificationID =  notificationID}
}

err := nk.NotificationsDelete(ctx, notifications)
if err != nil {
  logger.WithField("err", err).Error("nk.NotificationsDelete error.")
  return
}

NotificationsDeleteId #

Delete notifications by their id.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userID string REQUIREDOptional userID to scope deletions to that user only. Use empty string to ignore.
ids []string REQUIREDA list of notification ids.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
notificationID := "a042c19c-2377-11eb-b7c1-cfafae11cfbc"

notificationIDs := []string{notificationID}

err := nk.NotificationsDeleteId(ctx, userID, notificationIDs)
if err != nil {
  logger.WithField("err", err).Error("nk.NotificationsDeleteId error.")
  return
}

NotificationSend #

Send one in-app notification to a user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the user to be sent the notification.
subject string REQUIREDNotification subject.
content map[string]interface REQUIREDNotification content. Must be set but can be an struct.
code int REQUIREDNotification code to use. Must be equal or greater than 0.
sender stringThe sender of this notification. If left empty, it will be assumed that it is a system notification.
persistent bool REQUIREDfalseWhether to record this in the database for later listing.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
subject:= "You've unlocked level 100!"
content:= map[string] interface {} {
    "reward_coins": 1000,
}
receiverID:= "4c2ae592-b2a7-445e-98ec-697694478b1c"
senderID:= "dcb891ea-a311-4681-9213-6741351c9994"
code:= 101
persistent:= true

nk.NotificationSend(ctx, receiverID, subject, content, code, senderID, persistent)

NotificationSendAll #

Send an in-app notification to all users.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
subject string REQUIREDNotification subject.
content map[string]interface REQUIREDNotification content. Must be set but can be any empty map.
code int REQUIREDNotification code to use. Must be greater than or equal to 0.
persistent bool REQUIREDWhether to record this in the database for later listing.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
subject:= "You've unlocked level 100!"
content:= map[string] interface {} {
    "reward_coins": 1000,
}
code:= 101
persistent:= true

nk.NotificationSendAll(ctx, subject, content, code, persistent)

NotificationsGetId #

Get notifications by their id.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userID string REQUIREDOptional userID to scope results to that user only.
ids []string REQUIREDA list of notification ids.
Returns
NameDescription
notifications []*api.NotificationA list of notifications.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
notificationID := "a042c19c-2377-11eb-b7c1-cfafae11cfbc"

notificationIDs := []string{notificationID}

notifications, err := nk.NotificationsGetId(ctx, userID, notificationIDs)
if err != nil {
  logger.WithField("err", err).Error("nk.NotificationsGetId error.")
  return
}

NotificationsSend #

Send one or more in-app notifications to a user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
notifications []*runtime.NotificationSend REQUIREDA list of notifications to be sent together.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
notifications:= [] * runtime.NotificationSend { & runtime.NotificationSend {
    UserID: "4c2ae592-b2a7-445e-98ec-697694478b1c",
    Subject: "You've unlocked level 100!",
    Content: map[string] interface {} {
        "reward_coins": 1000
    },
    Code: 101,
    Persistent: true,
}, & runtime.NotificationSend {
    UserID: "69769447-b2a7-445e-98ec-8b1c4c2ae592",
    Subject: "You've unlocked level 100!",
    Content: map[string] interface {} {
        "reward_coins": 1000
    },
    Code: 101,
    Persistent: true,
},
}
if err:= nk.NotificationsSend(ctx, notifications);
err != nil {
logger.WithField("err", err).Error("Notifications send error.")
}

Purchases #

PurchaseGetByTransactionId #

Look up a purchase receipt by transaction ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
transactionId string REQUIREDTransaction ID of the purchase to look up.
Returns
NameDescription
purchase *api.ValidatedPurchaseA validated purchase.
error errorAn optional error value if an error occurred.
1
2
3
4
5
transactionId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
userId, purchase, err := nk.PurchaseGetByTransactionId(ctx, transactionId)
if err != nil {
	// Handle error
}

PurchasesList #

List stored validated purchase receipts.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDFilter by user ID. Can be an empty string to list purchases for all users.
limit int100Limit number of records retrieved.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
listPurchases *api.PurchaseListA page of stored validated purchases and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
purchases, err := nk.PurchasesList(ctx, userId, 100, "")
if err != nil {
	// Handle error
}
for _, p := range purchases.ValidatedPurchases {
	logger.Info("Purchase: %+v", v)
}

PurchaseValidateApple #

Validates and stores the purchases present in an Apple App Store Receipt.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDBase-64 encoded receipt data returned by the purchase operation itself.
persist bool REQUIREDPersist the purchase so that seenBefore can be computed to protect against replay attacks.
passwordOverride stringOverride the iap.apple.shared_password provided in your configuration.
Returns
NameDescription
validation *api.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
receipt := "<base64-receipt-data>"
validation, err := nk.PurchaseValidateApple(ctx, userId, receipt)
if err != nil {
	// Handle error
}
for _, p := range validation.ValidatedPurchases {
	logger.Info("Validated purchase: %+v", v)
}

PurchaseValidateFacebookInstant #

Validates and stores a purchase receipt from Facebook Instant Games.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the owner of the receipt.
signedRequest string REQUIREDThe Facebook Instant signedRequest receipt data.
persist bool REQUIREDPersist the purchase so that seenBefore can be computed to protect against replay attacks.
Returns
NameDescription
validation *api.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
signedRequest := "<signedRequest-data>"

validation, err := nk.PurchaseValidateFacebookInstant(ctx, userId, signedRequest)
if err != nil {
	// Handle error
}
for _, p := range validation.ValidatedPurchases {
	logger.Info("Validated purchase: %+v", v)
}

PurchaseValidateGoogle #

Validates and stores a purchase receipt from the Google Play Store.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDJSON encoded Google receipt.
persist bool REQUIREDPersist the purchase so that seenBefore can be computed to protect against replay attacks.
overrides stringOverride the iap.google.client_email and iap.google.private_key provided in your configuration.
Returns
NameDescription
validation *api.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
receipt := "{\"json\":{\"orderId \":\"..\",\"packageName \":\"..\",\"productId \":\"..\",\"purchaseTime\":1607721533824,\"purchaseState\":0,\"purchaseToken\":\"..\",\"acknowledged\":false},\"signature \":\"..\",\"skuDetails \":{\"productId\":\"..\",\"type\":\"inapp\",\"price\":\"u20ac82.67\",\"price_amount_micros\":82672732,\"price_currency_code\":\"EUR\",\"title\":\"..\",\"description\":\"..\",\"skuDetailsToken\":\"..\"}}"
validation, err := nk.PurchaseValidateGoogle(ctx, userId, receipt)
if err != nil {
	// Handle error
}
for _, p := range validation.ValidatedPurchases {
	logger.Info("Validated purchase: %+v", v)
}

PurchaseValidateHuawei #

Validates and stores a purchase receipt from the Huawei App Gallery.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDThe Huawei receipt data.
signature string REQUIREDThe receipt signature.
persist bool REQUIREDPersist the purchase so that seenBefore can be computed to protect against replay attacks.
Returns
NameDescription
validation *api.ValidatePurchaseResponseThe resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
signature := "<signature-data>"
receipt := "<receipt-data>"

validation, err := nk.PurchaseValidateHuawei(ctx, userId, signature, receipt)
if err != nil {
	// Handle error
}
for _, p := range validation.ValidatedPurchases {
	logger.Info("Validated purchase: %+v", v)
}

Satori #

Authenticate #

Create a new identity.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
ipAddress stringAn optional client IP address to pass on to Satori for geo-IP lookup.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
userId := "user-id"
satori.Authenticate(ctx, userId)

EventsPublish #

Publish one or more events.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
events runtime.Event REQUIREDAn array of events to publish.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
satori.EventsPublish(ctx, "identityId", []*runtime.Event{{
	Name: "eventName",
	Id:   "optionalEventId",
	Metadata: map[string]string{
		"someProperty": "someValue",
	},
	Value:     "someValue",
	Timestamp: time.Now().Unix(),
}})

ExperimentsList #

List the experiments for an identity.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
names []string[]Optional list of experiment names to filter.
Returns
NameDescription
experiments runtime.ExperimentListThe list of experiments.
error errorAn optional error value if an error occurred.
1
experimentList, err := satori.ExperimentsList(ctx, "identityId", "experimentName1", "experimentName2")

FlagsList #

List the feature flags for an identity.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
names []string[]Optional list of flag names to filter.
Returns
NameDescription
flags runtime.FlagListThe list of feature flags.
error errorAn optional error value if an error occurred.
1
flagList, err := satori.FlagsList(ctx, "identityId", "flagName1", "flagName2")

GetSatori #

Get the Satori client.

Parameters
NameDefaultDescription
Returns
NameDescription
satori runtime.SatoriThe Satori client.
1
satori := nk.GetSatori()

LiveEventsList #

List the live events for an identity.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
names []string[]Optional list of live event names to filter.
Returns
NameDescription
liveEvents runtime.FlagListThe list of live events.
error errorAn optional error value if an error occurred.
1
liveEventList, err := satori.LiveEventsList(ctx, "identityId", "liveEventName1", "liveEventName2")

PropertiesGet #

Get the properties of an identity.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
Returns
NameDescription
properties runtime.PropertiesThe properties associated with the identity.
error errorAn optional error value if an error occurred.
1
properties, err := satori.PropertiesGet(ctx, "identityId")

PropertiesUpdate #

Update the properties of an identity.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe identifier of the identity.
properties runtime.PropertiesUpdate REQUIREDThe identity properties to update.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
err := satori.PropertiesUpdate(ctx, "identityId", &runtime.PropertiesUpdate{
	Default: map[string]string{
		"language": "japanese",
	},
	Custom: map[string]string{
		"customProperty": "someValue",
	},
})

Sessions #

SessionDisconnect #

Disconnect a session.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
sessionId string REQUIREDThe ID of the session to be disconnected.
reason runtime.PresenceReasonThe reason for the session disconnect.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
err := nk.SessionDisconnect(ctx, "sessionId", reason)
if err != nil {
    // Handle error
}

SessionLogout #

Log out a user from their current session.

Parameters
NameDefaultDescription
userId string REQUIREDThe ID of the user to be logged out.
token stringThe current session authentication token. If the current auth and refresh tokens are not provided, all user sessions will be logged out.
refreshToken stringThe current session refresh token. If the current auth and refresh tokens are not provided, all user sessions will be logged out.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
token := "<authToken>"
refreshToken := "<refreshToken"
err := nk.SessionLogout(ctx, token, refreshToken)
if err != nil {
    // Handle error
}

Storage #

StorageDelete #

Remove one or more objects by their collection/keyname and optional user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
objectIds []*runtime.StorageDelete REQUIREDAn array of object identifiers to be deleted.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
userID := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
friendUserID := "8d98ee3f-8c9f-42c5-b6c9-c8f79ad1b820"
objectIds := []*runtime.StorageDelete{&runtime.StorageDelete{
	Collection: "save",
	Key:        "save1",
	UserID:     userID,
}, &runtime.StorageDelete{
	Collection: "save",
	Key:        "save2",
	UserID:     userID,
}, &runtime.StorageDelete{
	Collection: "public",
	Key:        "progress",
	UserID:     friendUserID,
},
}

err := nk.StorageDelete(ctx, objectIds)
if err != nil {
	logger.WithField("err", err).Error("Storage delete error.")
}

StorageIndexList #

List storage index entries

Parameters
NameDefaultDescription
indexName string REQUIREDName of the index to list entries from.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty, defaults to system user and permissions are bypassed.
queryString string REQUIREDQuery to filter index entries.
limit int REQUIREDMaximum number of results to be returned.
order []stringThe storage object fields to sort the query results by. The prefix '-' before a field name indicates descending order. All specified fields must be indexed and sortable.
Returns
NameDescription
objects *api.StorageObjectListA list of storage objects.
error errorAn optional error value if an error occurred.
1
2
3
4
5
name := "index_name"
query := "+field1:1 field2:foo"
limit := 10

err := nk.StorageIndexList(name, query, limit)

StorageList #

List records in a collection and page through results. The records returned can be filtered to those owned by the user or "" for public records.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
callerId stringUser ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
userId string REQUIREDUser ID to list records for or "" (empty string) for public records.
collection string REQUIREDCollection to list data from.
limit int100Limit number of records retrieved.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
objects []*api.StorageObjectA list of storage objects.
cursor stringPagination cursor. Will be set to "" or nil when fetching last available page.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
userID := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
listRecords, nextCursor, err := nk.StorageList(ctx, userID, "collection", 10, "")
if err != nil {
	logger.WithField("err", err).Error("Storage list error.")
} else {
	for _, r := range listRecords {
		logger.Info("read: %d, write: %d, value: %s", r.PermissionRead, r.PermissionWrite, r.Value)
	}
}

StorageRead #

Fetch one or more records by their bucket/collection/keyname and optional user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
objectIds []*runtime.StorageRead REQUIREDAn array of object identifiers to be fetched.
Returns
NameDescription
objects []*api.StorageObjectA list of storage objects matching the parameters criteria.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
userID := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
objectIds := []*runtime.StorageRead{&runtime.StorageRead{
	Collection: "save",
	Key:        "save1",
	UserID:     userID,
}, &runtime.StorageRead{
	Collection: "save",
	Key:        "save2",
	UserID:     userID,
}, &runtime.StorageRead{
	Collection: "save",
	Key:        "save3",
	UserID:     userID,
},
}

records, err := nk.StorageRead(ctx, objectIds)
if err != nil {
	logger.WithField("err", err).Error("Storage read error.")
} else {
	for _, record := range records {
		logger.Info("read: %d, write: %d, value: %s", record.PermissionRead, record.PermissionWrite, record.Value)
	}
}

StorageWrite #

Write one or more objects by their collection/keyname and optional user.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
objectIds []*runtime.StorageWrite REQUIREDAn array of object identifiers to be written.
Returns
NameDescription
acks []*api.StorageObjectAckA list of acks with the version of the written objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
userID := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
objectIDs := []*runtime.StorageWrite{&runtime.StorageWrite{
	Collection: "save",
	Key:        "save1",
	UserID:     userID,
	Value:      "{}", // Value must be a valid encoded JSON object.
}, &runtime.StorageWrite{
	Collection: "save",
	Key:        "save2",
	UserID:     userID,
	Value:      "{}", // Value must be a valid encoded JSON object.
}, &runtime.StorageWrite{
	Collection:      "public",
	Key:             "save3",
	UserID:          userID,
	Value:           "{}", // Value must be a valid encoded JSON object.
	PermissionRead:  2,
	PermissionWrite: 1,
}, &runtime.StorageWrite{
	Collection:      "public",
	Key:             "save4",
	UserID:          userID,
	Value:           "{}", // Value must be a valid encoded JSON object.
	Version:         "*",
	PermissionRead:  2,
	PermissionWrite: 1,
},
}

_, err := nk.StorageWrite(ctx, objectIDs)
if err != nil {
	logger.WithField("err", err).Error("Storage write error.")
}

Streams #

StreamClose #

Close a stream and remove all presences on it.

Parameters
NameDefaultDescription
mode uint REQUIREDThe Type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
mode := uint8(123)
label := "label"
nk.StreamClose(mode, "", "", label)

StreamCount #

Get a count of stream presences.

Parameters
NameDefaultDescription
mode uint REQUIREDThe Type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
Returns
NameDescription
countByStream intNumber of current stream presences.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
mode := uint8(123)
label := "label"
count, err := nk.StreamCount(mode, "", "", label)
if err != nil {
  // Handle error here.
}

StreamSend #

Send data to presences on a stream.

Parameters
NameDefaultDescription
mode uint REQUIREDThe Type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
data string REQUIREDThe data to send.
presences []runtime.PresenceallArray of presences to receive the sent data.
reliable bool REQUIREDWhether the sender has been validated prior.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
mode := uint8(123)
label := "label"
// Data does not have to be JSON, but it's a convenient format.
data := "{\"some\":\"data\"}"
nk.StreamSend(mode, "", "", label, data, nil)

StreamSendRaw #

Send a message to presences on a stream.

Parameters
NameDefaultDescription
mode uint REQUIREDThe Type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
msg *rtapi.Envelope REQUIREDThe message to send.
presences []runtime.PresenceallArray of presences to receive the sent data.
reliable bool REQUIREDWhether the sender has been validated prior.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
mode := uint8(123)
label := "label"
msg := <*rtapi.Envelope>
nk.StreamSendRaw(mode, "", "", label, msg, nil)

StreamUserGet #

Retrieve a stream presence and metadata by user ID.

Parameters
NameDefaultDescription
mode uint REQUIREDThe type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
userId string REQUIREDThe user ID to fetch information for.
sessionId string REQUIREDThe current session ID for the user.
Returns
NameDescription
meta runtime.PresenceMetaPresence and metadata for the user.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
mode := uint8(123)
label := "label"

if metaPresence, err := nk.StreamUserGet(mode, "", "", label, userID, sessionID); err != nil {
    // Handle error.
} else if metaPresence != nil {
    logger.Info("User found on stream")
} else {
    logger.Info("User not found on stream")
}

return "Success", nil

StreamUserJoin #

Add a user to a stream.

Parameters
NameDefaultDescription
mode uint REQUIREDThe type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
userId string REQUIREDThe user ID to be added.
sessionId string REQUIREDThe current session ID for the user.
hidden bool REQUIREDWhether the user will be marked as hidden.
persistence bool REQUIREDWhether message data should be stored in the database.
status string REQUIREDUser status message.
Returns
NameDescription
success boolWhether the user was successfully added.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
userID := "<userId>"
sessionID := "<sessionId>"
mode := 123
hidden := false
persistence := false
if _, err := nk.StreamUserJoin(mode, "", "", "label", userID, sessionID, hidden, persistence, ""); err != nil {
    return "", err
}

StreamUserKick #

Kick a user from a stream.

Parameters
NameDefaultDescription
mode uint REQUIREDThe Type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
presence REQUIREDThe presence to be kicked.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
mode := uint8(123)
label := "some chat room channel name"
userID := "user ID to kick"
sessionID := "session ID to kick"

if err := nk.StreamUserKick(mode, "", "", label, userID, sessionID); err != nil {
  // Handle error.
}

StreamUserLeave #

Remove a user from a stream.

Parameters
NameDefaultDescription
mode uint REQUIREDThe Type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
userId string REQUIREDThe user ID to be removed.
sessionId string REQUIREDThe current session ID for the user.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
mode := uint8(123)
label := "some chat room channel name"
userID := "user ID to leave"
sessionID := "session ID to leave"

if err := nk.StreamUserLeave(mode, "", "", label, userID, sessionID); err != nil {
  // Handle error.
}

StreamUserList #

List all users currently online and connected to a stream.

Parameters
NameDefaultDescription
mode uint REQUIREDThe type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
includeHidden boolInclude stream presences marked as hidden in the results.
includeNotHidden boolInclude stream presences not marked as hidden in the results.
Returns
NameDescription
presences []runtime.PresenceArray of stream presences and their information.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
mode := uint8(123)
label := "label"
includeHidden := true
includeNotHidden := true

members, err := nk.StreamUserList(mode, "", "", label, includeHidden, includeNotHidden)
if err != nil {
  // Handle error here
}

StreamUserUpdate #

Update a stream user by ID.

Parameters
NameDefaultDescription
mode uint REQUIREDThe type of stream, '2' for a chat channel for example.
subject string REQUIREDThe primary stream subject, typically a user ID.
subcontext string REQUIREDA secondary subject, for example for direct chat between two users.
label string REQUIREDMeta-information about the stream, for example a chat room name.
userId string REQUIREDThe user ID to be updated.
sessionId string REQUIREDThe current session ID for the user.
hidden bool REQUIREDWhether the user will be marked as hidden.
persistence bool REQUIREDWhether message data should be stored in the database.
status string REQUIREDUser status message.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
userID := "<userId>"
sessionID := "<sessionId>"
mode := 123
hidden := true
persistence := false
status := "<userStatus"
if _, err := nk.StreamUserUpdate(mode, "", "", "label", userID, sessionID, hidden, persistence, ""); err != nil {
    return "", err
}

return "Success", nil

Subscriptions #

SubscriptionGetByProductId #

Look up a subscription receipt by productID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDUser ID of the subscription owner.
productId string REQUIREDProduct ID of the subscription to look up.
Returns
NameDescription
subscription *api.ValidatedSubscriptionA validated subscription.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
productId := "productId"
userId, subscription, err := nk.SubscriptionGetByProductId(ctx, userId, productId)
if err != nil {
	// Handle error
}

SubscriptionsList #

List stored validated subscriptions.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDFilter by user ID. Can be an empty string to list purchases for all users.
limit int100Limit number of records retrieved.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
listSubscriptions *api.SubscriptionListA page of stored validated subscriptions and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
subscriptions, err := nk.SubscriptionsList(ctx, userId)
if err != nil {
	// Handle error
}
for _, p := range Subscriptions.ValidatedSubscriptions {
	logger.Info("Subscription: %+v", v)
}

SubscriptionValidateApple #

Validates and stores the subscription present in an Apple App Store Receipt.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDBase-64 encoded receipt data returned by the purchase operation itself.
persist bool REQUIREDPersist the subscription.
passwordOverride stringOverride the iap.apple.shared_password provided in your configuration.
Returns
NameDescription
validation *api.ValidateSubscriptionResponseThe resulting successfully validated subscription purchase.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
receipt := "<base64-receipt-data>"
persist := true
validation, err := nk.SubscriptionValidateApple(ctx, userId, receipt, persist)
if err != nil {
	// Handle error
}
for _, p := range validation.ValidatedSubscriptions {
	logger.Info("Validated Subscription: %+v", v)
}

SubscriptionValidateGoogle #

Validates and stores a subscription receipt from the Google Play Store.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe user ID of the owner of the receipt.
receipt string REQUIREDJSON encoded Google receipt.
persist bool REQUIREDPersist the subscription.
overrides stringOverride the iap.google.client_email and iap.google.private_key provided in your configuration.
Returns
NameDescription
validation *api.ValidateSubscriptionResponseThe resulting successfully validated subscription.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
userId := "4c2ae592-b2a7-445e-98ec-697694478b1c"
receipt := "{\"json\":{\"orderId \":\"..\",\"packageName \":\"..\",\"productId \":\"..\",\"purchaseTime\":1607721533824,\"purchaseState\":0,\"purchaseToken\":\"..\",\"acknowledged\":false},\"signature \":\"..\",\"skuDetails \":{\"productId\":\"..\",\"type\":\"inapp\",\"price\":\"u20ac82.67\",\"price_amount_micros\":82672732,\"price_currency_code\":\"EUR\",\"title\":\"..\",\"description\":\"..\",\"skuDetailsToken\":\"..\"}}"
persist := true
validation, err := nk.SubscriptionValidateGoogle(ctx, userId, receipt, persist)
if err != nil {
	// Handle error
}
for _, p := range validation.ValidatedPurchases {
	logger.Info("Validated Subscription: %+v", v)
}

Tournaments #

TournamentAddAttempt #

Add additional score attempts to the owner's tournament record. This overrides the max number of score attempts allowed in the tournament for this specific owner.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the tournament to update.
owner string REQUIREDThe owner of the records to increment the count for.
count int REQUIREDThe number of attempt counts to increment. Can be negative to decrease count.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "leaderboard-record-owner"
count := -10
err := nk.TournamentAddAttempt(ctx, id, ownerID, count)
if err != nil {
	logger.WithField("err", err).Error("Tournament add attempt error.")
}

TournamentCreate #

Setup a new dynamic tournament with the specified ID and various configuration settings. The underlying leaderboard will be created if it doesn't already exist, otherwise its configuration will not be updated.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the new tournament. This is used by clients to submit scores.
authoritative bool REQUIREDWhether the tournament created is server authoritative.
sortOrder string REQUIREDThe sort order for records in the tournament. Possible values are "asc" or "desc".
operator string REQUIREDThe operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr".
resetSchedule string REQUIREDThe cron format used to define the reset schedule for the tournament. This controls when the underlying leaderboard resets and the tournament is considered active again.
metadata map[string]interface REQUIREDThe metadata you want associated to the tournament. Some good examples are weather conditions for a racing game.
title string REQUIREDThe title of the tournament.
description string REQUIREDThe description of the tournament.
category int REQUIREDA category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127.
startTime intThe start time of the tournament. Leave empty for immediately or a future time.
endTime intneverThe end time of the tournament. When the end time is elapsed, the tournament will not reset and will cease to exist. Must be greater than startTime if set.
duration int REQUIREDThe active duration for a tournament. This is the duration when clients are able to submit new records. The duration starts from either the reset period or tournament start time, whichever is sooner. A game client can query the tournament for results between end of duration and next reset period.
maxSize int REQUIREDMaximum size of participants in a tournament.
maxNumScore int REQUIRED1000000Maximum submission attempts for a tournament record.
joinRequired bool REQUIREDfalseWhether the tournament needs to be joined before a record write is allowed.
enableRanks bool REQUIREDWhether to enable rank values for the tournament.
Returns
NameDescription
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
authoritative := false
sortOrder := "desc"           // One of: "desc", "asc".
operator := "best"            // One of: "best", "set", "incr".
resetSchedule := "0 12 * * *" // Noon UTC each day.
metadata := map[string]interface{}{
	"weather_conditions": "rain",
}
title := "Daily Dash"
description := "Dash past your opponents for high scores and big rewards!"
category := 1
startTime := 0       // Start now.
endTime := 0         // Never end, repeat the tournament each day forever.
duration := 3600     // In seconds.
maxSize := 10000     // First 10,000 players who join.
maxNumScore := 3     // Each player can have 3 attempts to score.
joinRequired := true // Must join to compete.
enableRanks := true  // Set to true to enable rank computation on leaderboard records.

err := nk.TournamentCreate(ctx, id, authoritative, sortOrder, operator, resetSchedule, metadata,
	title, description, category, startTime, endTime, duration, maxSize, maxNumScore, joinRequired, enableRanks)
if err != nil {
	logger.WithField("err", err).Error("Tournament create error.")
}

TournamentDelete #

Delete a tournament and all records that belong to it.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the tournament to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
err := nk.TournamentDelete(ctx, id)
if err != nil {
	logger.WithField("err", err).Error("Tournament delete error.")
}

TournamentJoin #

A tournament may need to be joined before the owner can submit scores. This operation is idempotent and will always succeed for the owner even if they have already joined the tournament.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the tournament to join.
ownerId string REQUIREDThe owner of the record.
username string REQUIREDThe username of the record owner.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "leaderboard-record-owner"
userName := "myusername"
err := nk.TournamentJoin(ctx, id, ownerID, userName)
if err != nil {
	logger.WithField("err", err).Error("Tournament join error.")
}

TournamentList #

Find tournaments which have been created on the server. Tournaments can be filtered with categories and via start and end times.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
categoryStart int REQUIREDFilter tournaments with categories greater or equal than this value.
categoryEnd int REQUIREDFilter tournaments with categories equal or less than this value.
startTime int REQUIREDFilter tournaments that start after this time.
endTime int REQUIREDFilter tournaments that end before this time.
limit int REQUIRED10Return only the required number of tournament denoted by this limit value.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
tournamentList []*api.TournamentListA list of tournament results and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
categoryStart := 1
categoryEnd := 2
startTime := int(time.Now().Unix())
endTime := 0 // All tournaments from the start time.
limit := 100 // Number to list per page.
cursor := ""
list, err := nk.TournamentList(ctx, categoryStart, categoryEnd, startTime, endTime, limit, cursor)
if err != nil {
	logger.WithField("err", err).Error("Tournament list error.")
} else {
	for _, t := range list.Tournaments {
		logger.Info("ID %s - can enter? %b", t.Id, t.CanEnter)
	}
}

TournamentRanksDisable #

Disable a tournament rank cache freeing its allocated resources. If already disabled is a NOOP.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe tournament id.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
err := nk.TournamentRanksDisable(ctx, id)
if err != nil {
	logger.WithField("err", err).Error("Tournament ranks disable error.")
}

TournamentRecordDelete #

Remove an owner's record from a tournament, if one exists.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the tournament to delete from.
owner string REQUIREDThe owner of the score to delete.
Returns
NameDescription
error errorAn optional error value if an error occurred.

TournamentRecordsHaystack #

Fetch the list of tournament records around the owner.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe ID of the tournament to list records for.
ownerId string REQUIREDThe owner ID around which to show records.
limit int REQUIREDReturn only the required number of tournament records denoted by this limit value. Between 1-100.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
expiry int REQUIREDTime since epoch in seconds. Must be greater than 0.
Returns
NameDescription
tournamentRecordsHaystack *api.TournamentRecordListA list of tournament records and possibly a cursor. If cursor is empty/nil there are no further results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "4c2ae592-b2a7-445e-98ec-697694478b1c"
limit := 10
records, err := nk.TournamentRecordsHaystack(ctx, id, ownerID, limit)
if err != nil {
	logger.WithField("err", err).Error("Tournament record haystack error.")
} else {
	for _, r := range records {
		logger.Info("Leaderboard: %s, score: %d, subscore: %d", r.GetLeaderboardId(), r.Score, r.Subscore)
	}
}

TournamentRecordsList #

List records on the specified tournament, optionally filtering to only a subset of records by their owners. Records will be listed in the preconfigured tournament sort order.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
tournamentId string REQUIREDThe ID of the tournament to list records for.
ownerIds []string REQUIREDArray of owner IDs to filter results by.
limit int REQUIREDReturn only the required number of tournament records denoted by this limit value. Max is 10000.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiry int REQUIREDRecords with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
NameDescription
records []*api.LeaderboardRecordA page of tournament records.
ownerRecords []*api.LeaderboardRecordA list of owner tournament records (empty if the owners input parameter is not set).
prevCursor stringAn optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursor stringAn optional next page cursor that can be used to retrieve the next page of records (if any).
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
limit := 100
overrideExpiry := 0
records, err := nk.TournamentRecordsList(ctx, id, limit, overrideExpiry)
if err != nil {
	logger.WithField("err", err).Error("Tournament records list error.")
} else {
	for _, r := range records {
		logger.Info("Leaderboard: %s, score: %d, subscore: %d", r.GetLeaderboardId(), r.Score, r.Subscore)
	}
}

TournamentRecordWrite #

Submit a score and optional subscore to a tournament leaderboard. If the tournament has been configured with join required this will fail unless the owner has already joined the tournament.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
id string REQUIREDThe unique identifier for the tournament leaderboard to submit to.
owner string REQUIREDThe owner of this score submission.
username string REQUIREDThe owner username of this score submission, if it's a user.
score int REQUIREDThe score to submit.
subscore intA secondary subscore parameter for the submission.
metadata map[string]interfaceThe metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
Returns
NameDescription
result *api.LeaderboardRecordThe newly created leaderboard record.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
id := "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
ownerID := "4c2ae592-b2a7-445e-98ec-697694478b1c"
username := "02ebb2c8"
score := int64(10)
subscore := int64(0)
metadata := map[string]interface{}{
	"weather_conditions": "rain",
}
_, err := nk.TournamentRecordWrite(ctx, id, ownerID, username, score, subscore, metadata)
if err != nil {
	logger.WithField("err", err).Error("Tournament record write error.")
}

TournamentsGetId #

Fetch one or more tournaments by ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
ids []string REQUIREDThe table array of tournament ids.
Returns
NameDescription
result []*api.TournamentArray of tournament records.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
tournamentIDs := []string{
	"3ea5608a-43c3-11e7-90f9-7b9397165f34",
	"447524be-43c3-11e7-af09-3f7172f05936",
}
tournaments, err := nk.TournamentsGetId(ctx, tournamentIDs)
if err != nil {
	logger.WithField("err", err).Error("Tournaments get error.")
}

Users #

MultiUpdate #

Update account, storage, and wallet information simultaneously.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
accountUpdates []*runtime.AccountUpdate REQUIREDArray of account information to be updated.
storageWrites []*runtime.StorageWrite REQUIREDArray of storage objects to be updated.
storageDeletes []*runtime.StorageDelete REQUIREDArray of storage objects to be deleted.
walletUpdates []*runtime.WalletUpdate REQUIREDArray of wallet updates to be made.
updateLedger boolfalseWhether to record this wallet update in the ledger.
Returns
NameDescription
storageWriteOps []*api.StorageObjectAckA list of acks with the version of the written objects.
walletUpdateOps []*runtime.WalletUpdateResultA list of wallet updates results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
accountUpdates := []*runtime.AccountUpdate{}
storageWrites := []*runtime.StorageWrite{}
walletUpdates := []*runtime.WalletUpdate{}
updateLedger := true
storageAcks, walletUpdateResults, err := nk.MultiUpdate(ctx, accountUpdates, storageWrites, walletUpdates, updateLedger)

if err != nil {
    logger.WithField("err", err).Error("Multi update error.")
} else {
    logger.Info("Storage Acks: %d", len(storageAcks))
    logger.Info("Wallet Updates: %d", len(walletUpdateResults))
}

UsersBanId #

Ban one or more users by ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userIds []string REQUIREDAn array of user IDs to ban.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
userIDs := []string{
    "3ea5608a-43c3-11e7-90f9-7b9397165f34",
    "447524be-43c3-11e7-af09-3f7172f05936",
}
err := nk.UsersBanId(ctx, userIDs)
if err != nil {
logger.WithField("err", err).Error("Users ban ID error.")
}

UsersGetId #

Fetch one or more users by ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userIds []string REQUIREDAn array of user IDs to fetch.
Returns
NameDescription
users []*api.UserA list of user record objects.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
userIDs := []string{
    "3ea5608a-43c3-11e7-90f9-7b9397165f34",
    "447524be-43c3-11e7-af09-3f7172f05936",
}
users, err := nk.UsersGetId(ctx, userIDs)
if err != nil {
logger.WithField("err", err).Error("Users get ID error.")
} else {
for _, u := range users {
    logger.Info("username: %s, displayname: %s", u.Username, u.DisplayName)
    }
}

UsersGetRandom #

Fetch one or more users randomly.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
count int REQUIREDThe number of users to fetch.
Returns
NameDescription
users []*api.UserA list of user record objects.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
users, err := nk.UsersGetRandom(ctx, 10)
if err != nil {
    logger.WithField("err", err).Error("Users get random error.")
} else {
for _, u := range users {
    logger.Info("id: %s, displayname: %s", u.Id, u.DisplayName)
    }
}

UsersGetUsername #

Fetch one or more users by username.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
usernames []string REQUIREDAn array of usernames to fetch.
Returns
NameDescription
users []*api.UserA list of user record objects.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
users, err := nk.UsersGetUsername(ctx, []string{"b7865e7e", "c048ba7a"})
if err != nil {
logger.WithField("err", err).Error("Users get username error.")
} else {
for _, u := range users {
    logger.Info("id: %s, displayname: %s", u.Id, u.DisplayName)
    }
}

UsersUnbanId #

Unban one or more users by ID.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userIds []string REQUIREDAn array of user IDs to unban.
Returns
NameDescription
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
userIDs := []string{
    "3ea5608a-43c3-11e7-90f9-7b9397165f34",
    "447524be-43c3-11e7-af09-3f7172f05936",
}
err := nk.UsersUnbanId(ctx, userIDs)
if err != nil {
logger.WithField("err", err).Error("Users unban id error.")
}

Utils #

CronNext #

Parses a CRON expression and a timestamp in UTC seconds, and returns the next matching timestamp in UTC seconds.

Parameters
NameDefaultDescription
expression string REQUIREDA valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight).
timestamp int REQUIREDA time value expressed as UTC seconds.
Returns
NameDescription
nextTs int64The next UTC seconds timestamp (number) that matches the given CRON expression, and is immediately after the given timestamp.
error errorAn optional error value if an error occurred.
1
2
3
expr := "0 0 * * 1"
ts := time.Now().Unix()
next, err := nk.CronNext(expr, ts)

CronPrev #

Parses a CRON expression and a timestamp in UTC seconds, and returns the previous matching timestamp in UTC seconds.

Parameters
NameDefaultDescription
expression string REQUIREDA valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight).
timestamp int REQUIREDA time value expressed as UTC seconds.
Returns
NameDescription
prevTs int64The previous UTC seconds timestamp (number) that matches the given CRON expression, and is immediately before the given timestamp.
error errorAn optional error value if an error occurred.
1
2
3
expr := "0 0 * * 1"
ts := time.Now().Unix()
prev, err := nk.CronPrev(expr, ts)

ReadFile #

Read file from user device.

Parameters
NameDefaultDescription
relPath string REQUIREDRelative path to the file to be read.
Returns
NameDescription
fileRead *os.FileThe read file.
error errorAn optional error value if an error occurred.
1
2
3
4
5
path := "<relative file path>"
fileRead, err := nk.ReadFile(ctx, path)
if err != nil {
	logger.WithField("err", err).Error("File read error.")
}

Wallets #

WalletLedgerList #

List all wallet updates for a particular user from oldest to newest.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user to list wallet updates for.
limit int100Limit number of results.
cursor stringPagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
NameDescription
runtimeItems []runtime.WalletLedgerItemA Go slice containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
userID := "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
items, err := nk.WalletLedgerList(ctx, userID)
if err != nil {
    logger.WithField("err", err).Error("Wallet ledger list error.")
} else {
for _, item := range items {
    logger.Info("Found wallet update with id: %v", item.GetID())
    }
}

WalletLedgerUpdate #

Update the metadata for a particular wallet update in a user's wallet ledger history. Useful when adding a note to a transaction for example.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
itemId string REQUIREDThe ID of the wallet ledger item to update.
metadata map[string]interface REQUIREDThe new metadata to set on the wallet ledger item.
Returns
NameDescription
updateWalletLedger runtime.WalletLedgerItemThe updated wallet ledger item.
error errorAn optional error value if an error occurred.
1
2
3
4
5
6
7
8
itemID := "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
metadata := map[string]interface{}{
"game_result": "loss",
}
_, err := nk.WalletLedgerUpdate(ctx, itemID, metadata)
if err != nil {
    logger.WithField("err", err).Error("Wallet ledger update error.")
}

WalletsUpdate #

Update one or more user wallets with individual changesets. This function will also insert a new wallet ledger item into each user's wallet history that tracks their update.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
updates []*runtime.WalletUpdate REQUIREDThe set of user wallet update operations to apply.
updateLedger bool REQUIREDfalseWhether to record this update in the ledger.
Returns
NameDescription
updateWallets []runtime.WalletUpdateResultA list of wallet update results.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
updates := []*runtime.WalletUpdate{
    &runtime.WalletUpdate{
        UserID: "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592",
        Changeset: map[string]interface{}{
            "coins": 10, // Add 10 coins to the user's wallet.
            "gems":  -5, // Remove 5 gems from the user's wallet.
        },
        Metadata: map[string]interface{}{
            "game_result": "won",
        },
    },
}
err := nk.WalletsUpdate(ctx, updates, true)
if err != nil {
    logger.WithField("err", err).Error("Wallets update error.")
}

WalletUpdate #

Update a user's wallet with the given changeset.

Parameters
NameDefaultDescription
ctx context.Context REQUIREDThe context object represents information about the server and requester.
userId string REQUIREDThe ID of the user whose wallet to update.
changeset map[string]int REQUIREDThe set of wallet operations to apply.
metadata map[string]interface REQUIREDAdditional metadata to tag the wallet update with.
updateLedger bool REQUIREDfalseWhether to record this update in the ledger.
Returns
NameDescription
updatedValue mapThe updated wallet value.
previousValue mapThe previous wallet value.
error errorAn optional error value if an error occurred.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
userID := "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
changeset := map[string]interface{}{
    "coins": 10, // Add 10 coins to the user's wallet.
    "gems":  -5, // Remove 5 gems from the user's wallet.
}
metadata := map[string]interface{}{
    "game_result": "won",
}
updated, previous, err := nk.WalletUpdate(ctx, userID, changeset, metadata, true)
if err != nil {
    logger.WithField("err", err).Error("Wallet update error.")
}