Examples
Complete scripts in bash, Node.js and Python for common jobs.
Every example assumes these two variables. Create the keys first with /md web key create <name> <scope>.
export MD_URL="http://127.0.0.1:8765/v1"
export MD_KEY="mdk_..." # read or write key
export ADMIN_KEY="mdk_..." # admin key, only for config editsFor Node.js and Python the examples use these helpers:
const MD_URL = process.env.MD_URL;
const headers = { Authorization: `Bearer ${process.env.MD_KEY}` };
const get = async (path) => {
const res = await fetch(MD_URL + path, { headers });
const body = await res.json();
if (!body.ok) throw new Error(`${res.status} ${body.error.code}: ${body.error.message}`);
return body.data;
};import os, time, requests
BASE = os.environ["MD_URL"]
HEADERS = {"Authorization": f"Bearer {os.environ['MD_KEY']}"}
def get(path, **params):
r = requests.get(BASE + path, headers=HEADERS, params=params, timeout=10)
body = r.json()
if not body["ok"]:
raise RuntimeError(f"{r.status_code} {body['error']['code']}: {body['error']['message']}")
return body["data"]Check that the API is up
curl -s -o /dev/null -w "%{http_code}\n" "$MD_URL"200The index needs no key. With a key:
curl -s -H "Authorization: Bearer $MD_KEY" "$MD_URL/status" | jq '.data | {server, role, online}'{ "server": "lobby-1", "role": "lobby", "online": 31 }Uptime monitor
Exit code 0 when the API answers and no fresh server is draining unexpectedly. Run it from cron every minute.
#!/usr/bin/env bash
status=$(curl -fsS -m 5 -H "Authorization: Bearer $MD_KEY" "$MD_URL/servers") || { echo "API down"; exit 2; }
down=$(echo "$status" | jq -r '[.data[] | select(.fresh | not) | .name] | join(", ")')
[ -z "$down" ] || { echo "silent servers: $down"; exit 1; }
echo "all servers fresh"Network player count and matches
const servers = await get('/servers');
const players = servers.filter((s) => s.role !== 'proxy' && s.fresh).reduce((n, s) => n + s.players, 0);
const matches = (await get('/matches/running')).length;
console.log(`${players} players, ${matches} matches running`);39 players, 7 matches runningplayers = sum(s["players"] for s in get("/servers") if s["role"] != "proxy" and s["fresh"])
print(players, "players,", len(get("/matches/running")), "matches running")Look up a player
curl -s -H "Authorization: Bearer $MD_KEY" "$MD_URL/players/Steve/stats" \
| jq -r '.data.kits[] | "\(.kit): \(.elo) ELO, \(.wins)W \(.losses)L"'nodebuff: 1284 ELO, 41W 22L
sumo: 1050 ELO, 3W 5Lstats = get("/players/Steve/stats")
for k in sorted(stats["kits"], key=lambda k: -k["elo"]):
print(f"{k['kit']:<10} {k['elo']:>5} ELO {k['wins']}W {k['losses']}L")Last 5 matches of a player with opponents
const matches = await get('/players/Steve/matches?limit=5');
for (const m of matches) {
const me = m.players.find((p) => p.name === 'Steve');
const others = m.players.filter((p) => p.side !== me.side).map((p) => p.name).join(', ');
console.log(`${me.outcome.padEnd(4)} vs ${others} (${m.kit}, ${m.durationSeconds}s, ${me.eloChange >= 0 ? '+' : ''}${me.eloChange})`);
}WIN vs Alex (nodebuff, 143s, +16)
LOSS vs Jeb (nodebuff, 98s, -14)
WIN vs Notch (sumo, 41s, +0)Daily stats export to CSV
import csv
with open("nodebuff-top100.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["rank", "name", "uuid", "elo", "wins", "losses"])
for r in get("/leaderboards/nodebuff", limit=100):
w.writerow([r["rank"], r["name"], r["uuid"], r["elo"], r["wins"], r["losses"]])Discord bot commands
A slash command handler with discord.js:
client.on('interactionCreate', async (i) => {
if (!i.isChatInputCommand()) return;
if (i.commandName === 'stats') {
const name = i.options.getString('player');
try {
const s = await get(`/players/${encodeURIComponent(name)}/stats`);
const best = [...s.kits].sort((a, b) => b.elo - a.elo)[0];
await i.reply(`**${s.name}**: ${best ? `${best.kit} ${best.elo} ELO` : 'no ranked games'}, win streak ${s.streak}`);
} catch (e) {
await i.reply(e.message.includes('not_found') ? 'No such player.' : 'The API is busy, try again.');
}
}
if (i.commandName === 'top') {
const rows = await get(`/leaderboards/${i.options.getString('kit')}?limit=10`);
await i.reply(rows.map((r) => `${r.rank}. ${r.name} ${r.elo}`).join('\n') || 'Nobody is ranked yet.');
}
});Use a read key for the bot, and keep cache-seconds at 5 or more so many commands share one query.
Announce finished ranked matches
let since = Date.now();
setInterval(async () => {
const list = await get(`/matches?ranked=true&since=${since}&limit=100`);
for (const m of list.reverse()) {
const winners = m.players.filter((p) => p.side === m.winnerSide);
if (winners.length) {
await postToDiscord(`${winners.map((p) => p.name).join(', ')} won a ranked ${m.kit} match (${winners[0].eloChange >= 0 ? '+' : ''}${winners[0].eloChange})`);
}
since = Math.max(since, m.endedAt + 1);
}
}, 15_000);Rolling restart of the game servers
Drain one game server at a time, wait until it is empty, restart it, then un-drain.
import time, requests
def post(path, body):
r = requests.post(BASE + path, headers=HEADERS, json=body, timeout=10)
r.raise_for_status()
return r.json()["data"]
def server(name):
return next(s for s in get("/servers") if s["name"] == name)
for name in ["game-1", "game-2", "game-3"]:
post("/drain/start", {"server": name, "reason": "rolling restart"})
while True:
s = server(name)
busy = s["players"] + sum(s["playing"].values())
print(f"{name}: {s['players']} players, {sum(s['playing'].values())} matches")
if busy == 0:
break
time.sleep(15)
restart(name) # your own code, for example a Pterodactyl power action
while not server(name)["fresh"]: # wait until it is back
time.sleep(5)
post("/drain/stop", {"server": name})Players keep playing on the other game servers, since a draining server takes no new matches.
Change settings on a schedule
Lower the ranked search range for a weekend event, then restore it:
# friday evening
curl -s -X PATCH -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \
-d '{"changes":[
{"file":"matchmaking.yml","path":"queue.ranked.max-range","value":800},
{"file":"matchmaking.yml","path":"queue.ranked.initial-range","value":100}
]}' "$MD_URL/config" | jq '.data.changes'[
{ "file": "matchmaking.yml", "path": "queue.ranked.max-range", "old": 400, "new": 800 },
{ "file": "matchmaking.yml", "path": "queue.ranked.initial-range", "old": 50, "new": 100 }
]# monday morning: send the old values back
curl -s -X PATCH -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \
-d '{"changes":[
{"file":"matchmaking.yml","path":"queue.ranked.max-range","value":400},
{"file":"matchmaking.yml","path":"queue.ranked.initial-range","value":50}
]}' "$MD_URL/config" | jq '.data.applied'trueBulk edit with a dry run in Python
def patch(changes, dry_run):
r = requests.patch(BASE + "/config", headers={"Authorization": f"Bearer {os.environ['ADMIN_KEY']}"},
json={"dryRun": dry_run, "changes": changes}, timeout=40)
body = r.json()
if not body["ok"]:
raise RuntimeError(body["error"]["message"])
return body["data"]
changes = [
{"file": "matchmaking.yml", "path": "history.keep-days", "value": 60},
{"file": "matchmaking.yml", "path": "duel.request-seconds", "value": 90},
]
preview = patch(changes, dry_run=True)
for c in preview["changes"]:
print(f"{c['file']} {c['path']}: {c['old']} -> {c['new']}")
if input("apply? [y/N] ").lower() == "y":
done = patch(changes, dry_run=False)
print("reloaded:", done["reloaded"], "warnings:", done["warnings"])matchmaking.yml history.keep-days: 30 -> 60
matchmaking.yml duel.request-seconds: 60 -> 90
apply? [y/N] y
reloaded: True warnings: []Back up a config before an edit
for f in matchmaking.yml messages.yml; do
curl -s -H "Authorization: Bearer $ADMIN_KEY" "$MD_URL/config/$f" | jq -r '.data.content' > "backup-$f"
doneHandle rate limits in a loop
Fetch the first 500 finished matches of a kit, 100 at a time, waiting when limited:
const all = [];
for (let offset = 0; offset < 500; offset += 100) {
for (;;) {
const res = await fetch(`${MD_URL}/matches?kit=nodebuff&limit=100&offset=${offset}`, { headers });
if (res.status === 429 || res.status === 503) {
await new Promise((r) => setTimeout(r, Number(res.headers.get('retry-after') || 1) * 1000));
continue;
}
const body = await res.json();
if (!body.ok) throw new Error(body.error.message);
all.push(...body.data);
if (body.data.length < 100) offset = 500;
break;
}
}
console.log(all.length, 'matches');Test the API from the command line
The mineduels-bots folder has a checker that calls every read endpoint, tries a wrong key, and does a dry-run config edit:
cd mineduels-bots
node tools/web-api-check.js --url http://127.0.0.1:8765/v1 --key "$MD_KEY" --admin-key "$ADMIN_KEY" --player Steve
node tools/web-api-check.js --url http://127.0.0.1:8765/v1 --key "$MD_KEY" --burstPASS index answers without a key (22 endpoints, version 0.10.0)
PASS no key is refused with 401
PASS GET /status (lobby-1 (lobby), 31 online, 7 matches)
PASS GET /servers (4 server(s))
...
PASS rate limit answers 429 with Retry-After (64 of 120 limited)
32 passed, 0 failed--burst sends 120 quick requests to prove the rate limit works. It uses up the key's read bucket for a moment, so do not run it while a dashboard polls with the same key. The exit code is 1 when anything fails.