The code runtime built into the server includes a module with functions to implement various logic and custom behavior, enabling you to define authoritative code and conditions on input received by clients. Learn more about it in the Server Framework Basics documentation.
This page lists all functions available within Nakama and their respective parameters, with corresponding code samples for each.
If you haven’t already, see the documentation on using the server framework.
Writing custom SQL is discouraged in favor of using the built-in features of the Storage Engine. If custom SQL is needed for your use case, please contact Heroic Labs before proceeding.
The creation of custom tables is strongly discouraged.
The context object represents information about the server and requester.
userIdstringREQUIRED
User ID to fetch information for. Must be valid UUID.
Returns
Name
Description
account*api.Account
All account information including wallet, device IDs and more.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
account,err:=nk.AccountGetId(ctx,"8f4d52c7-bf28-4fcf-8af2-1d4fcf685592")iferr!=nil{logger.WithField("err",err).Error("Get accounts error.")return}logger.Info("Wallet is: %v",account.Wallet)
Fetch information for multiple accounts by user IDs.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
userIds[]stringREQUIRED
Array of user IDs to fetch information for. Must be valid UUID.
Returns
Name
Description
account[]*api.Account
An array of accounts.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
userIDs:=[]string{"9a51cf3a-2377-11eb-b713-e7d403afe081","a042c19c-2377-11eb-b7c1-cfafae11cfbc"}accounts,err:=nk.AccountsGetId(ctx,userIDs)iferr!=nil{logger.WithField("err",err).Error("Get accounts error.")return}for_,account:=rangeaccounts{logger.Info("Wallet is: %v",account.Wallet)}
The context object represents information about the server and requester.
userIdstringREQUIRED
User ID for which the information is to be updated. Must be valid UUID.
metadatamap[string]interfaceREQUIRED
The metadata to update for this account.
usernamestringREQUIRED
Username to be set. Must be unique. Use "" if it is not being updated.
displayNamestringREQUIRED
Display name to be updated. Use "" if it is not being updated.
timezonestringREQUIRED
Timezone to be updated. Use "" if it is not being updated.
locationstringREQUIRED
Location to be updated. Use "" if it is not being updated.
languagestringREQUIRED
Lang tag to be updated. Use "" if it is not being updated.
avatarUrlstringREQUIRED
User's avatar URL. Use "" if it is not being updated.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
userID:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"// Some user ID.
username:=""metadata:=make(map[string]interface{})displayName:=""timezone:=""location:=""langTag:=""avatarUrl:=""iferr:=nk.AccountUpdateId(ctx,userID,username,metadata,displayName,timezone,location,langTag,avatarUrl);err!=nil{logger.WithField("err",err).Error("Account update error.")}
Authenticate user and create a session token using an Apple sign in token.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
tokenstringREQUIRED
Apple sign in token.
usernamestringREQUIRED
The user's username. If left empty, one is generated.
createboolREQUIRED
Create user if one didn't exist previously.
Returns
Name
Description
userIDstring
The user ID of the authenticated user.
usernamestring
The username of the authenticated user.
createbool
Value indicating if this account was just created or already existed.
errorerror
An optional error value if an error occurred.
1
2
3
4
userid,username,created,err:=nk.AuthenticateApple(ctx,"some-oauth-access-token","username",true)iferr!=nil{logger.WithField("err",err).Error("Authenticate apple error.")}
Authenticate user and create a session token using Apple Game Center credentials.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
playerIdstringREQUIRED
PlayerId provided by GameCenter.
bundleIdstringREQUIRED
BundleId of your app on iTunesConnect.
timestampintREQUIRED
Timestamp at which Game Center authenticated the client and issued a signature.
saltstringREQUIRED
A random string returned by Game Center authentication on client.
signaturestringREQUIRED
A signature returned by Game Center authentication on client.
publicKeyUrlstringREQUIRED
A URL to the public key returned by Game Center authentication on client.
usernamestring
The user's username. If left empty, one is generated.
createboolREQUIRED
Create user if one didn't exist previously.
Returns
Name
Description
userIDstring
The user ID of the authenticated user.
usernamestring
The username of the authenticated user.
createbool
Value indicating if this account was just created or already existed.
errorerror
An optional error value if an error occurred.
1
2
3
4
userid,username,created,err:=nk.AuthenticateGameCenter(ctx,playerID,bundleID,timestamp,salt,signature,publicKeyUrl,username,create)iferr!=nil{logger.WithField("err",err).Error("Authenticate game center error.")}
Authenticate user and create a session token using a Google ID token.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
tokenstringREQUIRED
Google OAuth access token.
usernamestringREQUIRED
The user's username. If left empty, one is generated.
createboolREQUIRED
Create user if one didn't exist previously.
Returns
Name
Description
userIDstring
The user ID of the authenticated user.
usernamestring
The username of the authenticated user.
createbool
Value indicating if this account was just created or already existed.
errorerror
An optional error value if an error occurred.
1
2
3
4
userid,username,created,err:=nk.AuthenticateGoogle(ctx,"some-id-token","username",true)iferr!=nil{logger.WithField("err",err).Error("Authenticate google error.")}
Link Apple Game Center authentication to a user ID.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
userIdstringREQUIRED
The user ID to be linked.
playerIdstringREQUIRED
Player ID provided by Game Center.
bundleIdstringREQUIRED
Bundle ID of your app on iTunesConnect.
timestampintREQUIRED
Timestamp at which Game Center authenticated the client and issued a signature.
saltstringREQUIRED
A random string returned by Game Center authentication on client.
signaturestringREQUIRED
A signature returned by Game Center authentication on client.
publicKeyUrlstringREQUIRED
A URL to the public key returned by Game Center authentication on client.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
err:=nk.LinkGameCenter(ctx,userID,playerID,bundleID,timestamp,salt,signature,publicKeyUrl)iferr!=nil{logger.WithField("err",err).Error("Link game center error.")}
Unlink Apple Game Center authentication from a user ID.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
userIdstringREQUIRED
The user ID to be unlinked.
playerIdstringREQUIRED
Player ID provided by Game Center.
bundleIdstringREQUIRED
Bundle ID of your app on iTunesConnect.
timestampintREQUIRED
Timestamp at which Game Center authenticated the client and issued a signature.
saltstringREQUIRED
A random string returned by Game Center authentication on client.
signaturestringREQUIRED
A signature returned by Game Center authentication on client.
publicKeyUrlstringREQUIRED
A URL to the public key returned by Game Center authentication on client.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
err:=nk.UnlinkGameCenter(ctx,userID,playerID,bundleID,timestamp,salt,signature,publicKeyUrl)iferr!=nil{logger.WithField("err",err).Error("Unlink game center error.")}
The context object represents information about the server and requester.
channelIdstringREQUIRED
The ID of the channel to send the message on.
contentmap[string]interfaceREQUIRED
Message content.
senderIdstring
The UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsernamestring
The username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persistboolREQUIRED
Whether to record this message in the channel history.
Returns
Name
Description
channelMessageSend*rtapi.ChannelMessageAck
Message sent ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
channelID:="<ChannelId>"content:=map[string]interface{}{"message":"Hello",}senderID:="<SenderId>"senderUsername:="<SenderUsername>"persist:=trueack,err:=nk.ChannelMessageSend(ctx,channelID,content,senderID,senderUsername,persist)iferr!=nil{logger.Debug("%v created at %v",ack.MessageId,ack.CreateTime)returnerr}
The context object represents information about the server and requester.
channelIdstringREQUIRED
The ID of the channel to list messages from.
limitintREQUIRED
The number of messages to return per page.
forwardboolREQUIRED
Whether to list messages from oldest to newest, or newest to oldest.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
channelMessageList[]*rtapi.ChannelMessage
Messages from the specified channel.
nextCursorstring
Cursor for the next page of messages, if any.
prevCursorstring
Cursor for the previous page of messages, if any.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
channelID:="<ChannelId>"limit:=100forward:=truelist,err:=nk.ChannelMessagesList(ctx,channelID,limit,forward)iferr!=nil{logger.WithField("err",err).Error("Channel message list error.")}for_,m:=rangelist.Messages{logger.info("Message: %+v",v)}
The context object represents information about the server and requester.
channelIdstringREQUIRED
The ID of the channel to send the message on.
messageIdstringREQUIRED
The ID of the message to update.
contentmap[string]interfaceREQUIRED
Message content.
senderIdstring
The UUID for the sender of this message. If left empty, it will be assumed that it is a system message.
senderUsernamestring
The username of the user to send this message as. If left empty, it will be assumed that it is a system message.
persistboolREQUIRED
Whether to record this message in the channel history.
Returns
Name
Description
channelMessageUpdate*rtapi.ChannelMessageAck
Message updated ack containing the following variables: 'channelId', 'contentStr', 'senderId', 'senderUsername', and 'persist'.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
channelID:="<ChannelId>"messageID:="<MessageId>"content:=map[string]interface{}{"message":"Hello",}senderID:="<SenderId>"senderUsername:="<SenderUsername>"persist:=trueack,err:=nk.ChannelMessageUpdate(ctx,channelID,messageID,content,senderID,senderUsername,persist)iferr!=nil{logger.Debug("%v updated at %v",ack.MessageId,ack.UpdateTime)returnerr}
List all friends, invites, invited, and blocked which belong to a user.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
userIdstringREQUIRED
The ID of the user whose friends, invites, invited, and blocked you want to list.
limitintREQUIRED
The number of friends to retrieve in this page of results. No more than 100 limit allowed per result.
stateint
The state of the friendship with the user. If unspecified this returns friends in all states for the user.
cursorstringREQUIRED
Pagination cursor from previous result. Set to "" to start fetching from the beginning.
Returns
Name
Description
friends[]*api.Friend
The user information for users that are friends of the current user.
cursorstring
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.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
userID:="b1aafe16-7540-11e7-9738-13777fcc7cd8"limit:=100state:=0cursor:=""friends,err:=nk.FriendsList(ctx,userID,limit,&state,cursor)iferr!=nil{logger.WithField("err",err).Error("nk.FriendsList error.")return}for_,friend:=rangefriends{// States are: friend(0), invite_sent(1), invite_received(2), blocked(3)
logger.Info("Friend username %s has state %d",friend.GetUser().Username,friend.GetState())}
The context object represents information about the server and requester.
userIdstringREQUIRED
The ID of the user whose friends of friends you want to list.
limitintREQUIRED
The number of friends of friends to retrieve in this page of results. No more than 100 limit allowed per result.
cursorstringREQUIRED
Pagination cursor from previous result. Set to "" to start fetching from the beginning.
Returns
Name
Description
friends[]*api.Friend
The user information for users that are friends of friends the current user.
cursorstring
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.
The context object represents information about the server and requester.
groupIds[]stringREQUIRED
An array of strings of the IDs for the groups to get.
Returns
Name
Description
getGroups[]*api.Group
An array of groups with their fields.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:="dcb891ea-a311-4681-9213-6741351c9994"groups,err:=nk.GroupsGetId(ctx,[]string{groupID})iferr!=nil{logger.WithField("err",err).Error("Groups get by ID error.")return}
The context object represents information about the server and requester.
namestring
Search for groups that contain this value in their name. Cannot be combined with any other filter.
langTagstring
Filter based upon the entered language tag.
membersint
Search by number of group members.
openbool
Filter based on whether groups are Open or Closed.
limitint
Return only the required number of groups denoted by this limit value.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
groups[]*api.Group
A list of groups.
cursorstring
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.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
groupName:="Heroic"langTag:="en"members:=10open:=truelimit:=100cursor:=""list,cursor,err:=nk.GroupsList(ctx,groupName,langTag,&members,&open,limit,cursor)iferr!=nil{logger.WithField("err",err).Error("Group list error.")}else{for_,g:=rangelist{logger.Info("ID %s - open? %b cursor: %s",g.Id,g.Open,cursor)}}
The context object represents information about the server and requester.
groupIdstringREQUIRED
The ID of the group to join.
userIdstringREQUIRED
The user ID to add to this group.
usernamestringREQUIRED
The username of the user to add to this group.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
groupID:="dcb891ea-a311-4681-9213-6741351c9994"userID:="9a51cf3a-2377-11eb-b713-e7d403afe081"username:="myusername"iferr:=nk.GroupUserJoin(ctx,groupID,userID,username);err!=nil{logger.WithField("err",err).Error("Group user join error.")}
The context object represents information about the server and requester.
groupIdstringREQUIRED
The ID of the group to leave.
userIdstringREQUIRED
The user ID to remove from this group.
usernamestringREQUIRED
The username of the user to remove from this group.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
groupID:="dcb891ea-a311-4681-9213-6741351c9994"userID:="9a51cf3a-2377-11eb-b713-e7d403afe081"username:="myusername"iferr:=nk.GroupUserLeave(ctx,groupID,userID,username);err!=nil{logger.WithField("err",err).Error("Group user leave error.")}
The context object represents information about the server and requester.
callerIdstring
User ID of the caller, will apply permissions checks of the user. If empty defaults to system user and permissions are bypassed.
groupIdstringREQUIRED
The ID of the group to ban users from.
userIds[]stringREQUIRED
Table array of user IDs to ban from this group.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
groupID:="dcb891ea-a311-4681-9213-6741351c9994"userIDs:=[]string{"9a51cf3a-2377-11eb-b713-e7d403afe081","a042c19c-2377-11eb-b7c1-cfafae11cfbc"}iferr:=nk.GroupUsersBan(ctx,groupID,userIDs);err!=nil{logger.WithField("err",err).Error("Group users ban error.")}
List all members, admins and superadmins which belong to a group. This also lists incoming join requests.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
groupIdstringREQUIRED
The ID of the group to list members for.
limitintREQUIRED
Return only the required number of users denoted by this limit value.
stateintREQUIRED
Return only the users matching this state value, '0' for superadmins for example.
cursorstringREQUIRED
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
groupID:="dcb891ea-a311-4681-9213-6741351c9994"groupUserList,err:=nk.GroupUsersList(ctx,groupID)iferr!=nil{logger.WithField("err",err).Error("Group users list error.")return}for_,member:=rangegroupUserList{// States are => 0: Superadmin, 1: Admin, 2: Member, 3: Requested to join
logger.Info("Member username %s has state %d",member.GetUser().Username,member.GetState())}
List all groups which a user belongs to and whether they've been accepted or if it's an invite.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
userIdstringREQUIRED
The ID of the user to list groups for.
limitintREQUIRED
The maximum number of entries in the listing.
stateint
The state of the user within the group. If unspecified this returns users in all states.
cursorstringREQUIRED
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
cursorstring
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.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
userID:="dcb891ea-a311-4681-9213-6741351c9994"groups,err:=nk.UserGroupsList(ctx,userID)iferr!=nil{logger.WithField("err",err).Error("User groups list error.")return}for_,group:=rangegroups{logger.Printf("User has state %d in group %s.",group.GetState(),group.GetGroup().Name)}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
leaderboardIDstringREQUIRED
The unique identifier for the new leaderboard. This is used by clients to submit scores.
authoritativeboolREQUIRED
false
Mark the leaderboard as authoritative which ensures updates can only be made via the Go runtime. No client can submit a score directly.
sortOrderstringREQUIRED
The sort order for records in the leaderboard. Possible values are "asc" or "desc".
operatorstringREQUIRED
The operator that determines how scores behave when submitted. Possible values are "best", "set", or "incr".
resetSchedulestringREQUIRED
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.
metadatamap[string]interfaceREQUIRED
The metadata you want associated to the leaderboard. Some good examples are weather conditions for a racing game.
enableRanksboolREQUIRED
Whether to enable rank values for the leaderboard.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"authoritative:=falsesortOrder:="desc"operator:="best"resetSchedule:="0 0 * * 1"metadata:=map[string]interface{}{"weather_conditions":"rain",}enableRanks=false// Set to true to enable rank computation on leaderboard records.
iferr:=nk.LeaderboardCreate(ctx,id,authoritative,sortOrder,operator,resetSchedule,metadata,enableRanks);err!=nil{logger.WithField("err",err).Error("Leaderboard create error.")}
Find leaderboards which have been created on the server. Leaderboards can be filtered with categories.
Parameters
Name
Default
Description
limitintREQUIRED
Return only the required number of leaderboards denoted by this limit value.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
leaderboardList*api.LeaderboardList
A list of leaderboard results and possibly a cursor. If cursor is empty/nil there are no further results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
limit:=100// Number to list per page.
cursor:=""list,err:=nk.LeaderboardList(ctx,limit,cursor)iferr!=nil{logger.WithField("err",err).Error("Leaderboard list error.")}else{for_,l:=rangelist.Leaderboards{logger.Info("ID %s - can enter? %b",l.Id,l.CanEnter)}}
Remove an owner's record from a leaderboard, if one exists.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
idstringREQUIRED
The unique identifier for the leaderboard to delete from.
ownerstringREQUIRED
The owner of the score to delete.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"ownerID:="4c2ae592-b2a7-445e-98ec-697694478b1c"iferr:=nk.LeaderboardRecordDelete(ctx,id,ownerID);err!=nil{logger.WithField("err",err).Error("Leaderboard record delete error.")}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
idstringREQUIRED
The unique identifier for the leaderboard to list.
owners[]stringREQUIRED
Array of owners to filter to.
limitintREQUIRED
The maximum number of records to return (Max 10,000).
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiryintREQUIRED
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
records[]*api.LeaderboardRecord
A page of leaderboard records.
ownerRecords[]*api.LeaderboardRecord
A list of owner leaderboard records (empty if the owners input parameter is not set).
nextCursorstring
An optional next page cursor that can be used to retrieve the next page of records (if any).
prevCursorstring
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"ownerIDs:=[]string{}limit:=10cursor:=""expiry:=int64(0)records,ownerRecords,prevCursor,nextCursor,err:=nk.LeaderboardRecordsList(ctx,id,ownerIDs,limit,cursor,expiry)iferr!=nil{logger.WithField("err",err).Error("Leaderboard record list error.")}
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
leaderboardIDstringREQUIRED
The unique identifier of the leaderboard.
rankintREQUIRED
The rank to start listing leaderboard records from.
overrideExpiryintREQUIRED
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
leaderboardListCursorstring
A string cursor to be used with leaderboardRecordsList.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"rank:=int64(1)expiry:=int64(0)cursor,err:=nk.LeaderboardRecordsListCursorFromRank(ctx,id,rank,expiry)iferr!=nil{logger.WithField("err",err).Error("Leaderboard record list cursor from rank error.")}
Use the preconfigured operator for the given leaderboard to submit a score for a particular user.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
idstringREQUIRED
The unique identifier for the leaderboard to submit to.
ownerstringREQUIRED
The owner of this score submission.
usernamestringREQUIRED
The owner username of this score submission, if it's a user.
scoreintREQUIRED
The score to submit.
subscoreint
A secondary subscore parameter for the submission.
metadatamap[string]interface
The metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
overrideOperator*intREQUIRED
An override operator for the new record. The accepted values include: 0 (no override), 1 (best), 2 (set), 3 (incr), 4 (decr). Passing nil is the same as passing a pointer to 0 (no override), which uses the default leaderboard operator.
Returns
Name
Description
record*api.LeaderboardRecord
The newly created leaderboard record.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"ownerID:="4c2ae592-b2a7-445e-98ec-697694478b1c"username:="02ebb2c8"score:=int64(10)subscore:=int64(0)metadata:=map[string]interface{}{"weather_conditions":"rain",}overrideOperator:=new(int)// Optional operator to override the one set in the leaderboard. nil or 0 means no override
ifrecord,err:=nk.LeaderboardRecordWrite(ctx,id,ownerID,username,score,subscore,metadata,overrideOperator);err!=nil{logger.WithField("err",err).Error("Leaderboard record write error.")}
leaderboardIDs:=[]string{"3ea5608a-43c3-11e7-90f9-7b9397165f34","447524be-43c3-11e7-af09-3f7172f05936",}leaderboards,err:=nk.LeaderboardsGetId(ctx,leaderboardIDs)iferr!=nil{logger.WithField("err",err).Error("Leaderboards get error.")}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
modulestringREQUIRED
The name of an available runtime module that will be responsible for the match. This was registered in InitModule.
paramsmap[string]interfaceREQUIRED
Any value to pass to the match init hook.
Returns
Name
Description
matchIdstring
The match ID of the newly created match. Clients can immediately use this ID to join the match.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
// Assumes you've registered a match with initializer.RegisterMatch("some.folder.module", ...)
modulename:="some.folder.module"params:=map[string]interface{}{"some":"data",}matchID,err:=nk.MatchCreate(ctx,modulename,params)iferr!=nil{return"",err}
List currently running realtime multiplayer matches and optionally filter them by authoritative mode, label, and current participant count.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
limitint
100
The maximum number of matches to list.
authoritativebool
false
Set true to only return authoritative matches, false to only return relayed matches.
labelstringREQUIRED
A label to filter authoritative matches by. Default "" means any label matches.
minSizeintREQUIRED
Inclusive lower limit of current match participants.
maxSizeintREQUIRED
Inclusive upper limit of current match participants.
querystringREQUIRED
Additional query parameters to shortlist matches.
Returns
Name
Description
match[]*api.Match
A list of matches matching the parameters criteria.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// List at most 10 matches, not authoritative, and that
// have between 2 and 4 players currently participating.
limit:=10isAuthoritative:=falselabel:=""minSize:=2maxSize:=4matches,err:=nk.MatchList(ctx,limit,isAuthoritative,label,minSize,maxSize,"")iferr!=nil{logger.WithField("err",err).Error("Match list error.")}else{for_,match:=rangematches{logger.Info("Found match with id: %s",match.GetMatchId())}}
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
ctxcontext.ContextREQUIRED
Context object represents information about the match and server for information purposes.
idstringREQUIRED
The user ID or session ID to send a reservation signal for.
datastringREQUIRED
An arbitrary input supplied by the runtime caller of the signal.
Returns
Name
Description
datastring
Arbitrary data to return to the runtime caller of the signal. May be a string or nil.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
matchId:="52f02f3e-5b48-11eb-b182-0f5058adfcc6"data:="<Data>"result,err:=nk.MatchSignal(ctx,matchId,data)iferr!=nil{logger.WithField("err",err).Error("Match signal error.")}else{logger.Info("Match signal result: %s",result)}
User ID of the caller, will apply permissions checks of the user. If empty, defaults to system user and permissions are bypassed.
queryStringstringREQUIRED
Query to filter index entries.
limitintREQUIRED
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.
userID:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"objectIDs:=[]*runtime.StorageWrite{&runtime.StorageWrite{Collection:"save",Key:"save1",UserID:userID,Value:"{}",// Value must be a valid encoded JSON object.
},&runtime.StorageWrite{Collection:"save",Key:"save2",UserID:userID,Value:"{}",// Value must be a valid encoded JSON object.
},&runtime.StorageWrite{Collection:"public",Key:"save3",UserID:userID,Value:"{}",// Value must be a valid encoded JSON object.
PermissionRead:2,PermissionWrite:1,},&runtime.StorageWrite{Collection:"public",Key:"save4",UserID:userID,Value:"{}",// Value must be a valid encoded JSON object.
Version:"*",PermissionRead:2,PermissionWrite:1,},}_,err:=nk.StorageWrite(ctx,objectIDs)iferr!=nil{logger.WithField("err",err).Error("Storage write error.")}
The Type of stream, '2' for a chat channel for example.
subjectstringREQUIRED
The primary stream subject, typically a user ID.
subcontextstringREQUIRED
A secondary subject, for example for direct chat between two users.
labelstringREQUIRED
Meta-information about the stream, for example a chat room name.
datastringREQUIRED
The data to send.
presences[]runtime.Presence
all
Array of presences to receive the sent data.
reliableboolREQUIRED
Whether the sender has been validated prior.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
mode:=uint8(123)label:="label"// Data does not have to be JSON, but it's a convenient format.
data:="{\"some\":\"data\"}"nk.StreamSend(mode,"","",label,data,nil)
Retrieve a stream presence and metadata by user ID.
Parameters
Name
Default
Description
modeuintREQUIRED
The type of stream, '2' for a chat channel for example.
subjectstringREQUIRED
The primary stream subject, typically a user ID.
subcontextstringREQUIRED
A secondary subject, for example for direct chat between two users.
labelstringREQUIRED
Meta-information about the stream, for example a chat room name.
userIdstringREQUIRED
The user ID to fetch information for.
sessionIdstringREQUIRED
The current session ID for the user.
Returns
Name
Description
metaruntime.PresenceMeta
Presence and metadata for the user.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
mode:=uint8(123)label:="label"ifmetaPresence,err:=nk.StreamUserGet(mode,"","",label,userID,sessionID);err!=nil{// Handle error.
}elseifmetaPresence!=nil{logger.Info("User found on stream")}else{logger.Info("User not found on stream")}return"Success",nil
The Type of stream, '2' for a chat channel for example.
subjectstringREQUIRED
The primary stream subject, typically a user ID.
subcontextstringREQUIRED
A secondary subject, for example for direct chat between two users.
labelstringREQUIRED
Meta-information about the stream, for example a chat room name.
presenceREQUIRED
The presence to be kicked.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
mode:=uint8(123)label:="some chat room channel name"userID:="user ID to kick"sessionID:="session ID to kick"iferr:=nk.StreamUserKick(mode,"","",label,userID,sessionID);err!=nil{// Handle error.
}
The Type of stream, '2' for a chat channel for example.
subjectstringREQUIRED
The primary stream subject, typically a user ID.
subcontextstringREQUIRED
A secondary subject, for example for direct chat between two users.
labelstringREQUIRED
Meta-information about the stream, for example a chat room name.
userIdstringREQUIRED
The user ID to be removed.
sessionIdstringREQUIRED
The current session ID for the user.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
mode:=uint8(123)label:="some chat room channel name"userID:="user ID to leave"sessionID:="session ID to leave"iferr:=nk.StreamUserLeave(mode,"","",label,userID,sessionID);err!=nil{// Handle error.
}
List all users currently online and connected to a stream.
Parameters
Name
Default
Description
modeuintREQUIRED
The type of stream, '2' for a chat channel for example.
subjectstringREQUIRED
The primary stream subject, typically a user ID.
subcontextstringREQUIRED
A secondary subject, for example for direct chat between two users.
labelstringREQUIRED
Meta-information about the stream, for example a chat room name.
includeHiddenbool
Include stream presences marked as hidden in the results.
includeNotHiddenbool
Include stream presences not marked as hidden in the results.
Returns
Name
Description
presences[]runtime.Presence
Array of stream presences and their information.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
mode:=uint8(123)label:="label"includeHidden:=trueincludeNotHidden:=truemembers,err:=nk.StreamUserList(mode,"","",label,includeHidden,includeNotHidden)iferr!=nil{// Handle error here
}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
idstringREQUIRED
The unique identifier for the tournament to update.
ownerstringREQUIRED
The owner of the records to increment the count for.
countintREQUIRED
The number of attempt counts to increment. Can be negative to decrease count.
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
idstringREQUIRED
The unique identifier for the new tournament. This is used by clients to submit scores.
authoritativeboolREQUIRED
Whether the tournament created is server authoritative.
sortOrderstringREQUIRED
The sort order for records in the tournament. Possible values are "asc" or "desc".
operatorstringREQUIRED
The operator that determines how scores behave when submitted. The possible values are "best", "set", or "incr".
resetSchedulestringREQUIRED
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.
metadatamap[string]interfaceREQUIRED
The metadata you want associated to the tournament. Some good examples are weather conditions for a racing game.
titlestringREQUIRED
The title of the tournament.
descriptionstringREQUIRED
The description of the tournament.
categoryintREQUIRED
A category associated with the tournament. This can be used to filter different types of tournaments. Between 0 and 127.
startTimeint
The start time of the tournament. Leave empty for immediately or a future time.
endTimeint
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.
durationintREQUIRED
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.
maxSizeintREQUIRED
Maximum size of participants in a tournament.
maxNumScoreintREQUIRED
1000000
Maximum submission attempts for a tournament record.
joinRequiredboolREQUIRED
false
Whether the tournament needs to be joined before a record write is allowed.
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"authoritative:=falsesortOrder:="desc"// One of: "desc", "asc".
operator:="best"// One of: "best", "set", "incr".
resetSchedule:="0 12 * * *"// Noon UTC each day.
metadata:=map[string]interface{}{"weather_conditions":"rain",}title:="Daily Dash"description:="Dash past your opponents for high scores and big rewards!"category:=1startTime:=0// Start now.
endTime:=0// Never end, repeat the tournament each day forever.
duration:=3600// In seconds.
maxSize:=10000// First 10,000 players who join.
maxNumScore:=3// Each player can have 3 attempts to score.
joinRequired:=true// Must join to compete.
enableRanks:=true// Set to true to enable rank computation on leaderboard records.
err:=nk.TournamentCreate(ctx,id,authoritative,sortOrder,operator,resetSchedule,metadata,title,description,category,startTime,endTime,duration,maxSize,maxNumScore,joinRequired,enableRanks)iferr!=nil{logger.WithField("err",err).Error("Tournament create error.")}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
categoryStartintREQUIRED
Filter tournaments with categories greater or equal than this value.
categoryEndintREQUIRED
Filter tournaments with categories equal or less than this value.
startTimeintREQUIRED
Filter tournaments that start after this time.
endTimeintREQUIRED
Filter tournaments that end before this time.
limitintREQUIRED
10
Return only the required number of tournament denoted by this limit value.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
tournamentList[]*api.TournamentList
A list of tournament results and possibly a cursor. If cursor is empty/nil there are no further results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
categoryStart:=1categoryEnd:=2startTime:=int(time.Now().Unix())endTime:=0// All tournaments from the start time.
limit:=100// Number to list per page.
cursor:=""list,err:=nk.TournamentList(ctx,categoryStart,categoryEnd,startTime,endTime,limit,cursor)iferr!=nil{logger.WithField("err",err).Error("Tournament list error.")}else{for_,t:=rangelist.Tournaments{logger.Info("ID %s - can enter? %b",t.Id,t.CanEnter)}}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
tournamentIdstringREQUIRED
The ID of the tournament to list records for.
ownerIds[]stringREQUIRED
Array of owner IDs to filter results by.
limitintREQUIRED
Return only the required number of tournament records denoted by this limit value. Max is 10000.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
overrideExpiryintREQUIRED
Records with expiry in the past are not returned unless within this defined limit. Must be equal or greater than 0.
Returns
Name
Description
records[]*api.LeaderboardRecord
A page of tournament records.
ownerRecords[]*api.LeaderboardRecord
A list of owner tournament records (empty if the owners input parameter is not set).
prevCursorstring
An optional previous page cursor that can be used to retrieve the previous page of records (if any).
nextCursorstring
An optional next page cursor that can be used to retrieve the next page of records (if any).
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"limit:=100overrideExpiry:=0records,err:=nk.TournamentRecordsList(ctx,id,limit,overrideExpiry)iferr!=nil{logger.WithField("err",err).Error("Tournament records list error.")}else{for_,r:=rangerecords{logger.Info("Leaderboard: %s, score: %d, subscore: %d",r.GetLeaderboardId(),r.Score,r.Subscore)}}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
idstringREQUIRED
The unique identifier for the tournament leaderboard to submit to.
ownerstringREQUIRED
The owner of this score submission.
usernamestringREQUIRED
The owner username of this score submission, if it's a user.
scoreintREQUIRED
The score to submit.
subscoreint
A secondary subscore parameter for the submission.
metadatamap[string]interface
The metadata you want associated to this submission. Some good examples are weather conditions for a racing game.
Returns
Name
Description
result*api.LeaderboardRecord
The newly created leaderboard record.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
id:="4ec4f126-3f9d-11e7-84ef-b7c182b36521"ownerID:="4c2ae592-b2a7-445e-98ec-697694478b1c"username:="02ebb2c8"score:=int64(10)subscore:=int64(0)metadata:=map[string]interface{}{"weather_conditions":"rain",}_,err:=nk.TournamentRecordWrite(ctx,id,ownerID,username,score,subscore,metadata)iferr!=nil{logger.WithField("err",err).Error("Tournament record write error.")}
The context object represents information about the server and requester.
ids[]stringREQUIRED
The table array of tournament ids.
Returns
Name
Description
result[]*api.Tournament
Array of tournament records.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
tournamentIDs:=[]string{"3ea5608a-43c3-11e7-90f9-7b9397165f34","447524be-43c3-11e7-af09-3f7172f05936",}tournaments,err:=nk.TournamentsGetId(ctx,tournamentIDs)iferr!=nil{logger.WithField("err",err).Error("Tournaments get error.")}
The context object represents information about the server and requester.
userIds[]stringREQUIRED
An array of user IDs to ban.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
userIDs:=[]string{"3ea5608a-43c3-11e7-90f9-7b9397165f34","447524be-43c3-11e7-af09-3f7172f05936",}err:=nk.UsersBanId(ctx,userIDs)iferr!=nil{logger.WithField("err",err).Error("Users ban ID error.")}
The context object represents information about the server and requester.
userIds[]stringREQUIRED
An array of user IDs to fetch.
Returns
Name
Description
users[]*api.User
A list of user record objects.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
userIDs:=[]string{"3ea5608a-43c3-11e7-90f9-7b9397165f34","447524be-43c3-11e7-af09-3f7172f05936",}users,err:=nk.UsersGetId(ctx,userIDs)iferr!=nil{logger.WithField("err",err).Error("Users get ID error.")}else{for_,u:=rangeusers{logger.Info("username: %s, displayname: %s",u.Username,u.DisplayName)}}
The context object represents information about the server and requester.
countintREQUIRED
The number of users to fetch.
Returns
Name
Description
users[]*api.User
A list of user record objects.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
users,err:=nk.UsersGetRandom(ctx,10)iferr!=nil{logger.WithField("err",err).Error("Users get random error.")}else{for_,u:=rangeusers{logger.Info("id: %s, displayname: %s",u.Id,u.DisplayName)}}
The context object represents information about the server and requester.
userIds[]stringREQUIRED
An array of user IDs to unban.
Returns
Name
Description
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
userIDs:=[]string{"3ea5608a-43c3-11e7-90f9-7b9397165f34","447524be-43c3-11e7-af09-3f7172f05936",}err:=nk.UsersUnbanId(ctx,userIDs)iferr!=nil{logger.WithField("err",err).Error("Users unban id error.")}
List all wallet updates for a particular user from oldest to newest.
Parameters
Name
Default
Description
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
userIdstringREQUIRED
The ID of the user to list wallet updates for.
limitint
100
Limit number of results.
cursorstring
Pagination cursor from previous result. Don't set to start fetching from the beginning.
Returns
Name
Description
runtimeItems[]runtime.WalletLedgerItem
A Go slice containing wallet entries with Id, UserId, CreateTime, UpdateTime, Changeset, Metadata parameters.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
userID:="8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"items,err:=nk.WalletLedgerList(ctx,userID)iferr!=nil{logger.WithField("err",err).Error("Wallet ledger list error.")}else{for_,item:=rangeitems{logger.Info("Found wallet update with id: %v",item.GetID())}}
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
ctxcontext.ContextREQUIRED
The context object represents information about the server and requester.
updates[]*runtime.WalletUpdateREQUIRED
The set of user wallet update operations to apply.
updateLedgerboolREQUIRED
false
Whether to record this update in the ledger.
Returns
Name
Description
updateWallets[]runtime.WalletUpdateResult
A list of wallet update results.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
updates:=[]*runtime.WalletUpdate{&runtime.WalletUpdate{UserID:"8f4d52c7-bf28-4fcf-8af2-1d4fcf685592",Changeset:map[string]interface{}{"coins":10,// Add 10 coins to the user's wallet.
"gems":-5,// Remove 5 gems from the user's wallet.
},Metadata:map[string]interface{}{"game_result":"won",},},}err:=nk.WalletsUpdate(ctx,updates,true)iferr!=nil{logger.WithField("err",err).Error("Wallets update error.")}
The context object represents information about the server and requester.
userIdstringREQUIRED
The ID of the user whose wallet to update.
changesetmap[string]intREQUIRED
The set of wallet operations to apply.
metadatamap[string]interfaceREQUIRED
Additional metadata to tag the wallet update with.
updateLedgerboolREQUIRED
false
Whether to record this update in the ledger.
Returns
Name
Description
updatedValuemap
The updated wallet value.
previousValuemap
The previous wallet value.
errorerror
An optional error value if an error occurred.
1
2
3
4
5
6
7
8
9
10
11
12
userID:="8f4d52c7-bf28-4fcf-8af2-1d4fcf685592"changeset:=map[string]interface{}{"coins":10,// Add 10 coins to the user's wallet.
"gems":-5,// Remove 5 gems from the user's wallet.
}metadata:=map[string]interface{}{"game_result":"won",}updated,previous,err:=nk.WalletUpdate(ctx,userID,changeset,metadata,true)iferr!=nil{logger.WithField("err",err).Error("Wallet update error.")}