🔌 REST API v1
Time clock integration for external applications – e.g. FiveM servers, custom bots or scripts
The public REST API lets external applications clock Discord users in and out, query their clock status and send heartbeats. All requests go through the base URL:
https://shiftwatch.de/api/v1
🔑 Authentication
Every request needs a guild-scoped API key. Server admins create keys in the Admin Dashboard → Settings → API Keys (max. 5 active keys per server).
⚠️ Important: The full key is shown only once when it is created. Store it securely (server-side config, never in client code). If a key leaks, revoke it in the dashboard – access is cut off immediately.
Send the key in one of two headers:
Authorization: Bearer sk_<64 hex chars>
X-API-Key: sk_<64 hex chars>
The key determines which Discord server the request applies to – there is no guild parameter.
📡 Endpoints
Clocks a user in. The user must be a member of the Discord server.
Example request
curl -X POST https://shiftwatch.de/api/v1/clock-in \
-H "Authorization: Bearer sk_..." \
-H "Content-Type: application/json" \
-d '{"user_id": "123456789012345678"}'
Response 200
{
"success": true,
"user_id": "123456789012345678",
"guild_id": "987654321098765432",
"source": "api",
"entry": {
"id": 42,
"clock_in": 1751882400,
"clock_in_iso": "2026-07-07T10:00:00.000Z"
}
}
Side effects are identical to clocking in via the Discord button: the on-duty role is assigned, a log embed is posted to the configured log channel (source: "via API"), the leaderboard refreshes and open dashboards receive a live update.
Clocks a user out.
Example request
curl -X POST https://shiftwatch.de/api/v1/clock-out \
-H "Authorization: Bearer sk_..." \
-H "Content-Type: application/json" \
-d '{"user_id": "123456789012345678"}'
Response 200
{
"success": true,
"user_id": "123456789012345678",
"guild_id": "987654321098765432",
"source": "api",
"entry": {
"id": 42,
"clock_in": 1751882400,
"clock_out": 1751911200,
"clock_in_iso": "2026-07-07T10:00:00.000Z",
"clock_out_iso": "2026-07-07T18:00:00.000Z",
"duration_minutes": 480
}
}
Resets the auto-clockout timer for up to 100 users in one request – the API equivalent of pressing the "I'm still here" button in Discord. Send this periodically (e.g. every 5 minutes) for all players currently online on your game server. Users who are not clocked in are simply reported back with clocked_in: false (no error), so you can use the response to keep your local state in sync.
If a user already received an auto-clockout warning in Discord (e.g. they just rejoined the game), the heartbeat clears the pending warning and deletes the warning message – they will not be auto-clocked-out.
Example request
curl -X POST https://shiftwatch.de/api/v1/heartbeat \
-H "Authorization: Bearer sk_..." \
-H "Content-Type: application/json" \
-d '{"user_ids": ["123456789012345678", "234567890123456789"]}'
Response 200
{
"success": true,
"guild_id": "987654321098765432",
"results": [
{ "user_id": "123456789012345678", "clocked_in": true },
{ "user_id": "234567890123456789", "clocked_in": false }
]
}
Returns the current clock status of a user. Unknown users return clocked_in: false.
Example request
curl https://shiftwatch.de/api/v1/status/123456789012345678 \
-H "Authorization: Bearer sk_..."
Response 200
{
"user_id": "123456789012345678",
"guild_id": "987654321098765432",
"clocked_in": true,
"session": {
"id": 42,
"clock_in": 1751882400,
"clock_in_iso": "2026-07-07T10:00:00.000Z",
"duration_minutes": 125
}
}
⚠️ Errors
All errors use the shape { "error": "<code>", "message": "<human readable>" }.
| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | Missing/invalid user_id / user_ids (must be Discord IDs, 17–20 digits; heartbeat: 1–100 per request) |
| 401 | missing_api_key | No API key header sent |
| 401 | invalid_api_key | Key unknown, malformed or revoked |
| 404 | user_not_in_guild | The user is not a member of the guild |
| 409 | already_clocked_in | Clock-in refused; response includes current_session |
| 409 | not_clocked_in | Clock-out refused; the user has no open session |
| 429 | rate_limited | Rate limit exceeded, retry later |
| 503 | guild_unavailable | The bot is not on the guild or not ready yet |
🚦 Rate limits
- 60 requests/minute per API key
- 120 requests/minute per IP (counted before authentication)
Standard RateLimit-* response headers are included.
💓 Auto-clockout & heartbeats – how they work together
The bot has a built-in auto-clockout: after a configurable period without activity, the user receives a warning in Discord and is automatically clocked out if they don't react in time. Without further action, a player clocked in via the API would have to confirm that warning in Discord every few hours – while actively playing. The heartbeat endpoint solves this. The recommended integration pattern:
- Clock-in when the player starts their duty (
POST /clock-in). - Heartbeat loop: every ~5 minutes, send one
POST /heartbeatwith the Discord IDs of all clocked-in players currently online. As long as heartbeats arrive, the timer keeps resetting and no Discord warning is ever sent. - Clock-out on disconnect and shutdown: hook your platform's disconnect event (FiveM:
playerDropped) and callPOST /clock-out. Clean sessions then end immediately when the player leaves. When the game server restarts, the disconnect event often no longer runs or the request never goes out. There are dedicated hooks for that: Robloxgame:BindToClose, MinecraftonDisable(), FiveM with txAdmintxAdmin:events:serverShuttingDown. If a request fails with 429, 5xx or a network error, send it again after a few seconds. The examples below do both. - Crash safety net: if the game server crashes or the disconnect handler never runs, heartbeats simply stop. After the configured inactivity period the normal Discord flow takes over: a warning (the user can still react to it), otherwise auto-clockout. No session runs forever. The time until the warning is still counted, though. This is a safety net, not a replacement for a clean clock-out.
Pick a heartbeat interval well below the server's configured warning time (5 minutes is plenty) and batch all players into one request – 100 users per call keeps you far away from the rate limit.
🎮 Integration examples
The pattern is the same on every platform: resolve the user's Discord ID, call clock-in/clock-out at the right moments and send heartbeats while the user is active. The following examples are ready-made starting points for the most common use cases:
FiveM exposes each player's Discord ID via the discord: identifier. Complete server-side integration with clock-in/out commands, heartbeat loop and disconnect handling:
Set the API key via set stempeluhr_api_key "sk_..." in your server.cfg – never put it in client code!
local API_BASE = "https://shiftwatch.de/api/v1"
local API_KEY = GetConvar("stempeluhr_api_key", "")
local function getDiscordId(src)
for _, id in ipairs(GetPlayerIdentifiers(src)) do
if id:sub(1, 8) == "discord:" then
return id:sub(9)
end
end
end
-- POST with up to 3 attempts on network errors (status 0), 429 and 5xx.
-- cb(status, body) runs once with the final result.
local function apiPost(path, payload, cb, attempt)
attempt = attempt or 1
PerformHttpRequest(API_BASE .. path, function(status, body)
if (status == 0 or status == 429 or status >= 500) and attempt < 3 then
SetTimeout(attempt * 2000, function()
apiPost(path, payload, cb, attempt + 1)
end)
return
end
-- 409 = already clocked in / not clocked in, harmless
if status ~= 200 and status ~= 409 then
print(("[Shiftwatch] %s failed: %s"):format(path, status))
end
if cb then cb(status, status == 200 and body and json.decode(body) or nil) end
end, "POST", json.encode(payload), {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer " .. API_KEY
})
end
-- Discord ID -> true for every clocked-in player
local clockedIn = {}
local function clockOut(discordId)
if clockedIn[discordId] then
clockedIn[discordId] = nil
apiPost("/clock-out", { user_id = discordId })
end
end
RegisterCommand("clockin", function(src)
local discordId = getDiscordId(src)
if not discordId then return end
apiPost("/clock-in", { user_id = discordId }, function(status)
-- 409: already clocked in, e.g. via the Discord button
if status == 200 or status == 409 then
clockedIn[discordId] = true
-- TODO: notify the player in-game
end
end)
end, false)
RegisterCommand("clockout", function(src)
local discordId = getDiscordId(src)
if not discordId then return end
apiPost("/clock-out", { user_id = discordId }, function(status)
if status == 200 or status == 409 then
clockedIn[discordId] = nil
end
end)
end, false)
-- Disconnect: clock out immediately
AddEventHandler("playerDropped", function()
local discordId = getDiscordId(source)
if discordId then
clockOut(discordId)
end
end)
-- Restart/stop via txAdmin: the process is killed after eventData.delay
-- milliseconds, so clock everyone out right away
AddEventHandler("txAdmin:events:serverShuttingDown", function()
for discordId in pairs(clockedIn) do
clockOut(discordId)
end
end)
-- Heartbeat loop: right away, then every 5 minutes for all online players
-- with a Discord ID (max. 100 per request). Prevents the auto-clockout
-- warning in Discord while playing and syncs clockedIn with the API,
-- e.g. after a resource restart or a clock-out in the dashboard.
CreateThread(function()
while true do
local ids = {}
for _, src in ipairs(GetPlayers()) do
local discordId = getDiscordId(src)
if discordId then
ids[#ids + 1] = discordId
end
end
for i = 1, #ids, 100 do
local batch = { table.unpack(ids, i, math.min(i + 99, #ids)) }
apiPost("/heartbeat", { user_ids = batch }, function(status, body)
if status == 200 and body then
for _, r in ipairs(body.results) do
clockedIn[r.user_id] = r.clocked_in or nil
end
end
end)
end
Wait(5 * 60 * 1000)
end
end)
Roblox has no Discord identifiers – the mapping is handled by a linking system like Bloxlink, which players link once (standard in most Roblox Discord communities anyway). The server script resolves the Discord ID via the Bloxlink API and clocks players in and out when they join or leave the game:
Requirements: enable HttpService (Game Settings → Security → "Allow HTTP Requests") and use both keys only in server scripts (ServerScriptService), never in LocalScripts or ReplicatedStorage. Replace DISCORD_GUILD_ID with the ID of your own Discord server, the one your Bloxlink key was created for (enable Developer Mode in Discord, then right-click the server → "Copy Server ID").
-- Server script (ServerScriptService)
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local API_BASE = "https://shiftwatch.de/api/v1"
local API_KEY = "sk_..." -- e.g. from a private server module
local BLOXLINK_KEY = "..." -- Bloxlink server key (Developer API)
-- Replace with your own Discord server ID (the server your Bloxlink key
-- was created for). Only used for the Bloxlink lookup, Shiftwatch itself
-- takes the server from the API key.
local DISCORD_GUILD_ID = "YOUR_GUILD_ID"
-- Resolve the Discord ID of a linked player via the Bloxlink API
local discordIdCache = {}
local function getDiscordId(player)
if discordIdCache[player.UserId] ~= nil then
return discordIdCache[player.UserId]
end
local ok, res = pcall(function()
return HttpService:RequestAsync({
Url = "https://api.blox.link/v4/public/guilds/" .. DISCORD_GUILD_ID
.. "/roblox-to-discord/" .. player.UserId,
Method = "GET",
Headers = { Authorization = BLOXLINK_KEY }
})
end)
local discordId
if ok and res.Success then
local data = HttpService:JSONDecode(res.Body)
discordId = data.discordIDs and data.discordIDs[1] or nil
end
discordIdCache[player.UserId] = discordId
return discordId
end
-- POST with up to 3 attempts on network errors, 429 and 5xx.
-- Returns status code and raw body (status nil = no response).
local function apiPost(path, payload)
local status, body
for attempt = 1, 3 do
local ok, res = pcall(function()
return HttpService:RequestAsync({
Url = API_BASE .. path,
Method = "POST",
Headers = {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer " .. API_KEY
},
Body = HttpService:JSONEncode(payload)
})
end)
status = ok and res.StatusCode or nil
body = ok and res.Body or nil
if status and status ~= 429 and status < 500 then
break
end
if attempt < 3 then
task.wait(attempt * 2)
end
end
-- 409 = already clocked in / not clocked in, harmless
if status ~= 200 and status ~= 409 then
warn("[Shiftwatch] " .. path .. " failed: " .. tostring(status) .. " " .. tostring(body))
end
return status, body
end
-- Discord ID -> true for every clocked-in player
local clockedIn = {}
local pendingClockOuts = 0
local function clockOut(discordId)
if not clockedIn[discordId] then return end
clockedIn[discordId] = nil
pendingClockOuts += 1
apiPost("/clock-out", { user_id = discordId })
pendingClockOuts -= 1
end
-- Clock in on join, clock out on leave
Players.PlayerAdded:Connect(function(player)
local discordId = getDiscordId(player)
if not discordId then return end
local status = apiPost("/clock-in", { user_id = discordId })
if status == 200 or status == 409 then
clockedIn[discordId] = true
-- Player left while the requests were still running
if not player.Parent then
clockOut(discordId)
end
end
end)
Players.PlayerRemoving:Connect(function(player)
local discordId = discordIdCache[player.UserId]
if discordId then
clockOut(discordId)
end
end)
-- Server shutdown (last player left, update, "Shut Down All Servers"):
-- without this, Roblox closes the server before the clock-outs are sent.
-- BindToClose gets at most 30 seconds.
game:BindToClose(function()
for _, player in ipairs(Players:GetPlayers()) do
local discordId = discordIdCache[player.UserId]
if discordId then
task.spawn(clockOut, discordId)
end
end
local deadline = os.clock() + 25
while pendingClockOuts > 0 and os.clock() < deadline do
task.wait(0.5)
end
end)
-- Heartbeat loop: every 5 minutes for all clocked-in online players
task.spawn(function()
while true do
task.wait(300)
local ids = {}
for _, player in ipairs(Players:GetPlayers()) do
local discordId = discordIdCache[player.UserId]
if discordId and clockedIn[discordId] then
table.insert(ids, discordId)
end
end
if #ids > 0 then
local status, body = apiPost("/heartbeat", { user_ids = ids })
if status == 200 then
-- Sync local state (e.g. an admin clocked the
-- player out in the dashboard -> clocked_in: false)
for _, r in ipairs(HttpService:JSONDecode(body).results) do
if not r.clocked_in then
clockedIn[r.user_id] = nil
end
end
end
end
end
end)
On Minecraft servers (Paper/Spigot), DiscordSRV provides the link between Minecraft accounts and Discord IDs – players link once via /discord link. A small plugin then clocks them in on join and out on quit:
Store the API key in the plugin's config.yml – never hardcode it or commit it to your repository.
// Paper/Spigot plugin, DiscordSRV as the account link source.
// In your JavaPlugin:
// onEnable(): hook = new StempeluhrHook(getLogger(), getConfig().getString("api-key"));
// getServer().getPluginManager().registerEvents(hook, this);
// onDisable(): hook.shutdown();
public final class StempeluhrHook implements Listener {
private static final String API_BASE = "https://shiftwatch.de/api/v1";
private final String apiKey;
private final Logger logger;
private final HttpClient http = HttpClient.newHttpClient();
// One worker thread for all API calls: keeps clock-in and clock-out
// of a player in order and network I/O off the main thread
private final ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
// Player UUID -> Discord ID of every linked online player (worker thread only)
private final Map<UUID, String> linked = new HashMap<>();
public StempeluhrHook(Logger logger, String apiKey) {
this.logger = logger;
this.apiKey = apiKey;
worker.scheduleAtFixedRate(this::heartbeat, 1, 5, TimeUnit.MINUTES);
}
// POST with up to 3 attempts on network errors, 429 and 5xx
private void post(String path, String json) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE + path))
.timeout(Duration.ofSeconds(10))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
String result = "no response";
try {
for (int attempt = 1; attempt <= 3; attempt++) {
try {
HttpResponse<String> res =
http.send(request, HttpResponse.BodyHandlers.ofString());
// 409 = already clocked in / not clocked in, harmless
if (res.statusCode() == 200 || res.statusCode() == 409) return;
result = res.statusCode() + " " + res.body();
if (res.statusCode() != 429 && res.statusCode() < 500) break;
} catch (IOException e) {
result = e.toString();
}
if (attempt < 3) Thread.sleep(attempt * 2000L);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
logger.warning(path + " failed: " + result);
}
private static String userJson(String discordId) {
return "{\"user_id\": \"" + discordId + "\"}";
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
UUID uuid = event.getPlayer().getUniqueId();
worker.execute(() -> {
String discordId = DiscordSRV.getPlugin().getAccountLinkManager()
.getDiscordId(uuid);
if (discordId != null) {
linked.put(uuid, discordId);
post("/clock-in", userJson(discordId));
}
});
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
UUID uuid = event.getPlayer().getUniqueId();
worker.execute(() -> {
String discordId = linked.remove(uuid);
if (discordId != null) {
post("/clock-out", userJson(discordId));
}
});
}
// Heartbeat for all linked online players, max. 100 IDs per request
private void heartbeat() {
List<String> ids = new ArrayList<>(linked.values());
for (int i = 0; i < ids.size(); i += 100) {
List<String> batch = ids.subList(i, Math.min(i + 100, ids.size()));
post("/heartbeat", "{\"user_ids\": [\"" + String.join("\", \"", batch) + "\"]}");
}
}
// On /stop the plugin is disabled before players are kicked, so onQuit
// no longer runs for them. Clock everyone out here (waits max. 20 s).
public void shutdown() {
worker.execute(() -> {
for (String discordId : linked.values()) {
post("/clock-out", userJson(discordId));
}
linked.clear();
});
worker.shutdown();
try {
worker.awaitTermination(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
You can also use the API from your own Discord bot – for example for voice duty tracking: whoever joins the "on duty" voice channel gets clocked in, whoever leaves gets clocked out. The bot has the Discord IDs right at hand:
const { Client, GatewayIntentBits } = require('discord.js');
const API_BASE = 'https://shiftwatch.de/api/v1';
const API_KEY = process.env.STEMPELUHR_API_KEY;
const DUTY_CHANNEL_ID = '123456789012345678'; // "on duty" voice channel
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// POST with up to 3 attempts on network errors, 429 and 5xx.
// Never throws: an unhandled rejection would terminate the bot.
async function apiPost(path, payload) {
let status = 0;
let body = null;
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const res = await fetch(API_BASE + path, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10000)
});
status = res.status;
body = await res.json().catch(() => null);
} catch {
status = 0;
body = null;
}
if (status !== 0 && status !== 429 && status < 500) break;
if (attempt < 3) await sleep(attempt * 2000);
}
// 409 = already clocked in / not clocked in, harmless
if (status !== 200 && status !== 409) {
console.warn(`[Shiftwatch] ${path} failed: ${status}`, body);
}
return { status, body };
}
// API calls run one after another, so a quick join + leave
// can't overtake each other
let queue = Promise.resolve();
const enqueue = (task) => (queue = queue.then(task));
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates]
});
// Joining the duty channel clocks in, leaving clocks out
client.on('voiceStateUpdate', (oldState, newState) => {
const joined = newState.channelId === DUTY_CHANNEL_ID
&& oldState.channelId !== DUTY_CHANNEL_ID;
const left = oldState.channelId === DUTY_CHANNEL_ID
&& newState.channelId !== DUTY_CHANNEL_ID;
if (joined) enqueue(() => apiPost('/clock-in', { user_id: newState.id }));
if (left) enqueue(() => apiPost('/clock-out', { user_id: newState.id }));
});
// Heartbeat every 5 minutes for everyone in the duty channel
setInterval(async () => {
try {
const channel = await client.channels.fetch(DUTY_CHANNEL_ID);
const ids = [...channel.members.keys()];
if (ids.length > 0) {
await enqueue(() => apiPost('/heartbeat', { user_ids: ids }));
}
} catch (error) {
console.error('[Shiftwatch] Heartbeat failed:', error.message);
}
}, 5 * 60 * 1000);
client.login(process.env.DISCORD_TOKEN);
For scripts, cron jobs, custom tools or a kiosk terminal, a minimal Python client is all you need:
import os
import time
import requests
API_BASE = "https://shiftwatch.de/api/v1"
session = requests.Session()
session.headers.update({
"Authorization": "Bearer " + os.environ["STEMPELUHR_API_KEY"]
})
def request(method, path, payload=None):
"""Up to 3 attempts on network errors, 429 and 5xx.
Returns (status, body), status 0 = no response."""
code, body = 0, None
for attempt in range(1, 4):
try:
res = session.request(method, API_BASE + path,
json=payload, timeout=10)
code = res.status_code
try:
body = res.json()
except ValueError:
body = None
except requests.RequestException:
code, body = 0, None
if code and code != 429 and code < 500:
break
if attempt < 3:
time.sleep(attempt * 2)
return code, body
def clock_in(user_id):
return request("POST", "/clock-in", {"user_id": user_id})
def clock_out(user_id):
return request("POST", "/clock-out", {"user_id": user_id})
def heartbeat(user_ids):
return request("POST", "/heartbeat", {"user_ids": user_ids})
def status(user_id):
return request("GET", "/status/" + user_id)
# Example: clock a user in and show the running session.
# Every call returns (status, body), e.g. (200, {...}) or
# (409, {"error": "already_clocked_in", ...})
print(clock_in("123456789012345678"))
print(status("123456789012345678"))
In general, any environment that can send HTTP requests works – e.g. Garry's Mod, Rust, alt:V, RAGE:MP, custom intranet tools or automation platforms like n8n. The only requirement: you can map the user to a Discord ID. Missing an example for your platform? Reach out on the support server.