函数参考
#
服务器内置的代码运行库包括一个模块,该模块具有实现各种逻辑和自定义行为的功能,使您能够根据客户端接收的输入定义权威代码和条件。在服务器框架基础文档中进一步了解详情。
本页面列出了 Nakama 中的所有函数及其参数,并提供了每个函数相应的代码示例。
如未阅读关于如何使用服务器框架的文档,请阅读。
Accounts
#
AccountDeleteId
#
Delete an account by user ID.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | User ID for the account to be deleted. Must be valid UUID. |
recorded
bool
REQUIRED | false | Whether to record this deletion in the database. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | User ID for the account to be exported. Must be valid UUID. |
Returns |
---|
Name | Description |
---|
export
string | Account information for the provided user ID, in JSON format. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | User ID to fetch information for. Must be valid UUID. |
Returns |
---|
Name | Description |
---|
account
*api.Account | All account information including wallet, device IDs and more. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userIds
[]string
REQUIRED | | Array of user IDs to fetch information for. Must be valid UUID. |
Returns |
---|
Name | Description |
---|
account
[]*api.Account | An array of accounts. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | User ID for which the information is to be updated. Must be valid UUID. |
metadata
map[string]interface
REQUIRED | | The metadata to update for this account. |
username
string
REQUIRED | | Username to be set. Must be unique. Use "" if it is not being updated. |
displayName
string
REQUIRED | | Display name to be updated. Use "" if it is not being updated. |
timezone
string
REQUIRED | | Timezone to be updated. Use "" if it is not being updated. |
location
string
REQUIRED | | Location to be updated. Use "" if it is not being updated. |
language
string
REQUIRED | | Lang tag to be updated. Use "" if it is not being updated. |
avatarUrl
string
REQUIRED | | User's avatar URL. Use "" if it is not being updated. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
token
string
REQUIRED | | Apple sign in token. |
username
string
REQUIRED | | The user's username. If left empty, one is generated. |
create
bool
REQUIRED | | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | Custom ID to use to authenticate the user. Must be between 6-128 characters. |
username
string | | The user's username. If left empty, one is generated. |
create
bool
REQUIRED | | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | Device ID to use to authenticate the user. Must be between 1-128 characters. |
username
string | | The user's username. If left empty, one is generated. |
create
bool | true | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
email
string
REQUIRED | | Email address to use to authenticate the user. Must be between 10-255 characters. |
password
string
REQUIRED | | Password to set. Must be longer than 8 characters. |
username
string | | The user's username. If left empty, one is generated. |
create
bool | true | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
token
string
REQUIRED | | Facebook OAuth or Limited Login (JWT) access token. |
import
bool
REQUIRED | | Whether to automatically import Facebook friends after authentication. |
username
string | | The user's username. If left empty, one is generated. |
create
bool
REQUIRED | | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
playerInfo
string
REQUIRED | | Facebook Player info. |
username
string | | The user's username. If left empty, one is generated. |
create
bool
REQUIRED | | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
playerId
string
REQUIRED | | PlayerId provided by GameCenter. |
bundleId
string
REQUIRED | | BundleId of your app on iTunesConnect. |
timestamp
int
REQUIRED | | Timestamp at which Game Center authenticated the client and issued a signature. |
salt
string
REQUIRED | | A random string returned by Game Center authentication on client. |
signature
string
REQUIRED | | A signature returned by Game Center authentication on client. |
publicKeyUrl
string
REQUIRED | | A URL to the public key returned by Game Center authentication on client. |
username
string | | The user's username. If left empty, one is generated. |
create
bool
REQUIRED | | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
token
string
REQUIRED | | Google OAuth access token. |
username
string
REQUIRED | | The user's username. If left empty, one is generated. |
create
bool
REQUIRED | | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
token
string
REQUIRED | | Steam token. |
username
string | | The user's username. If left empty, one is generated. |
create
bool | true | Create user if one didn't exist previously. |
Returns |
---|
Name | Description |
---|
userID
string | The user ID of the authenticated user. |
username
string | The username of the authenticated user. |
create
bool | Value indicating if this account was just created or already existed. |
error
error | An 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 |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | User ID to use to generate the token. |
username
string | | The user's username. If left empty, one is generated. |
expiresAt
int | | UTC time in seconds when the token must expire. Defaults to server configured expiry time. |
vars
map[string]string | | Extra information that will be bundled in the session token. |
Returns |
---|
Name | Description |
---|
token
string | The Nakama session token. |
validity
int64 | The period for which the token remains valid. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
token
string
REQUIRED | | Apple sign in token. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
customId
string
REQUIRED | | Custom ID to be linked to the user. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
deviceId
string
REQUIRED | | Device ID to be linked to the user. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
email
string
REQUIRED | | Authentication email to be linked to the user. |
password
string
REQUIRED | | Password to set. Must be longer than 8 characters. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
username
string | | If left empty, one is generated. |
token
string
REQUIRED | | Facebook OAuth or Limited Login (JWT) access token. |
importFriends
bool
REQUIRED | | Whether to automatically import Facebook friends after authentication. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
signedPlayerInfo
string
REQUIRED | | Facebook player info. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
playerId
string
REQUIRED | | Player ID provided by Game Center. |
bundleId
string
REQUIRED | | Bundle ID of your app on iTunesConnect. |
timestamp
int
REQUIRED | | Timestamp at which Game Center authenticated the client and issued a signature. |
salt
string
REQUIRED | | A random string returned by Game Center authentication on client. |
signature
string
REQUIRED | | A signature returned by Game Center authentication on client. |
publicKeyUrl
string
REQUIRED | | A URL to the public key returned by Game Center authentication on client. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
token
string
REQUIRED | | Google OAuth access token. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be linked. |
username
string | | If left empty, one is generated. |
token
string
REQUIRED | | Steam access token. |
importFriends
bool
REQUIRED | | Whether to automatically import Steam friends after authentication. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string
REQUIRED | | Apple sign in token. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
customId
string
REQUIRED | | Custom ID to be unlinked from the user. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
deviceId
string
REQUIRED | | Device ID to be unlinked from the user. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
email
string
REQUIRED | | Email to be unlinked from the user. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string
REQUIRED | | Facebook OAuth or Limited Login (JWT) access token. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
playerInfo
string
REQUIRED | | Facebook player info. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
playerId
string
REQUIRED | | Player ID provided by Game Center. |
bundleId
string
REQUIRED | | Bundle ID of your app on iTunesConnect. |
timestamp
int
REQUIRED | | Timestamp at which Game Center authenticated the client and issued a signature. |
salt
string
REQUIRED | | A random string returned by Game Center authentication on client. |
signature
string
REQUIRED | | A signature returned by Game Center authentication on client. |
publicKeyUrl
string
REQUIRED | | A URL to the public key returned by Game Center authentication on client. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string
REQUIRED | | Google OAuth access token. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string
REQUIRED | | Steam access token. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
senderId
string
REQUIRED | | UserID of the message sender (when applicable). An empty string defaults to the system user. |
target
string
REQUIRED | | Can be the room name, group identifier, or another username. |
chanType
runtime.ChannelType
REQUIRED | | The type of channel, either Room (1), Direct (2), or Group (3). |
Returns |
---|
Name | Description |
---|
channelId
string | The generated ID representing a channel. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
channelId
string
REQUIRED | | The ID of the channel to remove the message on. |
messageId
string
REQUIRED | | The ID of the message to remove. |
senderId
string | | The UUID for the sender of this message. If left empty, it will be assumed that it is a system message. |
senderUsername
string | | The username of the user who sent this message. If left empty, it will be assumed that it is a system message. |
persist
bool
REQUIRED | | Whether to record this in the channel history. |
Returns |
---|
Name | Description |
---|
channelMessageRemove
*rtapi.ChannelMessageAck | Message removed ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'. |
error
error | An optional error value if an error occurred. |
ChannelMessageSend
#
Send a message on a realtime chat channel.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
channelId
string
REQUIRED | | The ID of the channel to send the message on. |
content
map[string]interface
REQUIRED | | Message content. |
senderId
string | | The UUID for the sender of this message. If left empty, it will be assumed that it is a system message. |
senderUsername
string | | The username of the user to send this message as. If left empty, it will be assumed that it is a system message. |
persist
bool
REQUIRED | | Whether to record this message in the channel history. |
Returns |
---|
Name | Description |
---|
channelMessageSend
*rtapi.ChannelMessageAck | Message sent ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
channelId
string
REQUIRED | | The ID of the channel to list messages from. |
limit
int
REQUIRED | | The number of messages to return per page. |
forward
bool
REQUIRED | | Whether to list messages from oldest to newest, or newest to oldest. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
channelMessageList
[]*rtapi.ChannelMessage | Messages from the specified channel. |
nextCursor
string | Cursor for the next page of messages, if any. |
prevCursor
string | Cursor for the previous page of messages, if any. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
channelId
string
REQUIRED | | The ID of the channel to send the message on. |
messageId
string
REQUIRED | | The ID of the message to update. |
content
map[string]interface
REQUIRED | | Message content. |
senderId
string | | The UUID for the sender of this message. If left empty, it will be assumed that it is a system message. |
senderUsername
string | | The username of the user to send this message as. If left empty, it will be assumed that it is a system message. |
persist
bool
REQUIRED | | Whether to record this message in the channel history. |
Returns |
---|
Name | Description |
---|
channelMessageUpdate
*rtapi.ChannelMessageAck | Message updated ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
evt
*api.Event
REQUIRED | | The event to be generated. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user to whom you want to add friends. |
username
string
REQUIRED | | The name of the user to whom you want to add friends. |
ids
[]string | | The IDs of the users you want to add as friends. This argument is optional and can be set as `nil`. |
usernames
[]string | | The usernames of the users you want to add as friends. This argument is optional and can be set as `nil`. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user for whom you want to block friends. |
username
string
REQUIRED | | The name of the user for whom you want to block friends. |
ids
[]string
REQUIRED | | The IDs of the users you want to block as friends. |
usernames
[]string
REQUIRED | | The usernames of the users you want to block as friends. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user from whom you want to delete friends. |
username
string
REQUIRED | | The name of the user from whom you want to delete friends. |
ids
[]string
REQUIRED | | The IDs of the users you want to delete as friends. |
usernames
[]string
REQUIRED | | The usernames of the users you want to delete as friends. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user whose friends, invites, invited, and blocked you want to list. |
limit
int
REQUIRED | | The number of friends to retrieve in this page of results. No more than 100 limit allowed per result. |
state
int | | The state of the friendship with the user. If unspecified this returns friends in all states for the user. |
cursor
string
REQUIRED | | Pagination cursor from previous result. Set to "" to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
friends
[]*api.Friend | The user information for users that are friends of the current user. |
cursor
string | An 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
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user whose friends of friends you want to list. |
limit
int
REQUIRED | | The number of friends of friends to retrieve in this page of results. No more than 100 limit allowed per result. |
cursor
string
REQUIRED | | Pagination cursor from previous result. Set to "" to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
friends
[]*api.FriendsOfFriendsList_FriendOfFriend | The user information for users that are friends of friends the current user. |
cursor
string | An 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
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID to be associated as the group superadmin. |
name
string
REQUIRED | | Group name, must be unique. |
creatorId
string | | The user ID to be associated as creator. If not set or nil/null, system user will be set. |
langTag
string | | Group language. |
description
string | | Group description, can be left empty as nil/null. |
avatarUrl
string | | URL to the group avatar, can be left empty as nil/null. |
open
bool | false | Whether the group is for anyone to join, or members will need to send invitations to join. |
metadata
map[string]interface | | Custom information to store for this group. Can be left empty as nil/null. |
maxCount
int
REQUIRED | 100 | Maximum number of members to have in the group. |
Returns |
---|
Name | Description |
---|
createGroup
*api.Group | The groupId of the newly created group. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
groupId
string
REQUIRED | | The ID of the group to delete. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
groupIds
[]string
REQUIRED | | An array of strings of the IDs for the groups to get. |
Returns |
---|
Name | Description |
---|
getGroups
[]*api.Group | An array of groups with their fields. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
count
int
REQUIRED | | The number of groups to fetch. |
Returns |
---|
Name | Description |
---|
users
[]*api.Group | A list of group record objects. |
error
error | An optional error value if an error occurred. |
GroupsList
#
Find groups based on the entered criteria.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
name
string | | Search for groups that contain this value in their name. Cannot be combined with any other filter. |
langTag
string | | Filter based upon the entered language tag. |
members
int | | Search by number of group members. |
open
bool | | Filter based on whether groups are Open or Closed. |
limit
int | | Return only the required number of groups denoted by this limit value. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
groups
[]*api.Group | A list of groups. |
cursor
string | An 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
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
groupId
string
REQUIRED | | The ID of the group to update. |
userId
string
REQUIRED | | User ID calling the update operation for permission checking. Set as empty string to enact the changes as the system user. |
name
string
REQUIRED | | Group name, can be empty if not changed. |
creatorId
string
REQUIRED | | The user ID to be associated as creator. Can be empty if not changed. |
langTag
string
REQUIRED | | Group language. Empty if not updated. |
description
string
REQUIRED | | Group description, can be left empty if not updated. |
avatarUrl
string
REQUIRED | | URL to the group avatar, can be left empty if not updated. |
open
bool
REQUIRED | | Whether the group is for anyone to join or not. |
metadata
map[string]interface
REQUIRED | | Custom information to store for this group. Use nil if field is not being updated. |
maxCount
int
REQUIRED | | Maximum number of members to have in the group. Use 0, nil/null if field is not being updated. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
groupId
string
REQUIRED | | The ID of the group to join. |
userId
string
REQUIRED | | The user ID to add to this group. |
username
string
REQUIRED | | The username of the user to add to this group. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
groupId
string
REQUIRED | | The ID of the group to leave. |
userId
string
REQUIRED | | The user ID to remove from this group. |
username
string
REQUIRED | | The username of the user to remove from this group. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed. |
groupId
string
REQUIRED | | The ID of the group to add users to. |
userIds
[]string
REQUIRED | | Table array of user IDs to add to this group. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed. |
groupId
string
REQUIRED | | The ID of the group to ban users from. |
userIds
[]string
REQUIRED | | Table array of user IDs to ban from this group. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed. |
groupId
string
REQUIRED | | The ID of the group whose members are being demoted. |
userIds
[]string
REQUIRED | | Table array of user IDs to demote. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed. |
groupId
string
REQUIRED | | The ID of the group to kick users from. |
userIds
[]string
REQUIRED | | Table array of user IDs to kick. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
groupId
string
REQUIRED | | The ID of the group to list members for. |
limit
int
REQUIRED | | Return only the required number of users denoted by this limit value. |
state
int
REQUIRED | | Return only the users matching this state value, '0' for superadmins for example. |
cursor
string
REQUIRED | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
error
error | An 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())
}
|
Promote users in a group.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed. |
groupId
string
REQUIRED | | The ID of the group whose members are being promoted. |
userIds
[]string
REQUIRED | | Table array of user IDs to promote. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user to list groups for. |
limit
int
REQUIRED | | The maximum number of entries in the listing. |
state
int | | The state of the user within the group. If unspecified this returns users in all states. |
cursor
string
REQUIRED | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
cursor
string | An 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
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
leaderboardID
string
REQUIRED | | The unique identifier for the new leaderboard. This is used by clients to submit scores. |
authoritative
bool
REQUIRED | false | Mark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly. |
sortOrder
string
REQUIRED | | The sort order for records in the leaderboard. Possible values are "asc" or "desc". |
operator
string
REQUIRED | | The operator that determines how scores behave when submitted. Possible values are "best", "set", or "incr". |
resetSchedule
string
REQUIRED | | The 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
REQUIRED | | The metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game. |
enableRanks
bool
REQUIRED | | Whether to enable rank values for the leaderboard. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the leaderboard to delete. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
limit
int
REQUIRED | | Return only the required number of leaderboards denoted by this limit value. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
leaderboardList
*api.LeaderboardList | A list of leaderboard results and possibly a cursor. If cursor is empty/nil there are no further results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The leaderboard id. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the leaderboard to delete from. |
owner
string
REQUIRED | | The owner of the score to delete. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The ID of the leaderboard to list records for. |
ownerId
string
REQUIRED | | The owner ID around which to show records. |
limit
int
REQUIRED | | Return only the required number of leaderboard records denoted by this limit value. Between 1-100. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
expiry
int
REQUIRED | | Time since epoch in seconds. Must be greater than 0. |
Returns |
---|
Name | Description |
---|
leaderboardRecordsHaystack
*api.LeaderboardRecordList | A list of leaderboard records and possibly a cursor. If cursor is empty/nil there are no further results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the leaderboard to list. |
owners
[]string
REQUIRED | | Array of owners to filter to. |
limit
int
REQUIRED | | The maximum number of records to return (Max 10,000). |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
overrideExpiry
int
REQUIRED | | Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0. |
Returns |
---|
Name | Description |
---|
records
[]*api.LeaderboardRecord | A page of leaderboard records. |
ownerRecords
[]*api.LeaderboardRecord | A list of owner leaderboard records (empty if the owners input parameter is not set). |
nextCursor
string | An optional next page cursor that can be used to retrieve the next page of records (if any). |
prevCursor
string | An optional previous page cursor that can be used to retrieve the previous page of records (if any). |
error
error | An 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 |
---|
Name | Default | Description |
---|
leaderboardID
string
REQUIRED | | The unique identifier of the leaderboard. |
rank
int
REQUIRED | | The rank to start listing leaderboard records from. |
overrideExpiry
int
REQUIRED | | Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0. |
Returns |
---|
Name | Description |
---|
leaderboardListCursor
string | A string cursor to be used with leaderboardRecordsList. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the leaderboard to submit to. |
owner
string
REQUIRED | | The owner of this score submission. |
username
string
REQUIRED | | The owner username of this score submission, if it's a user. |
score
int
REQUIRED | | The score to submit. |
subscore
int | | A secondary subscore parameter for the submission. |
metadata
map[string]interface | | The metadata you want associated to this submission. Some good examples are weather conditions for a racing game. |
overrideOperator
*int
REQUIRED | | An 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 |
---|
Name | Description |
---|
record
*api.LeaderboardRecord | The newly created leaderboard record. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ids
[]string
REQUIRED | | The table array of leaderboard ids. |
Returns |
---|
Name | Description |
---|
leaderboardsGet
[]*api.Leaderboard | The leaderboard records according to ID. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
module
string
REQUIRED | | The name of an available runtime module that will be responsible for the match. This was registered in InitModule. |
params
map[string]interface
REQUIRED | | Any value to pass to the match init hook. |
Returns |
---|
Name | Description |
---|
matchId
string | The match ID of the newly created match. Clients can immediately use this ID to join the match. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The ID of the match to fetch. |
Returns |
---|
Name | Description |
---|
match
*api.Match | Information for the running match. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
limit
int | 100 | The maximum number of matches to list. |
authoritative
bool | false | Set true to only return authoritative matches, false to only return relayed matches. |
label
string
REQUIRED | | A label to filter authoritative matches by. Default "" means any label matches. |
minSize
int
REQUIRED | | Inclusive lower limit of current match participants. |
maxSize
int
REQUIRED | | Inclusive upper limit of current match participants. |
query
string
REQUIRED | | Additional query parameters to shortlist matches. |
Returns |
---|
Name | Description |
---|
match
[]*api.Match | A list of matches matching the parameters criteria. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | Context object represents information about the match and server for information purposes. |
id
string
REQUIRED | | The user ID or session ID to send a reservation signal for. |
data
string
REQUIRED | | An arbitrary input supplied by the runtime caller of the signal. |
Returns |
---|
Name | Description |
---|
data
string | Arbitrary data to return to the runtime caller of the signal. May be a string or nil. |
error
error | An 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 |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the custom metrics counter. |
tags
map[string]string
REQUIRED | | The metrics tags associated with this counter. |
delta
int
REQUIRED | | Value to update this metric with. |
Returns |
---|
Name | Description |
---|
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 |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the custom metrics gauge. |
tags
map[string]string
REQUIRED | | The metrics tags associated with this gauge. |
value
float
REQUIRED | | Value to update this metric with. |
Returns |
---|
Name | Description |
---|
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 |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the custom metrics timer. |
tags
map[string]string
REQUIRED | | The metrics tags associated with this timer. |
value
time.Duration
REQUIRED | | Value to update this metric with. |
Returns |
---|
Name | Description |
---|
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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
notifications
[]*runtime.NotificationDelete
REQUIRED | | A list of notifications to be deleted. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userID
string
REQUIRED | | Optional userID to scope deletions to that user only. Use empty string to ignore. |
ids
[]string
REQUIRED | | A list of notification ids. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the user to be sent the notification. |
subject
string
REQUIRED | | Notification subject. |
content
map[string]interface
REQUIRED | | Notification content. Must be set but can be an struct. |
code
int
REQUIRED | | Notification code to use. Must be equal or greater than 0. |
sender
string | | The sender of this notification. If left empty, it will be assumed that it is a system notification. |
persistent
bool
REQUIRED | false | Whether to record this in the database for later listing. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
subject
string
REQUIRED | | Notification subject. |
content
map[string]interface
REQUIRED | | Notification content. Must be set but can be any empty map. |
code
int
REQUIRED | | Notification code to use. Must be greater than or equal to 0. |
persistent
bool
REQUIRED | | Whether to record this in the database for later listing. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userID
string
REQUIRED | | Optional userID to scope results to that user only. |
ids
[]string
REQUIRED | | A list of notification ids. |
Returns |
---|
Name | Description |
---|
notifications
[]*api.Notification | A list of notifications. |
error
error | An 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
}
|
NotificationsList
#
List notifications by user id.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userID
string
REQUIRED | | Optional userID to scope results to that user only. |
limit
int
REQUIRED | | Limit number of results. Must be a value between 1 and 1000. |
cursor
string
REQUIRED | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
notifications
*api.NotificationList | A list of notifications. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
8
| userID := "b1aafe16-7540-11e7-9738-13777fcc7cd8"
limit := 20
notifications, err := nk.NotificationsList(ctx, userID, limit)
if err != nil {
logger.WithField("err", err).Error("nk.NotificationsList error.")
return
}
|
NotificationsSend
#
Send one or more in-app notifications to a user.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
notifications
[]*runtime.NotificationSend
REQUIRED | | A list of notifications to be sent together. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
transactionId
string
REQUIRED | | Transaction ID of the purchase to look up. |
Returns |
---|
Name | Description |
---|
purchase
*api.ValidatedPurchase | A validated purchase. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | Filter by user ID. Can be an empty string to list purchases for all users. |
limit
int | 100 | Limit number of records retrieved. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
listPurchases
*api.PurchaseList | A page of stored validated purchases and possibly a cursor. If cursor is empty/nil there are no further results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | Base-64 encoded receipt data returned by the purchase operation itself. |
persist
bool
REQUIRED | | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
passwordOverride
string | | Override the iap.apple.shared_password provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
*api.ValidatePurchaseResponse | The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
signedRequest
string
REQUIRED | | The Facebook Instant signedRequest receipt data. |
persist
bool
REQUIRED | | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
Returns |
---|
Name | Description |
---|
validation
*api.ValidatePurchaseResponse | The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | JSON encoded Google receipt. |
persist
bool
REQUIRED | | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
overrides
string | | Override the iap.google.client_email and iap.google.private_key provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
*api.ValidatePurchaseResponse | The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | The Huawei receipt data. |
signature
string
REQUIRED | | The receipt signature. |
persist
bool
REQUIRED | | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
Returns |
---|
Name | Description |
---|
validation
*api.ValidatePurchaseResponse | The resulting successfully validated purchases. Any previously validated purchases are returned with a seenBefore flag. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
ipAddress
string | | An optional client IP address to pass on to Satori for geo-IP lookup. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| userId := "user-id"
satori.Authenticate(ctx, userId)
|
EventsPublish
#
Publish one or more events.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
events
runtime.Event
REQUIRED | | An array of events to publish. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
names
[]string | [] | Optional list of experiment names to filter. |
Returns |
---|
Name | Description |
---|
experiments
runtime.ExperimentList | The list of experiments. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
names
[]string | [] | Optional list of flag names to filter. |
Returns |
---|
Name | Description |
---|
flags
runtime.FlagList | The list of feature flags. |
error
error | An optional error value if an error occurred. |
1
| flagList, err := satori.FlagsList(ctx, "identityId", "flagName1", "flagName2")
|
GetSatori
#
Get the Satori client.
Parameters |
---|
Name | Default | Description |
---|
Returns |
---|
Name | Description |
---|
satori
runtime.Satori | The Satori client. |
1
| satori := nk.GetSatori()
|
LiveEventsList
#
List the live events for an identity.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
names
[]string | [] | Optional list of live event names to filter. |
Returns |
---|
Name | Description |
---|
liveEvents
runtime.FlagList | The list of live events. |
error
error | An optional error value if an error occurred. |
1
| liveEventList, err := satori.LiveEventsList(ctx, "identityId", "liveEventName1", "liveEventName2")
|
PropertiesGet
#
Get the properties of an identity.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
Returns |
---|
Name | Description |
---|
properties
runtime.Properties | The properties associated with the identity. |
error
error | An optional error value if an error occurred. |
1
| properties, err := satori.PropertiesGet(ctx, "identityId")
|
PropertiesUpdate
#
Update the properties of an identity.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The identifier of the identity. |
properties
runtime.PropertiesUpdate
REQUIRED | | The identity properties to update. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
sessionId
string
REQUIRED | | The ID of the session to be disconnected. |
reason
runtime.PresenceReason | | The reason for the session disconnect. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The ID of the user to be logged out. |
token
string | | The current session authentication token. If the current auth and refresh tokens are not provided, all user sessions will be logged out. |
refreshToken
string | | The current session refresh token. If the current auth and refresh tokens are not provided, all user sessions will be logged out. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
objectIds
[]*runtime.StorageDelete
REQUIRED | | An array of object identifiers to be deleted. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
indexName
string
REQUIRED | | Name of the index to list entries from. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty, defaults to system user and permissions are bypassed. |
queryString
string
REQUIRED | | Query to filter index entries. |
limit
int
REQUIRED | | Maximum number of results to be returned. |
order
[]string | | The 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. |
cursor
string
REQUIRED | | A cursor to fetch the next page of results. |
Returns |
---|
Name | Description |
---|
objects
*api.StorageObjectList | A list of storage objects. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed. |
userId
string
REQUIRED | | User ID to list records for or "" (empty string) for public records. |
collection
string
REQUIRED | | Collection to list data from. |
limit
int | 100 | Limit number of records retrieved. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
objects
[]*api.StorageObject | A list of storage objects. |
cursor
string | Pagination cursor. Will be set to "" or nil when fetching last available page. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
objectIds
[]*runtime.StorageRead
REQUIRED | | An array of object identifiers to be fetched. |
Returns |
---|
Name | Description |
---|
objects
[]*api.StorageObject | A list of storage objects matching the parameters criteria. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
objectIds
[]*runtime.StorageWrite
REQUIRED | | An array of object identifiers to be written. |
Returns |
---|
Name | Description |
---|
acks
[]*api.StorageObjectAck | A list of acks with the version of the written objects. |
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The Type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The Type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
Returns |
---|
Name | Description |
---|
countByStream
int | Number of current stream presences. |
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The Type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
data
string
REQUIRED | | The data to send. |
presences
[]runtime.Presence | all | Array of presences to receive the sent data. |
reliable
bool
REQUIRED | | Whether the sender has been validated prior. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The Type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
msg
*rtapi.Envelope
REQUIRED | | The message to send. |
presences
[]runtime.Presence | all | Array of presences to receive the sent data. |
reliable
bool
REQUIRED | | Whether the sender has been validated prior. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
userId
string
REQUIRED | | The user ID to fetch information for. |
sessionId
string
REQUIRED | | The current session ID for the user. |
Returns |
---|
Name | Description |
---|
meta
runtime.PresenceMeta | Presence and metadata for the user. |
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
userId
string
REQUIRED | | The user ID to be added. |
sessionId
string
REQUIRED | | The current session ID for the user. |
hidden
bool
REQUIRED | | Whether the user will be marked as hidden. |
persistence
bool
REQUIRED | | Whether message data should be stored in the database. |
status
string
REQUIRED | | User status message. |
Returns |
---|
Name | Description |
---|
success
bool | Whether the user was successfully added. |
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The Type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
presence
REQUIRED | | The presence to be kicked. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The Type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
userId
string
REQUIRED | | The user ID to be removed. |
sessionId
string
REQUIRED | | The current session ID for the user. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
includeHidden
bool | | Include stream presences marked as hidden in the results. |
includeNotHidden
bool | | Include stream presences not marked as hidden in the results. |
Returns |
---|
Name | Description |
---|
presences
[]runtime.Presence | Array of stream presences and their information. |
error
error | An 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 |
---|
Name | Default | Description |
---|
mode
uint
REQUIRED | | The type of stream, '2' for a chat channel for example. |
subject
string
REQUIRED | | The primary stream subject, typically a user ID. |
subcontext
string
REQUIRED | | A secondary subject, for example for direct chat between two users. |
label
string
REQUIRED | | Meta-information about the stream, for example a chat room name. |
userId
string
REQUIRED | | The user ID to be updated. |
sessionId
string
REQUIRED | | The current session ID for the user. |
hidden
bool
REQUIRED | | Whether the user will be marked as hidden. |
persistence
bool
REQUIRED | | Whether message data should be stored in the database. |
status
string
REQUIRED | | User status message. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | User ID of the subscription owner. |
productId
string
REQUIRED | | Product ID of the subscription to look up. |
Returns |
---|
Name | Description |
---|
subscription
*api.ValidatedSubscription | A validated subscription. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | Filter by user ID. Can be an empty string to list purchases for all users. |
limit
int | 100 | Limit number of records retrieved. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
listSubscriptions
*api.SubscriptionList | A page of stored validated subscriptions and possibly a cursor. If cursor is empty/nil there are no further results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | Base-64 encoded receipt data returned by the purchase operation itself. |
persist
bool
REQUIRED | | Persist the subscription. |
passwordOverride
string | | Override the iap.apple.shared_password provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
*api.ValidateSubscriptionResponse | The resulting successfully validated subscription purchase. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | JSON encoded Google receipt. |
persist
bool
REQUIRED | | Persist the subscription. |
overrides
string | | Override the iap.google.client_email and iap.google.private_key provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
*api.ValidateSubscriptionResponse | The resulting successfully validated subscription. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the tournament to update. |
owner
string
REQUIRED | | The owner of the records to increment the count for. |
count
int
REQUIRED | | The number of attempt counts to increment. Can be negative to decrease count. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the new tournament. This is used by clients to submit scores. |
authoritative
bool
REQUIRED | | Whether the tournament created is server authoritative. |
sortOrder
string
REQUIRED | | The sort order for records in the tournament. Possible values are "asc" or "desc". |
operator
string
REQUIRED | | The operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr". |
resetSchedule
string
REQUIRED | | The 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
REQUIRED | | The metadata you want associated to the tournament. Some good examples are weather conditions for a racing game. |
title
string
REQUIRED | | The title of the tournament. |
description
string
REQUIRED | | The description of the tournament. |
category
int
REQUIRED | | A category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127. |
startTime
int | | The start time of the tournament. Leave empty for immediately or a future time. |
endTime
int | never | The 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
REQUIRED | | The 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
REQUIRED | | Maximum size of participants in a tournament. |
maxNumScore
int
REQUIRED | 1000000 | Maximum submission attempts for a tournament record. |
joinRequired
bool
REQUIRED | false | Whether the tournament needs to be joined before a record write is allowed. |
enableRanks
bool
REQUIRED | | Whether to enable rank values for the tournament. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the tournament to delete. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the tournament to join. |
ownerId
string
REQUIRED | | The owner of the record. |
username
string
REQUIRED | | The username of the record owner. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
categoryStart
int
REQUIRED | | Filter tournaments with categories greater or equal than this value. |
categoryEnd
int
REQUIRED | | Filter tournaments with categories equal or less than this value. |
startTime
int
REQUIRED | | Filter tournaments that start after this time. |
endTime
int
REQUIRED | | Filter tournaments that end before this time. |
limit
int
REQUIRED | 10 | Return only the required number of tournament denoted by this limit value. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
tournamentList
[]*api.TournamentList | A list of tournament results and possibly a cursor. If cursor is empty/nil there are no further results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The tournament id. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the tournament to delete from. |
owner
string
REQUIRED | | The owner of the score to delete. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
TournamentRecordsHaystack
#
Fetch the list of tournament records around the owner.
Parameters |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The ID of the tournament to list records for. |
ownerId
string
REQUIRED | | The owner ID around which to show records. |
limit
int
REQUIRED | | Return only the required number of tournament records denoted by this limit value. Between 1-100. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
expiry
int
REQUIRED | | Time since epoch in seconds. Must be greater than 0. |
Returns |
---|
Name | Description |
---|
tournamentRecordsHaystack
*api.TournamentRecordList | A list of tournament records and possibly a cursor. If cursor is empty/nil there are no further results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
tournamentId
string
REQUIRED | | The ID of the tournament to list records for. |
ownerIds
[]string
REQUIRED | | Array of owner IDs to filter results by. |
limit
int
REQUIRED | | Return only the required number of tournament records denoted by this limit value. Max is 10000. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
overrideExpiry
int
REQUIRED | | Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0. |
Returns |
---|
Name | Description |
---|
records
[]*api.LeaderboardRecord | A page of tournament records. |
ownerRecords
[]*api.LeaderboardRecord | A list of owner tournament records (empty if the owners input parameter is not set). |
prevCursor
string | An optional previous page cursor that can be used to retrieve the previous page of records (if any). |
nextCursor
string | An optional next page cursor that can be used to retrieve the next page of records (if any). |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
id
string
REQUIRED | | The unique identifier for the tournament leaderboard to submit to. |
owner
string
REQUIRED | | The owner of this score submission. |
username
string
REQUIRED | | The owner username of this score submission, if it's a user. |
score
int
REQUIRED | | The score to submit. |
subscore
int | | A secondary subscore parameter for the submission. |
metadata
map[string]interface | | The metadata you want associated to this submission. Some good examples are weather conditions for a racing game. |
overrideOperator
*int
REQUIRED | | An 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 |
---|
Name | Description |
---|
result
*api.LeaderboardRecord | The newly created leaderboard record. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
ids
[]string
REQUIRED | | The table array of tournament ids. |
Returns |
---|
Name | Description |
---|
result
[]*api.Tournament | Array of tournament records. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
accountUpdates
[]*runtime.AccountUpdate
REQUIRED | | Array of account information to be updated. |
storageWrites
[]*runtime.StorageWrite
REQUIRED | | Array of storage objects to be updated. |
storageDeletes
[]*runtime.StorageDelete
REQUIRED | | Array of storage objects to be deleted. |
walletUpdates
[]*runtime.WalletUpdate
REQUIRED | | Array of wallet updates to be made. |
updateLedger
bool | false | Whether to record this wallet update in the ledger. |
Returns |
---|
Name | Description |
---|
storageWriteOps
[]*api.StorageObjectAck | A list of acks with the version of the written objects. |
walletUpdateOps
[]*runtime.WalletUpdateResult | A list of wallet updates results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userIds
[]string
REQUIRED | | An array of user IDs to ban. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userIds
[]string
REQUIRED | | An array of user IDs to fetch. |
Returns |
---|
Name | Description |
---|
users
[]*api.User | A list of user record objects. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
count
int
REQUIRED | | The number of users to fetch. |
Returns |
---|
Name | Description |
---|
users
[]*api.User | A list of user record objects. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
usernames
[]string
REQUIRED | | An array of usernames to fetch. |
Returns |
---|
Name | Description |
---|
users
[]*api.User | A list of user record objects. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userIds
[]string
REQUIRED | | An array of user IDs to unban. |
Returns |
---|
Name | Description |
---|
error
error | An 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 |
---|
Name | Default | Description |
---|
expression
string
REQUIRED | | A valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight). |
timestamp
int
REQUIRED | | A time value expressed as UTC seconds. |
Returns |
---|
Name | Description |
---|
nextTs
int64 | The next UTC seconds timestamp (number) that matches the given CRON expression, and is immediately after the given timestamp. |
error
error | An 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 |
---|
Name | Default | Description |
---|
expression
string
REQUIRED | | A valid CRON expression in standard format, for example "0 0 * * *" (meaning at midnight). |
timestamp
int
REQUIRED | | A time value expressed as UTC seconds. |
Returns |
---|
Name | Description |
---|
prevTs
int64 | The previous UTC seconds timestamp (number) that matches the given CRON expression, and is immediately before the given timestamp. |
error
error | An 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 |
---|
Name | Default | Description |
---|
relPath
string
REQUIRED | | Relative path to the file to be read. |
Returns |
---|
Name | Description |
---|
fileRead
*os.File | The read file. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user to list wallet updates for. |
limit
int | 100 | Limit number of results. |
cursor
string
REQUIRED | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
runtimeItems
[]runtime.WalletLedgerItem | A Go slice containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
itemId
string
REQUIRED | | The ID of the wallet ledger item to update. |
metadata
map[string]interface
REQUIRED | | The new metadata to set on the wallet ledger item. |
Returns |
---|
Name | Description |
---|
updateWalletLedger
runtime.WalletLedgerItem | The updated wallet ledger item. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
updates
[]*runtime.WalletUpdate
REQUIRED | | The set of user wallet update operations to apply. |
updateLedger
bool
REQUIRED | false | Whether to record this update in the ledger. |
Returns |
---|
Name | Description |
---|
updateWallets
[]runtime.WalletUpdateResult | A list of wallet update results. |
error
error | An 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 |
---|
Name | Default | Description |
---|
ctx
context.Context
REQUIRED | | The context object represents information about the server and requester. |
userId
string
REQUIRED | | The ID of the user whose wallet to update. |
changeset
map[string]int
REQUIRED | | The set of wallet operations to apply. |
metadata
map[string]interface
REQUIRED | | Additional metadata to tag the wallet update with. |
updateLedger
bool
REQUIRED | false | Whether to record this update in the ledger. |
Returns |
---|
Name | Description |
---|
updatedValue
map | The updated wallet value. |
previousValue
map | The previous wallet value. |
error
error | An 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.")
}
|