函数参考
#
服务器内置的代码运行库包括一个模块,该模块具有实现各种逻辑和自定义行为的功能,使您能够根据客户端接收的输入定义权威代码和条件。在服务器框架基础文档中进一步了解详情。
本页面列出了 Nakama 中的所有函数及其参数,并提供了每个函数相应的代码示例。
如未阅读关于如何使用服务器框架的文档,请阅读。
Accounts
#
account_delete_id
#
Delete an account by user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | User ID for the account to be deleted. Must be valid UUID. |
recorded
bool | false | Whether to record this deletion in the database. By default this is set to false. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
| nk.account_delete_id("8f4d52c7-bf28-4fcf-8af2-1d4fcf685592", false)
|
account_export_id
#
Export account information for a specified user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local account_data = nk.account_export_id(user_id)
|
account_get_id
#
Fetch account information by user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | User ID to fetch information for. Must be valid UUID. |
Returns |
---|
Name | Description |
---|
account
table | All account information including wallet, device IDs and more. |
error
error | An optional error value if an error occurred. |
1
2
3
| local account = nk.account_get_id("8f4d52c7-bf28-4fcf-8af2-1d4fcf685592")
local wallet = account.wallet
nk.logger_info(string.format("Wallet is: %s", nk.json_encode(wallet)))
|
accounts_get_id
#
Fetch information for multiple accounts by user IDs.
Parameters |
---|
Name | Default | Description |
---|
userIds
table
REQUIRED | | Table of user IDs to fetch information for. Must be valid UUID. |
Returns |
---|
Name | Description |
---|
account
Table | Table of accounts. |
error
error | An optional error value if an error occurred. |
1
2
| local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local accounts = nk.accounts_get_id(user_ids)
|
account_update_id
#
Update an account by user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | User ID for which the information is to be updated. Must be valid UUID. |
metadata
table | | The metadata to update for this account. |
username
string | | Username to be set. Must be unique. Use null if it is not being updated. |
displayName
string | | Display name to be updated. Use null if it is not being updated. |
timezone
string | | Timezone to be updated. Use null if it is not being updated. |
location
string | | Location to be updated. Use null if it is not being updated. |
language
string | | Lang tag to be updated. Use null if it is not being updated. |
avatarUrl
string | | User's avatar URL. Use null 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
| local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521" -- Some user ID.
local metadata = {}
local username = ""
local display_name = nil
local timezone = nil
local location = nil
local language = nil
local avatar_url = nil
nk.account_update_id(user_id, metadata, username, display_name, timezone, location, language, avatar_url)
|
Authenticate
#
authenticate_apple
#
Authenticate user and create a session token using an Apple sign in token.
Parameters |
---|
Name | Default | Description |
---|
token
string
REQUIRED | | Apple sign in 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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_apple("some-oauth-access-token", "username", true)
|
authenticate_custom
#
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 |
---|
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 | 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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_custom("48656C6C6F20776F726C64", "username", true)
|
authenticate_device
#
Authenticate user and create a session token using a device identifier.
Parameters |
---|
Name | Default | Description |
---|
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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_device("48656C6C6F20776F726C64", "username", true)
|
authenticate_email
#
Authenticate user and create a session token using an email address and password.
Parameters |
---|
Name | Default | Description |
---|
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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_email("email@example.com", "48656C6C6F20776F726C64", "username", true)
|
authenticate_facebook
#
Authenticate user and create a session token using a Facebook account token.
Parameters |
---|
Name | Default | Description |
---|
token
string
REQUIRED | | Facebook OAuth or Limited Login (JWT) access token. |
import
bool | true | Whether to automatically import Facebook friends after authentication. |
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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_facebook("some-oauth-access-token", true, "username", true)
|
authenticate_facebook_instance_game
#
Authenticate user and create a session token using a Facebook Instant Game.
Parameters |
---|
Name | Default | Description |
---|
playerInfo
string
REQUIRED | | Facebook Player info. |
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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_facebook_instant_game("player-info", true, "username", true)
|
authenticate_game_center
#
Authenticate user and create a session token using Apple Game Center credentials.
Parameters |
---|
Name | Default | Description |
---|
playerId
string
REQUIRED | | PlayerId provided by GameCenter. |
bundleId
string
REQUIRED | | BundleId of your app on iTunesConnect. |
timestamp
number
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 | 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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_game_center(player_id, bundle_id, timestamp, salt, signature, public_key_url, username, create)
|
authenticate_google
#
Authenticate user and create a session token using a Google ID token.
Parameters |
---|
Name | Default | Description |
---|
token
string
REQUIRED | | Google OAuth access 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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_google("some-id-token", "username", true)
|
authenticate_steam
#
Authenticate user and create a session token using a Steam account token.
Parameters |
---|
Name | Default | Description |
---|
token
string
REQUIRED | | Steam token. |
username
string | | The user's username. If left empty, one is generated. |
import
bool | true | Whether to automatically import Steam friends after authentication. |
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. |
created
bool | Value indicating if this account was just created or already existed. |
error
error | An optional error value if an error occurred. |
1
| local user_id, username, created = nk.authenticate_steam("steam-token", "username", true)
|
authenticate_token_generate
#
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
number | | UTC time in seconds when the token must expire. Defaults to server configured expiry time. |
vars
table | | Extra information that will be bundled in the session token. |
Returns |
---|
Name | Description |
---|
token
string | The Nakama session token. |
validity
number | The period for which the token remains valid. |
error
error | An optional error value if an error occurred. |
1
2
| local token, exp = nk.authenticate_token_generate("user_id", "username")
nk.logger_info(("Access token: %q, valid for %q seconds"):format(token, exp))
|
link_apple
#
Link Apple authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_apple(user_id, "some-oauth-access-token")
|
link_custom
#
Link custom authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_custom(user_id, "48656C6C6F20776F726C64")
|
link_device
#
Link device authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_device(user_id, "22226C6C6F20776F726C22")
|
link_email
#
Link email authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_email(user_id, "email@example.com", "password")
|
link_facebook
#
Link Facebook authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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 | true | Whether to automatically import Facebook friends after authentication. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local import_friends = true
nk.link_facebook(user_id, "username", "some-oauth-access-token", import_friends)
|
link_facebook_instant_game
#
Link Facebook Instant Game authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be linked. |
playerInfo
string
REQUIRED | | Facebook player info. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local import_friends = true
nk.link_facebook_instant_game(user_id, "player-info", import_friends)
|
link_gamecenter
#
Link Apple Game Center authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local timestamp = 1
nk.link_gamecenter(user_id, "player_id", "bundle_id", timestamp, "salt", "signature", "public_key_url")
|
link_google
#
Link Google authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.link_google(user_id, "some-oauth_access_token")
|
link_steam
#
Link Steam authentication to a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be linked. |
username
string
REQUIRED | | If left empty, one is generated. |
token
string
REQUIRED | | Steam access token. |
importFriends
bool
REQUIRED | true | Whether to automatically import Steam friends after authentication. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local import_friends = true
nk.link_steam(user_id, "username", "some-oauth_access_token", import_friends)
|
unlink_apple
#
Unlink Apple authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string | | Apple sign in token. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_apple(user_id, "some-oauth-access-token")
|
unlink_custom
#
Unlink custom authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
customId
string | | Custom ID to be unlinked from the user. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_custom(user_id, "48656C6C6F20776F726C64")
|
unlink_device
#
Unlink device authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
deviceId
string
REQUIRED | | Device ID to be unlinked to the user. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_device(user_id, "22226C6C6F20776F726C22")
|
unlink_email
#
Unlink email authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
email
string | | Email to be unlinked from the user. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_email(user_id, "email@example.com")
|
unlink_facebook
#
Unlink Facebook authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string | | Facebook OAuth or Limited Login (JWT) access token. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_facebook(user_id, "username", "some-oauth-access-token")
|
unlink_facebook_instant_game
#
Unlink Facebook Instant Game authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
playerInfo
string | | Facebook player info. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_facebook_instant_game(user_id, "player-info")
|
unlink_game_center
#
Unlink Apple Game Center authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local timestamp = 1
nk.unlink_gamecenter(user_id, "player_id", "bundle_id", timestamp, "salt", "signature", "public_key_url")
|
unlink_google
#
Unlink Google authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string | | Google OAuth access token. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_google(user_id, "some-oauth_access_token")
|
unlink_steam
#
Unlink Steam authentication from a user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be unlinked. |
token
string | | Steam access token. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
nk.unlink_steam(user_id, "some-oauth_access_token")
|
Chat
#
channel_id_build
#
Create a channel identifier to be used in other runtime calls. Does not create a channel.
Parameters |
---|
Name | Default | Description |
---|
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
int
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
| -- Channel Id Build
local sender_id = "SenderId"
local target = "RoomName"
local channel_type = 1
|
channel_message_remove
#
Remove a message on a realtime chat channel.
Parameters |
---|
Name | Default | Description |
---|
channelId
string
REQUIRED | | The ID of the channel to send 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 to send this message as. If left empty, it will be assumed that it is a system message. |
persist
bool | true | Whether to record this message in the channel history. |
Returns |
---|
Name | Description |
---|
ack
table | Message removed ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'. |
error
error | An optional error value if an error occurred. |
1
2
3
| -- Channel Message Remove
local remove_ack = nk.channel_message_remove("<ChannelId>", "<MessageId>", "<SenderId>", "<SenderUsername>", true)
nk.logger_info("%q deleted at %q", remove_ack.messageId, remove_ack.createTime)
|
channel_message_send
#
Send a message on a realtime chat channel.
Parameters |
---|
Name | Default | Description |
---|
channelId
string
REQUIRED | | The ID of the channel to send the message on. |
content
table
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 | true | Whether to record this message in the channel history. |
Returns |
---|
Name | Description |
---|
ack
table | Message sent ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local content = {}
content["message"] = "hello"
local create_ack = nk.channel_message_send("<ChannelId>", content, "<SenderId>", "<SenderUsername>", true)
nk.logger_info("%q created at %q", create_ack.messageId, create_ack.createTime)
|
channel_messages_list
#
List messages from a realtime chat channel.
Parameters |
---|
Name | Default | Description |
---|
channelId
string
REQUIRED | | The ID of the channel to send the message on. |
limit
number | 100 | The number of messages to return per page. |
forward
bool | true | 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 |
---|
messages
table | Messages from the specified channel. |
nextCursor
string | Cursor for the next page of messages, if any. Will be set to "" or nil when fetching last available page. |
prevCursor
string | Cursor for the previous page of messages, if any. |
error
error | An optional error value if an error occurred. |
1
2
| -- Channel Messages List
local channel_id = "<ChannelId>"
|
channel_message_update
#
Update a message on a realtime chat channel.
Parameters |
---|
Name | Default | Description |
---|
channelId
string
REQUIRED | | The ID of the channel to send the message on. |
messageId
string
REQUIRED | | The ID of the message to update. |
content
table
REQUIRED | | Message content. Must be set. |
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 | true | Whether to record this message in the channel history. |
Returns |
---|
Name | Description |
---|
ack
table | Message updated ack containing the following variables: 'channelId', 'messageId', 'code', 'username', 'createTime', 'updateTime', and 'persistent'. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local content = {}
content["message"] = "hello"
local update_ack = nk.channel_message_update("<ChannelId>", "<MessageId>", content, "<SenderId>", "<SenderUsername>", true)
nk.logger_info("%q created at %q", update_ack.messageId, update_ack.createTime)
|
Events
#
event
#
Generate an event.
Parameters |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the event to be created. |
properties
table
REQUIRED | | A table of event properties. |
timestamp
int
REQUIRED | | Numeric UTC value of when event is created. |
external
bool | false | Whether the event is external. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local properties = { some = "property" }
local timestamp = 0
local external = false
nk.event(name, properties, timestamp, external)
|
Friends
#
friends_add
#
Add friends to a user.
Parameters |
---|
Name | Default | Description |
---|
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
table
REQUIRED | | The IDs of the users you want to add as friends. |
usernames
table
REQUIRED | | The usernames of the users you want to add as friends. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local username = "username"
local ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local usernames = {"newfriend1", "newfriend2"}
local friends = nk.friends_add(user_id, username, ids, usernames)
|
friends_block
#
Block friends for a user.
Parameters |
---|
Name | Default | Description |
---|
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
table
REQUIRED | | The IDs of the users you want to block as friends. |
usernames
table
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
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local username = "username"
local ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local usernames = {"blockedfriend1", "blockedfriend2"}
local friends = nk.friends_block(user_id, username, ids, usernames)
|
friends_delete
#
Delete friends from a user.
Parameters |
---|
Name | Default | Description |
---|
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
table
REQUIRED | | The IDs of the users you want to delete as friends. |
usernames
table
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
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local username = "username"
local ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
local usernames = {"exfriend1", "exfriend2"}
local friends = nk.friends_delete(user_id, username, ids, usernames)
|
friends_list
#
List all friends, invites, invited, and blocked which belong to a user.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The ID of the user whose friends, invites, invited, and blocked you want to list. |
limit
number | | The number of friends to retrieve in this page of results. No more than 100 limit allowed per result. |
state
number | | The state of the friendship with the user. If unspecified this returns friends in all states for the user. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
friends
table | 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
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local limit = 100
local state = nil
local cursor = nil
local friends = nk.friends_list(user_id, limit, state, cursor)
for _, m in ipairs(friends) do
-- States are: friend(0), invite_sent(1), invite_received(2), blocked(3)
local msg = string.format("Friend username %q has state %q", m.user.username, m.state)
nk.logger_info(msg)
end
|
friends_of_friends_list
#
List all friends, invites, invited, and blocked which belong to a user.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The ID of the user whose friends, invites, invited, and blocked you want to list. |
limit
number | | The number of friends to retrieve in this page of results. No more than 100 limit allowed per result. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
friendsOfFriends
table | The user information for users that are friends of 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
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local limit = 100
local cursor = nil
local friends = nk.friends_of_friends_list(user_id, limit, cursor)
|
Groups
#
group_create
#
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 |
---|
userId
string
REQUIRED | | Mandatory. The user ID to be associated as the group superadmin. |
name
string
REQUIRED | | Mandatory. 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
table | | Custom information to store for this group. Can be left empty as nil/null. |
maxCount
number | 100 | Maximum number of members to have in the group. |
Returns |
---|
Name | Description |
---|
createGroup
string | The ID 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
| local metadata = { -- Add whatever custom fields you want.
my_custom_field = "some value"
}
local user_id = "dcb891ea-a311-4681-9213-6741351c9994"
local creator_id = "dcb891ea-a311-4681-9213-6741351c9994"
local name = "Some unique group name"
local description = "My awesome group."
local lang = "en"
local open = true
local creator_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local avatar_url = "url://somelink"
local maxMemberCount = 100
nk.group_create(user_id, name, creator_id, lang, description, avatar_url, open, metadata, maxMemberCount)
|
group_delete
#
Delete a group.
Parameters |
---|
Name | Default | Description |
---|
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
| local group_id = "f00fa79a-750f-11e7-8626-0fb79f45ff97"
nk.group_delete(group_id)
|
groups_get_id
#
Fetch one or more groups by their ID.
Parameters |
---|
Name | Default | Description |
---|
groupIds
table
REQUIRED | | A list of strings of the IDs for the groups to get. |
Returns |
---|
Name | Description |
---|
getGroups
table | A table of groups with their fields. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
8
9
10
11
| local group_ids = {
"0BF154F1-F7D1-4AAA-A060-5FFED3CDB982",
"997C0D18-0B25-4AEC-8331-9255BD36665D"
}
local groups = nk.groups_get_id(group_ids)
for _, g in ipairs(groups) do
local msg = string.format("Group name %q with id %q", g.name, g.id)
nk.logger_info(msg)
end
|
groupsGetRandom
#
Fetch one or more groups randomly.
Parameters |
---|
Name | Default | Description |
---|
count
int
REQUIRED | | The number of groups to fetch. |
Returns |
---|
Name | Description |
---|
users
table | A list of group record objects. |
error
error | An optional error value if an error occurred. |
groups_list
#
Find groups based on the entered criteria.
Parameters |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | Search for groups that contain this value in their name. |
langTag
string | | Filter based upon the entered language tag. |
members
number
REQUIRED | | Search by number of group members. |
open
bool
REQUIRED | | Filter based on whether groups are Open or Closed. |
limit
number | 100 | 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 |
---|
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
| local group_name = "Heroic"
local lang_tag = "en"
local members = 10
local open = true
local limit = 100
local groups = nk.groups_list(group_name, lang_tag, members, open, limit)
for i, group in ipairs(groups) do
nk.logger_info(string.format("ID: %q - can enter? %q", group.id, group.can_enter))
end
|
group_update
#
Update a group with various configuration settings. The group which is updated can change some or all of its fields.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group to update. |
userId
string | | User ID calling the update operation for permission checking. Set as nil to enact the changes as the system user. |
name
string | | Group name, can be empty if not changed. |
creatorId
string | | The user ID to be associated as creator. Can be empty if not changed. |
langTag
string | | Group language. Empty if not updated. |
description
string | | Group description, can be left empty if not updated. |
avatarUrl
string | | URL to the group avatar, can be left empty if not updated. |
open
bool | | Whether the group is for anyone to join or not. |
metadata
table | | Custom information to store for this group. Use nil if field is not being updated. |
maxCount
number | | 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
| local metadata = {
some_field = "some value"
}
group_id = "f00fa79a-750f-11e7-8626-0fb79f45ff97"
description = "An updated description."
nk.group_update(group_id, nil, "", "", "", description, "", nil, metadata, 0)
|
group_user_join
#
Join a group for a particular user.
Parameters |
---|
Name | Default | Description |
---|
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
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local username = "myusername"
nk.group_user_join(group_id, user_id, username)
|
group_user_leave
#
Leave a group for a particular user.
Parameters |
---|
Name | Default | Description |
---|
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
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local username = "myusername"
nk.group_user_leave(group_id, user_id, username)
|
group_users_add
#
Add users to a group.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group to add users to. |
userIds
table
REQUIRED | | Table 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
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
nk.group_users_add(group_id, user_ids)
|
group_users_ban
#
Ban users from a group.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group to ban users from. |
userIds
table
REQUIRED | | Table 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
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
nk.group_users_ban(group_id, user_ids)
|
group_users_demote
#
Demote users in a group.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group whose members are being demoted. |
userIds
table
REQUIRED | | Table of user IDs to demote. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
nk.group_users_demote(group_id, user_ids)
|
group_users_kick
#
Kick users from a group.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group to kick users from. |
userIds
table
REQUIRED | | Table of user IDs to kick. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
nk.group_users_kick(group_id, user_ids)
|
group_users_list
#
List all members, admins and superadmins which belong to a group. This also list incoming join requests.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group to list members for. |
limit
int | 100 | The maximum number of entries in the listing. |
state
int | null | The state of the user within the group. If unspecified this returns users in all states. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
groupUsers
table | The user information for members, admins and superadmins for the group. Also users who sent a join request. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local members = nk.group_users_list(group_id)
for _, m in ipairs(members) do
local msg = string.format("Member username %q has state %q", m.user.username, m.state)
nk.logger_info(msg)
end
|
Promote users in a group.
Parameters |
---|
Name | Default | Description |
---|
groupId
string
REQUIRED | | The ID of the group whose members are being promoted. |
userIds
table
REQUIRED | | Table of user IDs to promote. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
| local group_id = "a1aafe16-7540-11e7-9738-13777fcc7cd8"
local user_ids = {"9a51cf3a-2377-11eb-b713-e7d403afe081", "a042c19c-2377-11eb-b7c1-cfafae11cfbc"}
nk.group_users_promote(group_id, user_ids)
|
user_groups_list
#
List all groups which a user belongs to and whether they've been accepted or if it's an invite.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The ID of the user to list groups for. |
Returns |
---|
Name | Description |
---|
userGroups
table | A table of groups with their fields. |
cursor
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
| local user_id = "64ef6cb0-7512-11e7-9e52-d7789d80b70b"
local groups = nk.user_groups_list(user_id)
for _, g in ipairs(groups) do
local msg = string.format("User has state %q in group %q", g.state, g.group.name)
nk.logger_info(msg)
end
|
Hooks
#
register_leaderboard_reset
#
Registers a function to be run when a leaderboard resets.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each leaderboard reset. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local function my_func(ctx, leaderboard, reset)
-- Custom logic
end
nk.register_leaderboard_reset(my_func)
|
register_matchmaker_matched
#
Registers a function that will be called when matchmaking finds opponents.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each matchmake completion. |
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
25
26
27
28
| local function matchmaker_matched(context, matched_users)
for _, m in ipairs(matched_users) do
nk.logger_info(m.presence["user_id"])
nk.logger_info(m.presence["session_id"])
nk.logger_info(m.presence["username"])
nk.logger_info(m.presence["node"])
for _, p in ipairs(m.properties) do
nk.logger_info(p)
end
end
if #matched_users ~= 2 then
return nil
end
if matched_users[1].properties["mode"] ~= "authoritative" then
return nil
end
if matched_users[2].properties["mode"] ~= "authoritative" then
return nil
end
return nk.match_create("match", { debug = true, expected_users = matched_users })
end
nk.register_matchmaker_matched(matchmaker_matched)
|
register_req_after
#
Register a function with the server which will be executed after every non-realtime message as specified while registering the function.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each message. |
id
string
REQUIRED | | The specific message name to execute the function after. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local function my_func(context, payload)
-- Run some code.
end
nk.register_req_after(my_func, "FriendsAdd")
|
register_req_before
#
Register a function with the server which will be executed before any non-realtime message with the specified message name.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each message. |
id
string
REQUIRED | | The specific message name to execute the function after. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local function my_func(context, payload)
-- Run some code.
return payload -- Important!
end
nk.register_req_before(my_func, "FriendsAdd")
|
register_rpc
#
Registers a function for use with client RPC to the server.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each RPC message. |
id
string
REQUIRED | | The unique identifier used to register the function for RPC. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local function my_func(context, payload)
-- Run some code.
return payload
end
nk.register_rpc(my_func, "my_func_id")
|
register_rt_after
#
Register a function with the server which will be executed after every realtime message with the specified message name.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each msgname message. |
id
string
REQUIRED | | The specific message name to execute the function after. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local function my_func(context, payload)
-- Run some code.
end
nk.register_rt_after(my_func, "ChannelJoin")
|
register_rt_before
#
Register a function with the server which will be executed before any realtime message with the specified message name.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each msgname message. The function should pass the payload input back as a return argument so the pipeline can continue to execute the standard logic. |
id
string
REQUIRED | | The specific message name to execute the function after. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local function my_func(context, payload)
-- Run some code.
return payload -- Important!
end
nk.register_rt_before(my_func, "ChannelJoin")
|
register_shutdown
#
Registers a function to be run when the server received a shutdown signal. The function only fires if grace_period_sec > 0.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on server shutdown. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
|
local function my_func(ctx)
-- Custom logic
end
nk.register_shutdown(my_func)
|
register_tournament_end
#
Registers a function to be run when a tournament ends.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each tournament end. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local function my_func(ctx, leaderboard, reset)
-- Custom logic
end
nk.register_tournament_end(my_func)
|
register_tournament_reset
#
Registers a function to be run when a tournament resets.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed on each tournament reset. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local function my_func(ctx, leaderboard, reset)
-- Custom logic
end
nk.register_tournament_reset(my_func)
|
run_once
#
Registers a function to be run only once.
Parameters |
---|
Name | Default | Description |
---|
fn
function
REQUIRED | | A function reference which will be executed only once. |
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
| local function insert_user(context)
-- This is to create a system ID that cannot be used via a client.
local system_id = context.env["SYSTEM_ID"]
nk.sql_exec([[
INSERT INTO users (id, username)
VALUES ($1, $2)
ON CONFLICT (id) DO NOTHING
]], { system_id, "system_id" })
end
nk.run_once(insert_user)
|
Leaderboards
#
leaderboard_create
#
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 |
---|
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 | | The sort order for records in the leaderboard. Possible values are "asc" or "desc". |
operator
string | | The operator that determines how scores behave when submitted; possible values are "best", "set", or "incr". |
resetSchedule
string | | 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
table | | The metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game. |
enableRanks
bool | false | 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local authoritative = false
local sort = "desc"
local operator = "best"
local reset = "0 0 * * 1"
local metadata = {
weather_conditions = "rain"
}
local enable_ranks = false
nk.leaderboard_create(id, authoritative, sort, operator, reset, metadata, enable_ranks)
|
leaderboard_delete
#
Delete a leaderboard and all scores that belong to it.
Parameters |
---|
Name | Default | Description |
---|
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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
nk.leaderboard_delete(id)
|
leaderboard_list
#
Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.
Parameters |
---|
Name | Default | Description |
---|
limit
number | 10 | 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
table | 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
| local limit = 100 -- Number to list per page.
local leaderboards = nk.leaderboard_list(limit)
for i, leaderboard in ipairs(leaderboards) do
nk.logger_info(string.format("ID: %q - can enter? %q", leaderboard.id, leaderboard.can_enter))
end
|
leaderboard_ranks_disable
#
Disable a leaderboard rank cache freeing its allocated resources. If already disabled is a NOOP.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The leaderboard id. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
nk.leaderboard_ranks_disable(id)
|
leaderboard_record_delete
#
Remove an owner's record from a leaderboard, if one exists.
Parameters |
---|
Name | Default | Description |
---|
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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
nk.leaderboard_record_delete(id, owner)
|
leaderboard_records_haystack
#
Fetch the list of leaderboard records around the owner.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The ID of the leaderboard to list records for. |
ownerId
string
REQUIRED | | The owner ID around which to show records. |
limit
number | 10 | 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
number | 0 | Time since epoch in seconds. Must be greater than 0. |
Returns |
---|
Name | Description |
---|
records
table | A list of leaderboard records. |
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). 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
nk.leaderboard_records_haystack(id, owner, 10)
|
leaderboard_records_list
#
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 |
---|
id
string
REQUIRED | | The unique identifier for the leaderboard to list. Mandatory field. |
owners
table
REQUIRED | | List of owners to filter to. |
limit
number | | 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 | | 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
table | A page of leaderboard records. |
ownerRecords
table | 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). Will be set to "" or nil when fetching last available page. |
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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owners = {}
local limit = 10
local cursor = ""
local override_expiry = 3600
local records, owner_records, next_cursor, prev_cursor = nk.leaderboard_records_list(id, owners, limit, cursor, override_expiry)
|
leaderboard_records_list_cursor_from_rank
#
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
number
REQUIRED | | The rank to start listing leaderboard records from. |
overrideExpiry
number | | 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local rank = 1
local override_expiry = 0
local cursor = nk.leaderboard_records_list_cursor_from_rank(id, rank, override_expiry)
|
leaderboard_record_write
#
Use the preconfigured operator for the given leaderboard to submit a score for a particular user.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The unique identifier for the leaderboard to submit to. |
owner
string
REQUIRED | | The owner of this score submission. |
username
string | | The owner username of this score submission, if it's a user. |
score
number | 0 | The score to submit. |
subscore
number | 0 | A secondary subscore parameter for the submission. |
metadata
table | | The metadata you want associated to this submission. Some good examples are weather conditions for a racing game. |
Returns |
---|
Name | Description |
---|
record
table | 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
| local metadata = {
weather_conditions = "rain"
}
local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local username = "02ebb2c8"
local score = 10
local subscore = 0
nk.leaderboard_record_write(id, owner, username, score, subscore, metadata)
|
leaderboards_get_id
#
Fetch one or more leaderboards by ID.
Parameters |
---|
Name | Default | Description |
---|
ids
table
REQUIRED | | The table array of leaderboard ids. |
Returns |
---|
Name | Description |
---|
leaderboards
table | The leaderboard records according to ID. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local leaderboard_ids = {
"3ea5608a-43c3-11e7-90f9-7b9397165f34",
"447524be-43c3-11e7-af09-3f7172f05936"
}
local leaderboards = nk.leaderboards_get_id(leaderboard_ids)
|
Logger
#
logger_debug
#
Write a DEBUG level message to the server logs.
Parameters |
---|
Name | Default | Description |
---|
message
string
REQUIRED | | The message to write to server logs with DEBUG level severity. |
vars
vars
REQUIRED | | Variables to replace placeholders in message. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local message = string.format("%q - %q", "hello", "world")
nk.logger_debug(message)
|
logger_error
#
Write an ERROR level message to the server logs.
Parameters |
---|
Name | Default | Description |
---|
message
string
REQUIRED | | The message to write to server logs with ERROR level severity. |
vars
vars
REQUIRED | | Variables to replace placeholders in message. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local message = string.format("%q - %q", "hello", "world")
nk.logger_error(message)
|
logger_info
#
Write an INFO level message to the server logs.
Parameters |
---|
Name | Default | Description |
---|
message
string
REQUIRED | | The message to write to server logs with INFO level severity. |
vars
vars
REQUIRED | | Variables to replace placeholders in message. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local message = string.format("%q - %q", "hello", "world")
nk.logger_info(message)
|
logger_warn
#
Write a WARN level message to the server logs.
Parameters |
---|
Name | Default | Description |
---|
message
string
REQUIRED | | The message to write to server logs with WARN level severity. |
vars
vars
REQUIRED | | Variables to replace placeholders in message. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local message = string.format("%q - %q", "hello", "world")
nk.logger_warn(message)
|
Matches
#
match_create
#
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 |
---|
module
string
REQUIRED | | The name of an available runtime module that will be responsible for the match. This was registered in InitModule. |
params
any | | 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
| -- Assumes you've registered a runtime module with a path of "some/folder/module.lua".
local module = "some.folder.module"
local params = {
some = "data"
}
local match_id = nk.match_create(module, params)
|
match_get
#
Get information on a running match.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The ID of the match to fetch. |
Returns |
---|
Name | Description |
---|
match
table | Information for the running match. |
error
error | An optional error value if an error occurred. |
1
2
| local match_id = "52f02f3e-5b48-11eb-b182-0f5058adfcc6"
local match_data = nk.match_get(match_id)
|
match_list
#
List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.
Parameters |
---|
Name | Default | Description |
---|
limit
number | 1 | The maximum number of matches to list. |
authoritative
bool | nil | Set true to only return authoritative matches, false to only return relayed matches and nil to return both. |
label
string | | A label to filter authoritative matches by. Default "" means any label matches. |
minSize
number | | Inclusive lower limit of current match participants. |
maxSize
number | | Inclusive upper limit of current match participants. |
query
string | | Additional query parameters to shortlist matches. |
Returns |
---|
Name | Description |
---|
match
table | A table 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
| -- List at most 10 matches, not authoritative, and that
-- have between 2 and 4 players currently participating.
local limit = 10
local authoritative = false
local label = nil
local min_size = 2
local max_size = 4
local matches = nk.match_list(limit, authoritative, label, min_size, max_size)
for _, m in ipairs(matches) do
local message = string.format("Found match with id: %q", m.match_id)
nk.logger_info(message)
end
|
match_signal
#
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 |
---|
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 |
---|
state
any | An (optionally) updated state. May be any non-nil value, or nil to end the match. |
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
| local match_id = "52f02f3e-5b48-11eb-b182-0f5058adfcc6"
local data = "<SignalData>"
local response = nk.match_signal(match_id, data)
|
Metrics
#
metrics_counter_add
#
Add a custom metrics counter.
Parameters |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the custom metrics counter. |
tags
table
REQUIRED | | The metrics tags associated with this counter. |
delta
number
REQUIRED | | An integer value to update this metric with. |
Returns |
---|
Name | Description |
---|
1
2
3
4
5
6
7
| local name = "metricName"
local tags = {
-- Metrics tags for this counter.
}
local delta = 100
nk.metrics_counter_add(name, tags, delta)
|
metrics_gauge_set
#
Add a custom metrics gauge.
Parameters |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the custom metrics gauge. |
tags
table
REQUIRED | | The metrics tags associated with this gauge. |
value
number
REQUIRED | | A value to update this metric with. |
Returns |
---|
Name | Description |
---|
1
2
3
4
5
6
7
| local name = "metricName"
local tags = {
-- Metrics tags for this counter.
}
local value = 3.14
nk.metrics_gauge_set(name, tags, value)
|
metrics_timer_record
#
Add a custom metrics timer.
Parameters |
---|
Name | Default | Description |
---|
name
string
REQUIRED | | The name of the custom metrics timer. |
tags
table
REQUIRED | | The metrics tags associated with this timer. |
value
number
REQUIRED | | An integer value to update this metric with (in nanoseconds). |
Returns |
---|
Name | Description |
---|
1
2
3
4
5
6
7
| local name = "metricName"
local tags = {
-- Metrics tags for this counter.
}
local value = 100000000000
nk.metrics_timer_record(name, tags, value)
|
Notifications
#
notifications_delete
#
Delete one or more in-app notifications.
Parameters |
---|
Name | Default | Description |
---|
notifications
table
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
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local notification_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local notifications = {user_id = user_id, notification_id = notification_id}
nk.notifications_delete(notifications)
|
notifications_delete_id
#
Delete notifications by their id.
Parameters |
---|
Name | Default | Description |
---|
ids
table
REQUIRED | | A list of notification ids. |
userID
string
REQUIRED | | Optional userID to scope deletions to that user only. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local notification_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local notifications = {notification_id}
nk.notifications_delete_id(notifications, user_id)
|
notification_send
#
Send one in-app notification to a user.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID of the user to be sent the notification. |
subject
string
REQUIRED | | Notification subject. |
content
table
REQUIRED | | Notification content. Must be set but can be an empty table. |
code
number
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 | 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
11
12
| local subject = "You've unlocked level 100!"
local content = {
reward_coins = 1000
}
local receiver_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local sender_id = "dcb891ea-a311-4681-9213-6741351c9994"
local code = 101
local persistent = true
nk.notification_send(receiver_id, subject, content, code, sender_id, persistent)
|
notification_send_all
#
Send an in-app notification to all users.
Parameters |
---|
Name | Default | Description |
---|
subject
string
REQUIRED | | Notification subject. |
content
table
REQUIRED | | Notification content. Must be set but can be an empty table. |
code
number
REQUIRED | | Notification code to use. Must be greater than or equal to 0. |
persistent
bool | 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
| local subject = "You've unlocked level 100!"
local content = {
reward_coins = 1000
}
local code = 101
local persistent = true
nk.notification_send_all(subject, content, code, persistent)
|
notifications_get_id
#
Get notifications by their id.
Parameters |
---|
Name | Default | Description |
---|
ids
table
REQUIRED | | A list of notification ids. |
userID
string
REQUIRED | | Optional userID to scope results to that user only. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local notification_id = "9a51cf3a-2377-11eb-b713-e7d403afe081"
local notifications = {notification_id}
nk.notifications_get_id(notifications, user_id)
|
notifications_list
#
List notifications by user id.
Parameters |
---|
Name | Default | Description |
---|
userID
string
REQUIRED | | Optional userID to scope results to that user only. |
limit
int
REQUIRED | 100 | Limit number of results. Must be a value between 1 and 1000. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
notifications
table | A list of notifications. |
cursor
string | A cursor to fetch the next page of results. |
error
error | An optional error value if an error occurred. |
1
2
3
4
| local user_id = "b1aafe16-7540-11e7-9738-13777fcc7cd8"
local limit = 20
local notifications = nk.notifications_list(userId, limit)
|
notifications_send
#
Send one or more in-app notifications to a user.
Parameters |
---|
Name | Default | Description |
---|
notifications
table
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
| local subject = "You've unlocked level 100!"
local content = {
reward_coins = 1000
}
local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c" -- who to send
local sender_id = "dcb891ea-a311-4681-9213-6741351c9994" -- who the message if from
local code = 101
local new_notifications = {
{
subject = subject,
content = content,
sender_id = sender_id,
user_id = user_id,
code = code,
persistent = true
}
}
nk.notifications_send(new_notifications)
|
Purchases
#
purchase_get_by_transaction_id
#
Look up a purchase receipt by transaction ID.
Parameters |
---|
Name | Default | Description |
---|
transactionId
string
REQUIRED | | Transaction ID of the purchase to look up. |
Returns |
---|
Name | Description |
---|
purchase
table | A validated purchase and its owner. |
error
error | An optional error value if an error occurred. |
1
2
| local transaction_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local purchases = nk.purchase_get_by_transaction_id(transaction_id)
|
purchases_list
#
List stored validated purchase receipts.
Parameters |
---|
Name | Default | Description |
---|
userId
string | | Filter by user ID. Can be an empty string to list purchases for all users. |
limit
number | 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
table | 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
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local purchases = nk.purchases_list(user_id)
|
purchase_validate_apple
#
Validates and stores the purchases present in an Apple App Store Receipt.
Parameters |
---|
Name | Default | Description |
---|
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 | true | 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
table | 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
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = "<base64-receipt-data>"
local validation = nk.purchase_validate_apple(user_id, receipt)
|
purchase_validate_facebook_instant
#
Validates and stores a purchase receipt from the Facebook Instant Games.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
signedRequest
string
REQUIRED | | The Facebook Instant signedRequest receipt data. |
persist
bool | true | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
Returns |
---|
Name | Description |
---|
validation
table | 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
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local signed_request = "<signed_request-data>"
local validation = nk.purchase_validate_facebook_instant(user_id, signed_request)
|
purchase_validate_google
#
Validates and stores a purchase receipt from the Google Play Store.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | JSON encoded Google receipt. |
persist
bool | true | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
clientEmailOverride
string | | Override the iap.google.client_email provided in your configuration. |
privateKeyOverride
string | | Override the iap.google.private_key provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
table | 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
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local 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":".."}}'
local validation = nk.purchase_validate_google(user_id, receipt)
|
purchase_validate_huawei
#
Validates and stores a purchase receipt from the Huawei App Gallery.
Parameters |
---|
Name | Default | Description |
---|
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 | true | Persist the purchase so that seenBefore can be computed to protect against replay attacks. |
Returns |
---|
Name | Description |
---|
validation
table | 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
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = "<receipt-data>"
local signature = "<signature-data>"
local validation = nk.purchase_validate_huawei(user_id, receipt, signature)
|
Satori
#
getSatori
#
Get the Satori client.
Parameters |
---|
Name | Default | Description |
---|
Returns |
---|
Name | Description |
---|
satori
table | The satori client. |
error
error | An optional error value if an error occurred. |
1
| local satori = nk.get_satori()
|
satoriAuthenticate
#
Create a new identity.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
defaultProperties
table | nil | Default properties. |
customProperties
table | nil | Custom properties. |
ip
string
REQUIRED | | Ip address. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
| local userId = "user-id"
satori.authenticate(userId)
|
satoriEventsPublish
#
Publish an event.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
events
table
REQUIRED | | An array of events to publish. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
satoriExperimentsList
#
List experiments.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
names
table | | Optional list of experiment names to filter. |
Returns |
---|
Name | Description |
---|
experiments
table | The experiment list. |
error
error | An optional error value if an error occurred. |
1
| local experiments = satori.experiments_list("identityId", { "experimentName1", "experimentName2" })
|
satoriFlagsList
#
List flags.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
names
table | | Optional list of flag names to filter. |
Returns |
---|
Name | Description |
---|
flags
table | The flag list. |
error
error | An optional error value if an error occurred. |
1
| local flags = satori.flags_list("identityId", { "flagName1", "flagName2" })
|
satoriLiveEventsList
#
List live events.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
names
table | | Optional list of live event names to filter. |
Returns |
---|
Name | Description |
---|
liveEvents
table | The live event list. |
error
error | An optional error value if an error occurred. |
1
| local liveEvents = satori.live_events_list("identityId", { "liveEventName1", "liveEventName2" })
|
satoriMessageDelete
#
Delete message.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
messageId
string
REQUIRED | | The identifier of the message. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
| satori.message_delete("identityId", "messageId")
|
satoriMessagesList
#
List messages.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
limit
int | 100 | The max number of messages to return. |
forward
bool | true | True if listing should be older messages to newer, false if reverse. |
cursor
string | | A pagination cursor, if any. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
| local limit = 20
local forward = true
local messages = satori.messages_list("identityId", limit, forward)
|
satoriMessageUpdate
#
Update message.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
messageId
string
REQUIRED | | The identifier of the message. |
readTime
string
REQUIRED | | The time the message was read at the client. |
consumeTime
string
REQUIRED | | The time the message was consumed by the identity. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
| satori.message_update("identityId", "<readTime>", "<consumeTime>")
|
satoriPropertiesGet
#
Get identity properties.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
| local properties = satori.properties_get("identityId")
|
satoriPropertiesUpdate
#
Update identity properties.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The identifier of the identity. |
properties
table
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
| satori.properties_update("identityId", {
["default"] = {
["language"] = "japanese"
},
["custom"] = {
["customProperty"] = "someValue"
}
})
|
Sessions
#
session_disconnect
#
Disconnect a session.
Parameters |
---|
Name | Default | Description |
---|
sessionId
string
REQUIRED | | The ID of the session to be disconnected. |
reason
[]runtime.PresenceReason
REQUIRED | | The reason for the session disconnect. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
| local session_id = "085f7e38-5f15-4147-80e0-9f75bec47b89"
local reason = 0
nk.session_disconnect(session_id, reason)
|
session_logout
#
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
REQUIRED | | The current session authentication token. |
refreshToken
string
REQUIRED | | The current session refresh token. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local token = "<AuthToken>"
local refresh_token = "<RefreshToken>"
nk.session_logout(user_id, token, refresh_token)
|
Storage
#
register_storage_index
#
Create a new storage index.
Parameters |
---|
Name | Default | Description |
---|
indexName
string
REQUIRED | | Name of the index to list entries from. |
collection
string
REQUIRED | | Collection of storage engine to index objects from. |
key
string
REQUIRED | | Key of storage objects to index. Set to empty string to index all objects of collection. |
fields
table
REQUIRED | | A table of strings with the keys of the storage object whose values are to be indexed. |
sortableFields
table | | A table of strings with the keys of the storage object whose values are to be sortable. The keys must exist within the previously specified fields to be indexed. |
maxEntries
int
REQUIRED | | Maximum number of entries kept in the index. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
| local name = "IndexName"
local collection = "CollectionName"
local key = "KeyName"
local fields = {"field1", "field2"} -- Only objects containing any of these keys and respective values are indexed.
local maxEntries = 1000
local err = nk.register_storage_index(name, collection, key, fields, maxEntries)
|
register_storage_index_filter
#
List storage index entries
Parameters |
---|
Name | Default | Description |
---|
indexName
string
REQUIRED | | Name of the index to register filter function. |
fn
function
REQUIRED | | A function reference which will be executed on each storage object to be written that is a candidate for the index. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
| local name = "index_name"
function indexFilter(context, logger, nk, storageWrite)
-- Inspect object to decide if it should be inserted or tentatively deleted.
return true
end
local err = nk.register_storage_index_filter(name, indexFilter)
|
storage_delete
#
Remove one or more objects by their collection/keyname and optional user.
Parameters |
---|
Name | Default | Description |
---|
objectIds
table
REQUIRED | | A list 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
| local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local friend_user_id = "8d98ee3f-8c9f-42c5-b6c9-c8f79ad1b820"
local object_ids = {
{ collection = "save", key = "save1", user_id = user_id },
{ collection = "save", key = "save2", user_id = user_id },
{ collection = "public", key = "progress", user_id = friend_user_id }
}
nk.storage_delete(object_ids)
|
storage_index_list
#
List storage index entries
Parameters |
---|
Name | Default | Description |
---|
indexName
string
REQUIRED | | Name of the index to list entries from. |
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. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. |
Returns |
---|
Name | Description |
---|
objects
table | A list of storage objects. |
objects
string | A cursor, if there's a next page of results, nil otherwise. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local name = "index_name"
local query = "+field1:1 field2:foo"
local limit = 10
local err = nk.storage_index_list(name, query, limit)
|
storage_list
#
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 |
---|
userId
string
REQUIRED | | User ID to list records for or "" (empty string) | void for public records. |
collection
string
REQUIRED | | Collection to list data from. |
limit
number | 100 | Limit number of records retrieved. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
callerId
string | | User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permission checks are bypassed. |
Returns |
---|
Name | Description |
---|
objects
table | A list of storage objects. |
cursor
string | Pagination cursor. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
| local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local records = nk.storage_list(user_id, "collection", 10, "")
for _, r in ipairs(records) do
local m = string.format("read: %q, write: %q, value: %q", r.permission_read, r.permission_write, r.value)
nk.logger_info(m)
end
|
storage_read
#
Fetch one or more records by their bucket/collection/keyname and optional user.
Parameters |
---|
Name | Default | Description |
---|
objectIds
table
REQUIRED | | A table of object identifiers to be fetched. |
Returns |
---|
Name | Description |
---|
objects
table | 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
| local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local object_ids = {
{ collection = "save", key = "save1", user_id = user_id },
{ collection = "save", key = "save2", user_id = user_id },
{ collection = "save", key = "save3", user_id = user_id }
}
local objects = nk.storage_read(object_ids)
for _, r in ipairs(objects) do
local message = string.format("read: %q, write: %q, value: %q", r.permission_read, r.permission_write, r.value)
nk.logger_info(message)
end
|
storage_write
#
Write one or more objects by their collection/keyname and optional user.
Parameters |
---|
Name | Default | Description |
---|
objectIds
table
REQUIRED | | A table of object identifiers to be written. |
Returns |
---|
Name | Description |
---|
acks
table | 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
| local user_id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local new_objects = {
{ collection = "save", key = "save1", user_id = user_id, value = {} },
{ collection = "save", key = "save2", user_id = user_id, value = {} },
{ collection = "save", key = "save3", user_id = user_id, value = {}, permission_read = 2, permission_write = 1 },
{ collection = "save", key = "save3", user_id = user_id, value = {}, version="*", permission_read = 1, permission_write = 1 }
}
nk.storage_write(new_objects)
|
Streams
#
stream_close
#
Close a stream and remove all presences on it.
Parameters |
---|
Name | Default | Description |
---|
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
8
| local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
nk.stream_close(stream_obj)
|
stream_count
#
Get a count of stream presences.
Parameters |
---|
Name | Default | Description |
---|
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
Returns |
---|
Name | Description |
---|
countByStream
number | Number of current stream presences. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
8
| local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local count = nk.stream_count(stream_obj)
|
stream_send
#
Send data to presences on a stream.
Parameters |
---|
Name | Default | Description |
---|
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
data
string
REQUIRED | | The data to send. |
presences
table
REQUIRED | | Table of presences to receive the sent data. If not set, will be sent to all presences. |
reliable
bool
REQUIRED | true | 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
6
7
8
9
10
11
12
| local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local data = "<Data>"
local presences = {} -- table of presences to send the data to
local reliable = true
nk.stream_send(stream_obj, data, presences, reliable)
|
stream_send_raw
#
Send a message to presences on a stream.
Parameters |
---|
Name | Default | Description |
---|
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
msg
REQUIRED | | The message to send. |
presences
table
REQUIRED | | Table of presences to receive the sent data. If not set, will be sent to all presences. |
reliable
bool
REQUIRED | true | 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
6
7
8
9
10
11
12
| local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local data = {} -- table that conforms to a Go &rtapi.Envelope object
local presences = {} -- table of presences to send the data to
local reliable = true
nk.stream_send_raw(stream_obj, data, presences, reliable)
|
stream_user_get
#
Retreive a stream presence and metadata by user ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to fetch information for. |
sessionId
string
REQUIRED | | The current session ID for the user. |
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
Returns |
---|
Name | Description |
---|
meta
table | 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
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"
local stream_obj = {
mode = 0,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local user = nk.stream_user_get(user_id, session_id, stream_obj)
|
stream_user_join
#
Add a user to a stream.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be added. |
sessionId
string
REQUIRED | | The current session ID for the user. |
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
hidden
bool | false | Whether the user will be marked as hidden. |
persistence
bool | true | Whether message data should be stored in the database. |
status
string | | 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
9
10
11
12
13
14
15
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"
local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local hidden = false
local persistence = true
local status = ""
local success = nk.stream_user_join(user_id, session_id, stream_obj, hidden, persistence, status)
|
stream_user_kick
#
Kick user(s) from a stream.
Parameters |
---|
Name | Default | Description |
---|
presence
table
REQUIRED | | The presence(s) to be kicked. |
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
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
| local presence_obj = {
user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed",
node = "<Node>"
}
local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
nk.stream_user_kick(presence_obj, stream_obj)
|
stream_user_leave
#
Remove a user from a stream.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be removed. |
sessionId
string
REQUIRED | | The current session ID for the user. |
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
8
9
10
11
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"
local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
nk.stream_user_leave(user_id, session_id, stream_obj)
|
stream_user_list
#
List all users currently online and connected to a stream.
Parameters |
---|
Name | Default | Description |
---|
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
includeHidden
bool | true | Include stream presences marked as hidden in the results. |
includeNotHidden
bool | true | Include stream presences not marked as hidden in the results. |
Returns |
---|
Name | Description |
---|
presences
table | Table 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
10
11
| local stream_obj = {
mode = 0,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local include_hidden = true
local include_not_hidden = true
local presences = nk.stream_user_list(stream_obj, include_hidden, include_not_hidden)
|
stream_user_update
#
Update a stream user by ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID to be updated. |
sessionId
string
REQUIRED | | The current session ID for the user. |
stream
table
REQUIRED | | A stream object consisting of a `mode` (int), `subject` (string), `descriptor` (string) and `label` (string). |
hidden
bool | false | Whether the user will be marked as hidden. |
persistence
bool | true | Whether message data should be stored in the database. |
status
string | | 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
12
13
14
15
| local user_id = "87fc43cf-16f1-4852-8fd3-12c07caccf7e"
local session_id = "4fda79f0-cc13-4e9c-91ed-f1294f6731ed"
local stream_obj = {
mode = 4,
subject = "87fc43cf-16f1-4852-8fd3-12c07caccf7e",
subcontext = "085f7e38-5f15-4147-80e0-9f75bec47b89",
label = ""
}
local hidden = false
local persistence = true
local status = "Updated status"
local success = nk.stream_user_update(user_id, session_id, stream_obj, hidden, persistence, status)
|
Subscriptions
#
subscription_get_by_product_id
#
Look up a subscription by product ID.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID of the subscription owner. |
productId
string
REQUIRED | | Transaction ID of the purchase to look up. |
Returns |
---|
Name | Description |
---|
purchase
table | A validated purchase and its owner. |
error
error | An optional error value if an error occurred. |
1
2
3
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local product_id = "subscriptionId"
local subscriptions = nk.subscription_get_by_product_id(user_id, product_id)
|
subscriptions_list
#
List stored validated subscription receipts.
Parameters |
---|
Name | Default | Description |
---|
userId
string | | Filter by user ID. Can be an empty string to list subscriptions for all users. |
limit
number | 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
table | 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
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local subscriptions = nk.subscriptions_list(user_id)
|
subscription_validate_apple
#
Validates and stores the subscription present in an Apple App Store Receipt.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | Base-64 encoded receipt data returned by the subscription operation itself. |
persist
bool | true | Persist the subscription. |
passwordOverride
string | | Override the iap.apple.shared_password provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
table | The resulting successfully validated subscriptions. |
error
error | An optional error value if an error occurred. |
1
2
3
4
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local receipt = "<base64-receipt-data>"
local validation = nk.subscriptions_validate_apple(user_id, receipt)
|
subscription_validate_google
#
Validates and stores a subscription receipt from the Google Play Store.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The user ID of the owner of the receipt. |
receipt
string
REQUIRED | | JSON encoded Google receipt. |
persist
bool | true | Persist the subscription. |
clientEmailOverride
string | | Override the iap.google.client_email provided in your configuration. |
privateKeyOverride
string | | Override the iap.google.private_key provided in your configuration. |
Returns |
---|
Name | Description |
---|
validation
table | The resulting successfully validated subscriptions. |
error
error | An optional error value if an error occurred. |
1
2
3
4
| local user_id = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local 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":".."}}'
local validation = nk.subscription_validate_google(user_id, receipt)
|
Tournaments
#
tournament_add_attempt
#
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 |
---|
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
number
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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "leaderboard-record-owner"
local count = -10
nk.tournament_add_attempt(id, owner, count)
|
tournament_create
#
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 |
---|
id
string
REQUIRED | | The unique identifier for the new tournament. This is used by clients to submit scores. |
authoritative
bool | true | Whether the tournament created is server authoritative. |
sortOrder
string | | The sort order for records in the tournament. Possible values are "asc" or "desc". |
operator
string | | The operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr". |
resetSchedule
string | | 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
table | | The metadata you want associated to the tournament. Some good examples are weather conditions for a racing game. |
title
string | | The title of the tournament. |
description
string | | The description of the tournament. |
category
number | | A category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127. |
startTime
number | | The start time of the tournament. Leave empty for immediately or a future time. |
endTime
number | 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
number
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
number | | Maximum size of participants in a tournament. |
maxNumScore
number | 1000000 | Maximum submission attempts for a tournament record. |
joinRequired
bool | false | Whether the tournament needs to be joined before a record write is allowed. |
enableRanks
bool | false | 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local authoritative = false
local sort = "desc" -- One of: "desc", "asc".
local operator = "best" -- One of: "best", "set", "incr".
local reset = "0 12 * * *" -- Noon UTC each day.
local metadata = {
weather_conditions = "rain"
}
title = "Daily Dash"
description = "Dash past your opponents for high scores and big rewards!"
category = 1
start_time = 0 -- Start now.
end_time = 0 -- Never end, repeat the tournament each day forever.
duration = 3600 -- In seconds.
max_size = 10000 -- First 10,000 players who join.
max_num_score = 3 -- Each player can have 3 attempts to score.
join_required = true -- Must join to compete.
enable_ranks = false
nk.tournament_create(id, sort, operator, duration, reset, metadata, title, description, category, start_time, end_time, max_size, max_num_score, join_required, enable_ranks)
|
tournament_delete
#
Delete a tournament and all records that belong to it.
Parameters |
---|
Name | Default | Description |
---|
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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
nk.tournament_delete(id)
|
tournament_join
#
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 |
---|
id
string
REQUIRED | | The unique identifier for the tournament to join. |
userId
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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "leaderboard-record-owner"
local username = "myusername"
nk.tournament_join(id, owner, username)
|
tournament_list
#
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 |
---|
categoryStart
number
REQUIRED | | Filter tournament with categories greater or equal than this value. |
categoryEnd
number
REQUIRED | | Filter tournament with categories equal or less than this value. |
startTime
number | | Filter tournament with that start after this time. |
endTime
number | | Filter tournament with that end before this time. |
limit
number | 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
table | A list of tournament results and possibly a cursor 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
| local category_start = 1
local category_end = 2
local start_time = 1538147711
local end_time = 0 -- All tournaments from the start time.
local limit = 100 -- Number to list per page.
local tournaments = nk.tournament_list(category_start, category_end, start_time, end_time, limit)
for i, tournament in ipairs(tournaments) do
nk.logger_info(string.format("ID: %q - can enter? %q", tournament.id, tournament.can_enter))
end
|
tournament_ranks_disable
#
Disable a tournament rank cache freeing its allocated resources. If already disabled is a NOOP.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The tournament id. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
nk.tournament_ranks_disable(id)
|
tournamentRecordDelete
#
Remove an owner's record from a tournament, if one exists.
Parameters |
---|
Name | Default | Description |
---|
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. |
tournament_records_haystack
#
Fetch the list of tournament records around the owner.
Parameters |
---|
Name | Default | Description |
---|
id
string
REQUIRED | | The ID of the tournament to list records for. |
ownerId
string
REQUIRED | | The owner ID around which to show records. |
limit
number | 10 | 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
number | 0 | Time since epoch in seconds. Must be greater than 0. |
Returns |
---|
Name | Description |
---|
records
table | A page of tournament records. |
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). 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
nk.tournament_records_haystack(id, owner, 10)
|
tournament_records_list
#
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 |
---|
tournamentId
string
REQUIRED | | The ID of the tournament to list records for. |
ownerIds
table | | List of owner IDs to filter results by. |
limit
number
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
number | 0 | 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
table | A page of tournament records. |
ownerRecords
table | 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). 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owners = {"4c2ae592-b2a7-445e-98ec-697694478b1c", "2c751239-e87a-4b5f-bc06-56873038339d"}
local limit = 100
local cursor = ""
local override_expiry = 0
local records = nk.tournament_records_list(id, owners, limit, cursor, override_expiry)
|
tournament_record_write
#
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 |
---|
id
string
REQUIRED | | The unique identifier for the tournament leaderboard to submit to. |
owner
string
REQUIRED | | The owner of this score submission. |
username
string | | The owner username of this score submission, if it's a user. |
score
number | 0 | The score to submit. |
subscore
number | 0 | A secondary subscore parameter for the submission. |
Returns |
---|
Name | Description |
---|
metadata
table | The metadata you want associated to this submission. Some good examples are weather conditions for a racing game. |
result
table | 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
| local id = "4ec4f126-3f9d-11e7-84ef-b7c182b36521"
local owner = "4c2ae592-b2a7-445e-98ec-697694478b1c"
local username = "02ebb2c8"
local score = 10
local subscore = 0
local metadata = {
weather_conditions = "rain"
}
nk.tournament_record_write(id, owner, username, score, subscore, metadata)
|
tournaments_get_id
#
Fetch one or more tournaments by ID.
Parameters |
---|
Name | Default | Description |
---|
ids
table
REQUIRED | | The table of tournament ids. |
Returns |
---|
Name | Description |
---|
tournamentIDs
table | List of tournament records. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local tournament_ids = {
"3ea5608a-43c3-11e7-90f9-7b9397165f34",
"447524be-43c3-11e7-af09-3f7172f05936"
}
local tournaments = nk.tournaments_get_id(tournament_ids)
|
Users
#
multi_update
#
Update account, storage, and wallet information simultaneously.
Parameters |
---|
Name | Default | Description |
---|
accountUpdates
table
REQUIRED | | List of account information to be updated. |
storageWrites
table
REQUIRED | | List of storage objects to be updated. |
storageDeletes
table
REQUIRED | | A list of storage objects to be deleted. |
walletUpdates
table
REQUIRED | | List of wallet updates to be made. |
updateLedger
bool | false | Whether to record this wallet update in the ledger. |
Returns |
---|
Name | Description |
---|
storageWriteAcks
table | A list of acks with the version of the written objects. |
walletUpdateAcks
table | A list of wallet updates results. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
| local account_updates = {} -- table of account update objects
local storage_writes = {} -- table of storage write objects
local wallet_updates = {} -- table of wallet_update objects
local update_ledger = true
local results = nk.multi_update(account_updates, storage_writes, wallet_updates, update_ledger)
|
users_ban_id
#
Ban one or more users by ID.
Parameters |
---|
Name | Default | Description |
---|
userIds
table
REQUIRED | | A table of user IDs to ban. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local user_ids = {
"3ea5608a-43c3-11e7-90f9-7b9397165f34",
"447524be-43c3-11e7-af09-3f7172f05936"
}
nk.users_ban_id(user_ids)
|
users_get_id
#
Fetch one or more users by ID.
Parameters |
---|
Name | Default | Description |
---|
userIds
table
REQUIRED | | A Lua table of user IDs to fetch. |
Returns |
---|
Name | Description |
---|
users
table | A table 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
| local user_ids = {
"3ea5608a-43c3-11e7-90f9-7b9397165f34",
"447524be-43c3-11e7-af09-3f7172f05936"
}
local users = nk.users_get_id(user_ids)
for _, u in ipairs(users) do
local message = string.format("username: %q, displayname: %q", u.username, u.display_name)
nk.logger_info(message)
end
|
users_get_random
#
Fetch one or more users randomly.
Parameters |
---|
Name | Default | Description |
---|
count
int
REQUIRED | | The number of users to fetch. |
Returns |
---|
Name | Description |
---|
users
table | A list of user record objects. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local users = nk.users_get_random(100)
for _, u in ipairs(users) do
local message = string.format("id: %q, displayname: %q", u.user_id, u.display_name)
nk.logger_info(message)
end
|
users_get_username
#
Fetch one or more users by username.
Parameters |
---|
Name | Default | Description |
---|
usernames
table
REQUIRED | | A table of usernames to fetch. |
Returns |
---|
Name | Description |
---|
users
table | A table of user record objects. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
| local usernames = {"b7865e7e", "c048ba7a"}
local users = nk.users_get_username(usernames)
for _, u in ipairs(users) do
local message = string.format("id: %q, displayname: %q", u.user_id, u.display_name)
nk.logger_info(message)
end
|
users_unban_id
#
Unban one or more users by ID.
Parameters |
---|
Name | Default | Description |
---|
userIds
table
REQUIRED | | A table of user IDs to unban. |
Returns |
---|
Name | Description |
---|
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local user_ids = {
"3ea5608a-43c3-11e7-90f9-7b9397165f34",
"447524be-43c3-11e7-af09-3f7172f05936"
}
nk.users_unban_id(user_ids)
|
Utils
#
aes128_decrypt
#
Decrypt an aes128 encrypted string.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string to be decrypted. |
key
string
REQUIRED | | The 16 Byte decryption key. |
Returns |
---|
Name | Description |
---|
clearText
string | The deciphered input. |
error
error | An optional error value if an error occurred. |
1
| local plaintext = nk.aes128_decrypt("48656C6C6F20776F726C64", "goldenbridge_key")
|
aes128_encrypt
#
aes128 encrypt a string input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string which will be aes128 encrypted. |
key
string
REQUIRED | | The 16 Byte encryption key. |
Returns |
---|
Name | Description |
---|
cipherText
string | The ciphered input. |
error
error | An optional error value if an error occurred. |
1
| local cyphertext = nk.aes128_encrypt("48656C6C6F20776F726C64", "goldenbridge_key")
|
aes256_decrypt
#
Decrypt an aes256 encrypted string.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string to be decrypted. |
key
string
REQUIRED | | The 32 Byte decryption key. |
Returns |
---|
Name | Description |
---|
clearText
string | The deciphered input. |
error
error | An optional error value if an error occurred. |
1
| local plaintext = nk.aes256_decrypt("48656C6C6F20776F726C64", "goldenbridge_key")
|
aes256_encrypt
#
aes256 encrypt a string input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string which will be aes256 encrypted. |
key
string
REQUIRED | | The 32 Byte encryption key. |
Returns |
---|
Name | Description |
---|
cipherText
string | The ciphered input. |
error
error | An optional error value if an error occurred. |
1
| local cyphertext = nk.aes256_encrypt("48656C6C6F20776F726C64", "goldenbridge_key")
|
base16_decode
#
Decode a base16 encoded string.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string to be decoded. |
Returns |
---|
Name | Description |
---|
output
string | Decoded string. |
error
error | An optional error value if an error occurred. |
1
2
| local decoded = nk.base16_decode("48656C6C6F20776F726C64")
nk.logger_info(decoded) -- outputs "Hello world".
|
base16_encode
#
base16 encode a string input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string to be encoded. |
Returns |
---|
Name | Description |
---|
output
string | Encoded string. |
error
error | An optional error value if an error occurred. |
1
2
| local encoded = nk.base16_encode("Hello world")
nk.logger_info(encoded) -- outputs "48656C6C6F20776F726C64"
|
base64_decode
#
Decode a base64 encoded string.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string which will be base64 decoded. |
padding
bool | true | Pad the string if padding is missing. |
Returns |
---|
Name | Description |
---|
output
string | Decoded string. |
error
error | An optional error value if an error occurred. |
1
2
| local decoded = nk.base64_decode("SGVsbG8gd29ybGQ=")
nk.logger_info(decoded) -- outputs "Hello world".
|
base64_encode
#
Base64 encode a string input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string which will be base64 encoded. |
Returns |
---|
Name | Description |
---|
output
string | Encoded string. |
error
error | An optional error value if an error occurred. |
1
2
| local encoded = nk.base64_encode("Hello world")
nk.logger_info(encoded) -- outputs "SGVsbG8gd29ybGQ="
|
base64url_decode
#
Decode a base64 URL encoded string.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string to be decoded. |
Returns |
---|
Name | Description |
---|
output
string | Decoded string. |
error
error | An optional error value if an error occurred. |
1
2
| local decoded = nk.base64url_decode("SGVsbG8gd29ybGQ=")
nk.logger_info(decoded) -- outputs "Hello world".
|
base64url_encode
#
Base64 URL encode a string input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The string which will be base64 URL encoded. |
Returns |
---|
Name | Description |
---|
output
string | Encoded string. |
error
error | An optional error value if an error occurred. |
1
2
| local encoded = nk.base64url_encode("Hello world")
nk.logger_info(encoded) -- outputs "SGVsbG8gd29ybGQ="
|
bcrypt_compare
#
Compare hashed input against a plaintext input.
Parameters |
---|
Name | Default | Description |
---|
hash
string
REQUIRED | | The bcrypted input string. |
plaintext
string
REQUIRED | | Plaintext input to compare against. |
Returns |
---|
Name | Description |
---|
result
bool | True if they are the same, false otherwise. |
error
error | An optional error value if an error occurred. |
1
2
| local is_same = nk.bcrypt_compare("$2a$04$bl3tac7Gwbjy04Q8H2QWLuUOEkpoNiAeTxazxi4fVQQRMGbMaUHQ2", "123456")
nk.logger_info(is_same) -- outputs true.
|
bcrypt_hash
#
Generate one-way hashed string using bcrypt.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The input string to bcrypt. |
Returns |
---|
Name | Description |
---|
hash
string | Hashed string. |
error
error | An optional error value if an error occurred. |
1
2
| local hashed = nk.bcrypt_hash("Hello World")
nk.logger_info(hashed)
|
cron_next
#
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
number
REQUIRED | | A time value expressed as UTC seconds. |
Returns |
---|
Name | Description |
---|
next_ts
number | 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
4
5
| -- Based on the current time, return the UTC seconds value representing the
-- nearest upcoming Monday at 00:00 UTC (midnight.)
local expr = "0 0 * * 1"
local ts = os.time()
local next = nk.cron_next(expr, ts)
|
cron_prev
#
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
number
REQUIRED | | A time value expressed as UTC seconds. |
Returns |
---|
Name | Description |
---|
prev_ts
number | 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
| local expr = "0 0 * * 1"
local ts = os.time()
local prev = nk.cron_prev(expr, ts)
|
file_read
#
Read file from user device.
Parameters |
---|
Name | Default | Description |
---|
relPath
string
REQUIRED | | Relative path to the file to be read. |
Returns |
---|
Name | Description |
---|
fileContent
string | The read file contents. |
error
error | An optional error value if an error occurred. |
1
2
| local relative_path = "<RelativePath>"
local contents = nk.file_read(relative_path)
|
hmac_sha256_hash
#
Create a HMAC-SHA256 hash from input and key.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The input string to hash. |
key
string
REQUIRED | | The hashing key. |
Returns |
---|
Name | Description |
---|
mac
string | Hashed input as a string using the key. |
error
error | An optional error value if an error occurred. |
1
2
| local hash = nk.hmac_sha256_hash("encryptthis", "somekey")
print(hash)
|
http_request
#
Send a HTTP request that returns a data type containing the result of the HTTP response.
Parameters |
---|
Name | Default | Description |
---|
url
string
REQUIRED | | The URL of the web resource to request. |
method
string
REQUIRED | | The HTTP method verb used with the request. |
headers
table | | A table of headers used with the request. |
content
string | | The bytes to send with the request. |
timeout
number | 5000 | Timeout of the request in milliseconds. |
insecure
bool | false | Set to true to skip request TLS validations. |
Returns |
---|
Name | Description |
---|
returnVal
table | Code, Headers, and Body response values for the HTTP response. |
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
| local url = "https://google.com/"
local method = "HEAD"
local headers = {
["Content-Type"] = "application/json",
["Accept"] = "application/json"
}
local content = nk.json_encode({}) -- encode table as JSON string
local timeout = 5000 -- 5 seconds timeout
local success, code, headers, body = pcall(nk.http_request, url, method, headers, content, timeout)
if (not success) then
nk.logger_error(string.format("Failed %q", code))
elseif (code >= 400) then
nk.logger_error(string.format("Failed %q %q", code, body))
else
nk.logger_info(string.format("Success %q %q", code, body))
end
|
json_decode
#
Decode the JSON input as a Lua table.
Parameters |
---|
Name | Default | Description |
---|
jsonString
string
REQUIRED | | The JSON encoded input. |
Returns |
---|
Name | Description |
---|
jsonData
table | Decoded JSON input as a Lua table. |
error
error | An optional error value if an error occurred. |
1
2
| local json = nk.json_decode('{"hello": "world"}')
nk.logger_info(json.hello)
|
json_encode
#
Encode the input as JSON.
Parameters |
---|
Name | Default | Description |
---|
value
string
REQUIRED | | The input to encode as JSON . |
Returns |
---|
Name | Description |
---|
jsonBytes
string | The encoded JSON string. |
error
error | An optional error value if an error occurred. |
1
2
3
4
| local input = {["some"] = "json"}
local json = nk.json_encode(input)
nk.logger_info(json) -- Outputs '{"some": "json"}'.
|
jqt_generate
#
Generate a JSON Web Token.
Parameters |
---|
Name | Default | Description |
---|
signingMethod
string
REQUIRED | | The signing method to be used, either HS256 or RS256. |
signingKey
string
REQUIRED | | The signing key to be used. |
claims
table
REQUIRED | | The JWT payload. |
Returns |
---|
Name | Description |
---|
token
string | The newly generated JWT. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
| local signing_method = "HS256"
local signing_key = "goldenbridge_key"
local claims = { email = "test@heroiclabs.com" }
local token = nk.jwt_generate(signing_method, signing_key, claims)
nk.logger_info("Token: " .. token)
|
md5_hash
#
Create an md5 hash from the input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The input string to hash. |
Returns |
---|
Name | Description |
---|
hash
string | A string with the md5 hash of the input. |
error
error | An optional error value if an error occurred. |
1
2
3
4
| local input = "somestring"
local hashed = nk.md5_hash(input)
nk.logger_info(hashed)
|
rsaSHA256Hash
#
Create a RSA encrypted SHA256 hash from the input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The input string to hash. |
key
string
REQUIRED | | The RSA private key. |
Returns |
---|
Name | Description |
---|
signature
string | A string with the RSA encrypted SHA256 hash of the input. |
error
error | An optional error value if an error occurred. |
1
2
| local cipher_text = nk.rsa_sha256_hash("Hello world", "rsa_private_key")
nk.logger_info(cipher_text)
|
sha256_hash
#
Create an SHA256 hash from the input.
Parameters |
---|
Name | Default | Description |
---|
input
string
REQUIRED | | The input string to hash. |
Returns |
---|
Name | Description |
---|
hash
string | A string with the SHA256 hash of the input. |
error
error | An optional error value if an error occurred. |
1
2
| local cipher_text = nk.sha256_hash("Hello world")
nk.logger_info(cipher_text)
|
sql_exec
#
Execute an arbitrary SQL query and return the number of rows affected. Typically an "INSERT", "DELETE", or "UPDATE" statement with no return columns.
Parameters |
---|
Name | Default | Description |
---|
query
string
REQUIRED | | A SQL query to execute. |
parameters
table
REQUIRED | | Arbitrary parameters to pass to placeholders in the query. |
Returns |
---|
Name | Description |
---|
count
number | 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
| -- This example query deletes all expired leaderboard records.
local query = [[
DELETE FROM leaderboard_record
WHERE expires_at > 0 AND expires_at <= $1
]]
local parameters = { os.time() * 1000 }
local affected_rows_count = nk.sql_exec(query, parameters)
|
sql_query
#
Execute an arbitrary SQL query that is expected to return row data. Typically a "SELECT" statement.
Parameters |
---|
Name | Default | Description |
---|
query
string
REQUIRED | | A SQL query to execute. |
parameters
table
REQUIRED | | Arbitrary parameters to pass to placeholders in the query. |
Returns |
---|
Name | Description |
---|
result
table | A table of rows and the respective columns and values. |
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
| -- Example fetching a list of usernames for the 100 most recently signed up users.
local query = [[
SELECT username, create_time
FROM users
ORDER BY create_time DESC
LIMIT 100
]]
local parameters = {}
local rows = nk.sql_query(query, parameters)
-- Example of processing the rows.
nk.logger_info("Selected " .. #rows .. " rows.")
for i, row in ipairs(rows) do
nk.logger_info(string.format("Username %q created at %q", row.username, row.create_time))
end
|
time
#
Get the current UTC time in milliseconds using the system wall clock.
Parameters |
---|
Name | Default | Description |
---|
Returns |
---|
Name | Description |
---|
t
int | A number representing the current UTC time in milliseconds. |
error
error | An optional error value if an error occurred. |
1
| local utc_msec = nk.time()
|
uuid_bytes_to_string
#
Convert the 16-byte raw representation of a UUID into the equivalent 36-character standard UUID string representation. Will raise an error if the input is not valid and cannot be converted.
Parameters |
---|
Name | Default | Description |
---|
uuid_bytes
string
REQUIRED | | The UUID bytes to convert. |
Returns |
---|
Name | Description |
---|
u
string | A string containing the equivalent 36-character standard representation of the UUID. |
error
error | An optional error value if an error occurred. |
1
2
| local uuid_bytes = "896418357731323983933079013" -- some uuid bytes.
local uuid_string = nk.uuid_bytes_to_string(uuid_bytes)
|
uuid_string_to_bytes
#
Convert the 36-character string representation of a UUID into the equivalent 16-byte raw UUID representation. Will raise an error if the input is not valid and cannot be converted.
Parameters |
---|
Name | Default | Description |
---|
uuid_string
string
REQUIRED | | The UUID string to convert. |
Returns |
---|
Name | Description |
---|
u
string | A string containing the equivalent 16-byte representation of the UUID. |
error
error | An optional error value if an error occurred. |
1
2
3
4
| local uuid_string = "4ec4f126-3f9d-11e7-84ef-b7c182b36521" -- some uuid string.
local uuid_bytes = nk.uuid_string_to_bytes(uuid_string)
nk.logger_info(uuid_bytes)
|
uuid_v4
#
Generate a version 4 UUID in the standard 36-character string representation.
Parameters |
---|
Name | Default | Description |
---|
Returns |
---|
Name | Description |
---|
u
string | The newly generated version 4 UUID identifier string. |
error
error | An optional error value if an error occurred. |
1
2
| local uuid = nk.uuid_v4()
nk.logger_info(uuid)
|
Wallets
#
wallet_ledger_list
#
List all wallet updates for a particular user from oldest to newest.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The ID of the user to list wallet updates for. |
limit
number | 100 | Limit number of results. |
cursor
string | | Pagination cursor from previous result. Don't set to start fetching from the beginning. |
Returns |
---|
Name | Description |
---|
itemsTable
table | A table containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters. |
newCursor
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
| local user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
local updates = nk.wallet_ledger_list(user_id)
for _, u in ipairs(updates) do
local message = string.format("Found wallet update with id: %q", u.id)
nk.logger_info(message)
end
|
wallet_ledger_update
#
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 |
---|
itemId
string
REQUIRED | | The ID of the wallet ledger item to update. |
metadata
table
REQUIRED | | The new metadata to set on the wallet ledger item. |
Returns |
---|
Name | Description |
---|
itemTable
table | The updated wallet ledger item. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
| local id = "2745ba53-4b43-4f83-ab8f-93e9b677f33a"
local metadata = {
game_result = "loss"
}
local u = nk.wallet_ledger_update(id, metadata)
|
wallets_update
#
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 |
---|
updates
table
REQUIRED | | The set of user wallet update operations to apply. |
updateLedger
bool | false | Whether to record this update in the ledger. |
Returns |
---|
Name | Description |
---|
updateWallets
table | 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
| local updates = {
{
user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592",
changeset = {
coins = 10, -- Add 10 coins to the user's wallet.
gems = -5 -- Remove 5 gems from the user's wallet.
},
metadata = {
game_result = "won"
}
}
}
nk.wallets_update(updates, true)
|
wallet_update
#
Update a user's wallet with the given changeset.
Parameters |
---|
Name | Default | Description |
---|
userId
string
REQUIRED | | The ID of the user whose wallet to update. |
changeset
table
REQUIRED | | The set of wallet operations to apply. |
metadata
table | | Additional metadata to tag the wallet update with. |
updateLedger
bool | false | Whether to record this update in the ledger. |
Returns |
---|
Name | Description |
---|
result
table | The changeset after the update and before to the update, respectively. |
error
error | An optional error value if an error occurred. |
1
2
3
4
5
6
7
8
9
10
11
12
| local user_id = "8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"
local changeset = {
coins = 10, -- Add 10 coins to the user's wallet.
gems = -5 -- Remove 5 gems from the user's wallet.
}
local metadata = {
game_result = "won"
}
local updated, previous = nk.wallet_update(user_id, changeset, metadata, true)
|