CTK Games docs
Add accounts, saves, leaderboards and friends to your game with our Python and C# modules.
Install
The Python module needs Python 3.8 or newer and nothing else. The C# module works with .NET and Godot, and you can download it here.
pip install https://games.ctksystem.com/downloads/ctkgames-python.zip
dotnet add reference path/to/CtkGames/CtkGames.csproj
Using Unity 2021 or newer? Copy the CtkGames folder from the download into Assets, delete CtkGames.csproj from the copy, and add the package com.unity.nuget.newtonsoft-json in the Package Manager.
You'll need a game id too. Make a game in the developer dashboard, which takes a Developer Account (one-time 7€).
Quick start
from ctkgames import CTKClient
ctk = CTKClient(game_id="my-game")
if not ctk.login_with_launcher():
ctk.login("[email protected]", "password")
ctk.data.save({"coins": 50, "checkpoint": 3}) # private
ctk.stats.save({"kills": 12}) # public
for row in ctk.stats.leaderboard("kills", limit=10):
print(row["rank"], row["uid"], row["kills"])
using CtkGames;
var ctk = new CtkClient("my-game");
if (!await ctk.LoginWithLauncherAsync())
await ctk.LoginAsync("[email protected]", "password");
await ctk.Data.SaveAsync(new { coins = 50, checkpoint = 3 }); // private
await ctk.Stats.SaveAsync(new { kills = 12 }); // public
foreach (var row in await ctk.Stats.LeaderboardAsync("kills", limit: 10))
Console.WriteLine($"{row.Rank} {row.Uid} {row.Stat<int>("kills")}");
You set your game id once. To use another game for a single call, pass it to that call.
Where your data goes
Everything a game saves belongs to that game. Your saves never mix with another game's, and they don't go on the player's CTK account.
| Use | For | Who can read it |
|---|---|---|
| Data | Save files, settings, unlocks, anything private | The player and you |
| Stats | Numbers to show off: kills, wins, high scores | Everyone |
| Inventory | Items the player owns in your game | The player and you |
Don't put anything secret in stats. Anyone can read them without logging in.
Logging in
If the CTK Games Launcher started your game, the player is already signed in, so try that first. They won't see a login screen or type a password.
if ctk.login_with_launcher():
print("Signed in as", ctk.user["displayName"])
else:
show_login_screen()
if (await ctk.LoginWithLauncherAsync())
Console.WriteLine("Signed in as " + ctk.User.DisplayName);
else
ShowLoginScreen();
This returns false when there's no launcher session, for example if the player isn't signed in to the launcher. You'll also get false when you run the game yourself from your editor or a terminal, so keep a login screen for those cases.
Logging in with a password
ctk.register("[email protected]", "password", "PlayerName")
ctk.login("[email protected]", "password")
print(ctk.logged_in, ctk.uid)
ctk.logout()
await ctk.RegisterAsync("[email protected]", "password", "PlayerName");
await ctk.LoginAsync("[email protected]", "password");
Console.WriteLine($"{ctk.LoggedIn} {ctk.Uid}");
ctk.Logout();
Registering doesn't log the player in, so call login afterwards. Display names are 2-16 characters.
Staying logged in
Sessions renew themselves while your game runs. Players who log in with a password can skip it next time if you save the session to a file:
if not ctk.login_with_launcher() and not ctk.load_session("session.json"):
ctk.login(email, password)
ctk.save_session("session.json")
if (!await ctk.LoginWithLauncherAsync() && !ctk.LoadSession(path))
{
await ctk.LoginAsync(email, password);
ctk.SaveSession(path);
}
That file can log in as the player, so keep it in their own app data folder and never ship it with your game.
Saving player data
Save any JSON you like. Saving only changes the keys you pass, the rest stay as they were.
ctk.data.save({"coins": 50, "map": [[1, 0], [0, 1]]})
ctk.data.save({"coins": 75}) # map is kept
save = ctk.data.get()
print(save["coins"])
ctk.data.delete("map") # remove one key
ctk.data.clear() # remove everything, inventory stays
var map = new[] { new[] { 1, 0 }, new[] { 0, 1 } };
await ctk.Data.SaveAsync(new { coins = 50, map });
await ctk.Data.SaveAsync(new { coins = 75 }); // map is kept
var save = await ctk.Data.GetAsync();
Console.WriteLine((int)save["coins"]);
await ctk.Data.DeleteAsync("map"); // remove one key
await ctk.Data.ClearAsync(); // remove everything, inventory stays
Looking at a player's save
As the game's developer you can read a player's save or wipe it, which helps with support:
ctk.data.player("PLAYER_UID") # {"data": {...}, "inventory": [...]}
ctk.data.wipe_player("PLAYER_UID") # deletes data and inventory
var player = await ctk.Data.PlayerAsync("PLAYER_UID");
await ctk.Data.WipePlayerAsync("PLAYER_UID"); // deletes data and inventory
Stats and leaderboards
Use any field names you like. Reading stats and leaderboards doesn't need a login.
ctk.stats.save({"kills": 12, "wins": 3})
mine = ctk.stats.get()
theirs = ctk.stats.player("PLAYER_UID")
top = ctk.stats.leaderboard("kills", limit=10)
print(top[0]["rank"], top[0]["uid"], top[0]["kills"])
await ctk.Stats.SaveAsync(new { kills = 12, wins = 3 });
var mine = await ctk.Stats.GetAsync();
var theirs = await ctk.Stats.PlayerAsync("PLAYER_UID");
var top = await ctk.Stats.LeaderboardAsync("kills", limit: 10);
Console.WriteLine($"{top[0].Rank} {top[0].Uid} {top[0].Stat<int>("kills")}");
Leaderboards go from highest to lowest, 100 rows at most. Players who don't have that field aren't listed. To clear a cheater's stats, the game's developer can call wipe player with their UID.
Inventory
Each game has its own inventory, so an item in your game doesn't exist in any other.
ctk.inventory.add("sword", "Iron Sword")
ctk.inventory.add("potion", quantity=5)
ctk.inventory.remove("potion", quantity=2)
for item in ctk.inventory.list():
print(item["itemName"], item["quantity"])
await ctk.Inventory.AddAsync("sword", "Iron Sword");
await ctk.Inventory.AddAsync("potion", quantity: 5);
await ctk.Inventory.RemoveAsync("potion", quantity: 2);
foreach (var item in await ctk.Inventory.ListAsync())
Console.WriteLine($"{item.ItemName} {item.Quantity}");
An item disappears when its quantity reaches 0. Removing more than the player has gives an error and changes nothing.
Friends and profiles
friends = ctk.friends.list() # UIDs
waiting = ctk.friends.requests() # UIDs
ctk.friends.send_request("PLAYER_UID")
ctk.friends.accept("PLAYER_UID")
ctk.friends.remove("PLAYER_UID")
profile = ctk.profiles.get("PLAYER_UID")
print(profile["displayName"], profile["bio"])
ctk.profiles.set_bio("Hello!")
ctk.account.set_display_name("NewName")
ctk.account.set_presence("online")
var friends = await ctk.Friends.ListAsync(); // UIDs
var waiting = await ctk.Friends.RequestsAsync(); // UIDs
await ctk.Friends.SendRequestAsync("PLAYER_UID");
await ctk.Friends.AcceptAsync("PLAYER_UID");
await ctk.Friends.RemoveAsync("PLAYER_UID");
var profile = await ctk.Profiles.GetAsync("PLAYER_UID");
Console.WriteLine($"{profile.DisplayName} {profile.Bio}");
await ctk.Profiles.SetBioAsync("Hello!");
await ctk.Account.SetDisplayNameAsync("NewName");
await ctk.Account.SetPresenceAsync("online");
Downloads and purchases
games = ctk.games.list()
ban = ctk.games.check_ban() # {"banned": False}
ctk.games.download("data/level1.pak", "level1.pak",
on_progress=lambda done, total: print(done, "/", total))
order = ctk.purchases.create_order("some-paid-game")
webbrowser.open(order["approvalLink"])
ctk.purchases.wait_for_order(order["orderId"])
var games = await ctk.Games.ListAsync();
var ban = await ctk.Games.CheckBanAsync();
await ctk.Games.DownloadAsync("data/level1.pak", "level1.pak",
onProgress: (done, total) => Console.WriteLine($"{done} / {total}"));
var order = await ctk.Purchases.CreateOrderAsync("some-paid-game");
var browser = new ProcessStartInfo(order.ApprovalLink);
browser.UseShellExecute = true;
Process.Start(browser);
await ctk.Purchases.WaitForOrderAsync(order.OrderId);
Downloading a paid game needs the player to own it. The approval link opens PayPal in their browser, and waiting on the order returns once they've paid.
Managing your games
You can do all of this in the developer dashboard too. Code is handy for build scripts.
ctk.dev.create_game("my-game", "My Game", description="A fun game")
ctk.dev.update_game(title="My Better Game")
ctk.dev.upload_version("build.zip", "1.2.0",
on_progress=lambda done, total: print(done, "/", total))
ctk.dev.publish()
print(ctk.dev.dashboard()["totalGames"], ctk.dev.versions())
ctk.dev.ban("PLAYER_UID", "Cheating")
ctk.dev.unban("PLAYER_UID")
print(ctk.dev.bans())
await ctk.Dev.CreateGameAsync(new NewGame
{
Id = "my-game",
Title = "My Game",
Description = "A fun game"
});
await ctk.Dev.UpdateGameAsync(new { title = "My Better Game" });
await ctk.Dev.UploadVersionAsync("build.zip", "1.2.0",
onProgress: (done, total) => Console.WriteLine($"{done} / {total}"));
await ctk.Dev.PublishAsync();
var dashboard = await ctk.Dev.DashboardAsync();
var versions = await ctk.Dev.VersionsAsync();
await ctk.Dev.BanAsync("PLAYER_UID", "Cheating");
await ctk.Dev.UnbanAsync("PLAYER_UID");
var bans = await ctk.Dev.BansAsync();
New games stay hidden until you publish them. Banned players can't load or save their stats, data or inventory in that game.
Errors
| Python | C# | What happened |
|---|---|---|
AuthError | CtkAuthException | Not logged in, wrong password, or the session ended |
BannedError | CtkBannedException | Banned from CTK Games or from this game |
ForbiddenError | CtkForbiddenException | Not allowed, for example it isn't your game |
NotFoundError | CtkNotFoundException | That game, player, order or file doesn't exist |
ConnectionFailed | CtkConnectionException | The server couldn't be reached |
CTKError | CtkException | Anything else, and the base of all of the above |
from ctkgames import AuthError, BannedError, ConnectionFailed, CTKError
try:
ctk.data.save({"coins": 50})
except BannedError as err:
print("Banned:", err.reason)
except AuthError:
show_login_screen()
except ConnectionFailed:
print("Offline")
except CTKError as err:
print(err.status, err.message)
try
{
await ctk.Data.SaveAsync(new { coins = 50 });
}
catch (CtkBannedException err) { Console.WriteLine("Banned: " + err.Reason); }
catch (CtkAuthException) { ShowLoginScreen(); }
catch (CtkConnectionException) { Console.WriteLine("Offline"); }
catch (CtkException err) { Console.WriteLine($"{err.Status} {err.Message}"); }
Limits
- Data: 512 KB per player in each game, and about 100 KB in one save
- Inventory: 1000 different items per player in each game, item ids up to 64 characters
- Leaderboards: 100 rows
- Uploads: zip files up to 8 GB
Your game runs on the player's computer, so a player can change what it sends. Don't rely on saves, stats or items for anything that has to be fair or worth real money.
Using the API directly
Using another language? Everything is plain HTTP and JSON. All paths start with https://server.ctksystem.com/games.
Log in to get a token, then send it on every call marked "login" below. Tokens last an hour. Errors come back as {"error": "message"}.
curl -X POST https://server.ctksystem.com/games/account/login \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "password"}'
curl -X POST https://server.ctksystem.com/games/sdk/data/my-game \
-H "Authorization: Bearer YOUR_ID_TOKEN" \
-H "Content-Type: application/json" \
-d '{"data": {"coins": 50}}'
| Call | Send | Needs |
|---|---|---|
POST /sdk/data/:gameId | {"data": {...}} | login |
GET /sdk/data/:gameId | login | |
DELETE /sdk/data/:gameId/key/:key | login | |
DELETE /sdk/data/:gameId | login | |
GET /sdk/data/:gameId/player/:uid | your game | |
DELETE /sdk/data/:gameId/player/:uid | your game | |
POST /sdk/stats/:gameId | {"stats": {...}} | login |
GET /sdk/stats/:gameId | login | |
GET /sdk/stats/:gameId/player/:uid | ||
GET /sdk/stats/:gameId/leaderboard | ?orderBy=kills&limit=10 | |
DELETE /sdk/stats/:gameId/player/:uid | your game | |
GET /sdk/inventory/:gameId | login | |
POST /sdk/inventory/:gameId/add | {"itemId", "itemName", "quantity"} | login |
POST /sdk/inventory/:gameId/remove | {"itemId", "quantity"} | login |
GET /profiles/:uid | ||
GET /friends | login | |
GET /friends/requests | login | |
POST /friends/request | {"to_uid"} | login |
POST /friends/accept | {"from_uid"} | login |
POST /friends/remove | {"friend_uid"} | login |
GET / | ||
GET /ban/check | ?gameId=my-game | login |
Signing in through the launcher
The launcher sets CTK_LAUNCHER_URL and CTK_LAUNCHER_KEY in your game's environment. Ask it for a token, and ask again when expiresIn runs out:
curl "$CTK_LAUNCHER_URL/token" -H "X-CTK-Launcher-Key: $CTK_LAUNCHER_KEY"
# {"idToken": "...", "expiresIn": 3500, "user": {...}}
This only works while the launcher is running your game.