API di Krak Multiplayer
Mostra lo stato dei tuoi mondi su Discord, Telegram o sul tuo sito, e lascia che il tuo bot avvii e fermi un mondo che gira su Krak Server. Semplici richieste HTTPS, risposte in JSON e una chiave personale dall’app.
Cosa fa l’API
- Leggere lo stato dei tuoi mondi: online o no, giocatori e limite di giocatori, versione di Minecraft, l’indirizzo con cui entrano i giocatori, il link d’invito e la valutazione.
- Avviare, fermare e riavviare un mondo che gira su Krak Server.
- Mostrare senza alcuna chiave un mondo aperto nel catalogo, per widget di stato sui siti web.
Cosa non fa
- Non avvia mai il server Minecraft in sé. Krak Server condivide un server che gira già sulla tua macchina, quindi avviare significa attivare l’hosting del mondo.
- I mondi ospitati dall’app su un telefono o un PC si possono solo leggere, non avviare né fermare.
- Riavviare riavvia l’hosting del mondo tramite Krak, non il tuo server Minecraft.
- Non mostra mai gli indirizzi IP di giocatori o host. L’indirizzo è l’indirizzo Krak del mondo (finisce con .krakmc.cc) oppure quello inserito dal proprietario di un server esterno.
Ottieni una chiave
- Apri Krak Multiplayer e vai in Impostazioni > Per sviluppatori.
- Tocca Crea chiave e dalle un nome, ad esempio Bot Discord.
- Attiva "Può avviare e fermare i miei mondi" se il tuo bot deve avviare e fermare i mondi. Senza, la chiave può solo leggere.
- Copia la chiave (inizia con krak_). L’app la mostra una sola volta.
Un account può avere fino a 5 chiavi. Cambiare o reimpostare la password, uscire da tutti i dispositivi, un ban o l’eliminazione dell’account le revocano tutte.
Tieni segreta la chiave: chiunque la abbia può leggere i tuoi mondi e, con l’interruttore attivo, avviarli e fermarli. Non metterla mai in codice che condividi; fai in modo che il bot la legga da una variabile d’ambiente. Se finisce in giro, eliminala nello stesso punto dell’app e smette subito di funzionare.
Richieste
Tutti gli endpoint si trovano a questo indirizzo:
https://krak-mp.cc/api/public/v1
Invia la tua chiave nell’header Authorization di ogni richiesta (solo GET /worlds/{id} non ne ha bisogno):
Authorization: Bearer krak_k7q4m2xp_…
Le risposte sono in JSON. Ogni id è una stringa di cifre e gli orari sono in millisecondi Unix. Un errore arriva con il suo stato HTTP e un corpo come questo; affidati a code, il testo di message può cambiare:
{"error": {"code": "world_not_found", "message": "…"}}
Endpoint
GET /me
Qualsiasi chiave
A chi appartiene la chiave: l’id e il nickname del tuo account, e la chiave con i suoi permessi. Un modo rapido per controllare che una chiave funzioni.
Richiesta
curl https://krak-mp.cc/api/public/v1/me \
-H "Authorization: Bearer krak_k7q4m2xp_…"
Risposta 200 OK
{
"id": "100123",
"nickname": "MrKrak",
"key": {"id": "7", "name": "Discord bot", "prefix": "krak_k7q4m2xp", "scopes": ["read", "control"]}
}
GET /me/worlds
Qualsiasi chiave
I tuoi mondi, al massimo 50, prima quelli modificati più di recente. L’id di un mondo è quello che chiedono gli endpoint qui sotto: chiama questo una volta per trovare il tuo.
Richiesta
curl https://krak-mp.cc/api/public/v1/me/worlds \
-H "Authorization: Bearer krak_k7q4m2xp_…"
Risposta 200 OK
{
"items": [
{
"id": "12",
"name": "§aSky §lIsland",
"namePlain": "Sky Island",
"type": "local",
"visibility": "public",
"status": "online",
"online": true,
"players": 3,
"maxPlayers": 10,
"editions": ["bedrock"],
"version": "1.26.52",
"javaVersion": null,
"hosting": {
"kind": "server",
"state": "live",
"platform": null,
"server": {"id": "9", "name": "Home box", "online": true, "enabled": true}
},
"address": {
"bedrock": {"host": "k7q4m2xp.krakmc.cc", "port": 19132},
"java": null
},
"inviteUrl": "https://krak-mp.cc/j/KRK-7Q4MX2PA",
"rating": {"avg": 4.6, "count": 7},
"onlineSince": 1762600000000
}
]
}
GET /me/worlds/{id}
Qualsiasi chiave
Uno dei tuoi mondi con onlinePlayers: i nickname Krak dei giocatori che sono nel mondo adesso. I giocatori entrati direttamente nel server contano in players, ma senza nome.
Richiesta
curl https://krak-mp.cc/api/public/v1/me/worlds/12 \
-H "Authorization: Bearer krak_k7q4m2xp_…"
Risposta 200 OK
{
"id": "12",
"name": "§aSky §lIsland",
"namePlain": "Sky Island",
"type": "local",
"visibility": "public",
"status": "online",
"online": true,
"players": 3,
"maxPlayers": 10,
"editions": ["bedrock"],
"version": "1.26.52",
"javaVersion": null,
"hosting": {
"kind": "server",
"state": "live",
"platform": null,
"server": {"id": "9", "name": "Home box", "online": true, "enabled": true}
},
"address": {
"bedrock": {"host": "k7q4m2xp.krakmc.cc", "port": 19132},
"java": null
},
"inviteUrl": "https://krak-mp.cc/j/KRK-7Q4MX2PA",
"rating": {"avg": 4.6, "count": 7},
"onlineSince": 1762600000000,
"onlinePlayers": ["Alex", "Steve"]
}
Campi del mondo
POST /me/worlds/{id}/start
Una chiave con "Può avviare e fermare i miei mondi"
Attiva l’hosting del mondo sul Krak Server a cui è assegnato. In pochi secondi hosting.state diventa starting, poi live appena il tuo server Minecraft risponde. Un mondo già attivo viene restituito così com’è.
La risposta contiene il mondo come lo restituisce GET /me/worlds/{id} (qui abbreviato). Rifiutato con not_on_server, agent_offline, host_limit o room_blocked: vedi Errori.
Richiesta
curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/start \
-H "Authorization: Bearer krak_k7q4m2xp_…"
Risposta 200 OK
{
"ok": true,
"world": {
"id": "12",
"namePlain": "Sky Island",
"status": "offline",
"online": false,
"players": 0,
"hosting": {
"kind": "server",
"state": "starting",
"platform": null,
"server": {"id": "9", "name": "Home box", "online": true, "enabled": true}
},
…
}
}
POST /me/worlds/{id}/stop
Una chiave con "Può avviare e fermare i miei mondi"
Disattiva l’hosting del mondo. Funziona anche mentre il Krak Server è offline.
Richiesta
curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/stop \
-H "Authorization: Bearer krak_k7q4m2xp_…"
Risposta 200 OK
{
"ok": true,
"world": {
"id": "12",
"namePlain": "Sky Island",
"status": "offline",
"online": false,
"players": 0,
"hosting": {
"kind": "server",
"state": "disabled",
"platform": null,
"server": {"id": "9", "name": "Home box", "online": true, "enabled": false}
},
…
}
}
POST /me/worlds/{id}/restart
Una chiave con "Può avviare e fermare i miei mondi"
Riavvia l’hosting del mondo tramite Krak: la connessione tra il tuo server Minecraft e il relay. Non riavvia mai il server Minecraft, e il risultato non viene riportato. Se l’hosting è disattivato, prima avvia il mondo (not_hosting).
Richiesta
curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/restart \
-H "Authorization: Bearer krak_k7q4m2xp_…"
Risposta 202 Accepted
{"ok": true, "commandIds": ["f3Kq9xY2LmPa0bCd"]}
GET /worlds/{id}
Senza chiave
Senza chiave: lo stato pubblico di un mondo che chiunque vede nel catalogo, per widget e pagine di stato. I mondi solo per amici o su invito, nascosti e sconosciuti rispondono 404 world_not_found.
Nessun dato dell’host e nessun nome di giocatore. La risposta resta in cache 15 secondi, e le pagine web di qualsiasi sito possono leggerla (CORS aperto).
Richiesta
curl https://krak-mp.cc/api/public/v1/worlds/12
Risposta 200 OK
{
"id": "12",
"name": "§aSky §lIsland",
"namePlain": "Sky Island",
"type": "local",
"online": true,
"players": 3,
"maxPlayers": 10,
"editions": ["bedrock"],
"version": "1.26.52",
"javaVersion": null,
"address": {
"bedrock": {"host": "k7q4m2xp.krakmc.cc", "port": 19132},
"java": null
},
"rating": {"avg": 4.6, "count": 7}
}
Errori
Lo stato HTTP e il codice di ogni errore che l’API restituisce:
Limiti
- 60 richieste al minuto per chiave.
- Avvio, arresto e riavvio: in più 10 al minuto per account e 200 per chiave al giorno (UTC).
- Chiavi sbagliate: dopo 30 richieste fallite in un minuto da un indirizzo IP, quell’indirizzo riceve 429.
- GET /worlds/{id}: 60 richieste al minuto per indirizzo IP. La risposta resta in cache 15 secondi, quindi chiedere più spesso non porta niente di nuovo.
Esempi di bot
Due piccoli bot in Python. Entrambi leggono la chiave e l’id del mondo da variabili d’ambiente, così la chiave non sta mai nel codice.
Per trovare l’id del tuo mondo, chiama GET /me/worlds una volta (la richiesta curl qui sopra) e prendi l’id del tuo mondo.
Per /status basta una chiave senza l’interruttore; per avviare e fermare, la chiave deve avere "Può avviare e fermare i miei mondi". Solo gli amministratori possono avviare e fermare: su Discord i membri con il permesso Gestisci server (di default), su Telegram gli id utente che indichi.
Bot Discord
Comandi /status, /start e /stop (discord.py 2). Crea un’applicazione con un bot nel Discord Developer Portal, invitalo nel tuo server con gli scope bot e applications.commands, poi avvialo:
export KRAK_API_KEY="krak_k7q4m2xp_…"
export KRAK_WORLD_ID="12"
export DISCORD_TOKEN="…"
python discord_bot.py
# pip install discord.py
import os
import aiohttp
import discord
from discord import app_commands
API = "https://krak-mp.cc/api/public/v1"
KRAK_KEY = os.environ["KRAK_API_KEY"] # the key from the app: Settings > For developers
WORLD_ID = os.environ["KRAK_WORLD_ID"] # the "id" of your world in GET /me/worlds
DISCORD_TOKEN = os.environ["DISCORD_TOKEN"]
client = discord.Client(intents=discord.Intents.default())
tree = app_commands.CommandTree(client)
async def krak(method, path):
headers = {"Authorization": f"Bearer {KRAK_KEY}"}
async with aiohttp.ClientSession(headers=headers) as http:
async with http.request(method, API + path) as resp:
data = await resp.json(content_type=None)
if resp.status >= 400:
raise RuntimeError(data["error"]["code"])
return data
def describe(w):
state = "online" if w["online"] else "offline"
lines = [f"{w['namePlain']}: {state}, {w['players']}/{w['maxPlayers']} players"]
for edition, a in (w["address"] or {}).items():
if a:
lines.append(f"{edition.title()}: {a['host']}:{a['port']}")
return "\n".join(lines)
@tree.command(description="Show the world's status")
async def status(interaction: discord.Interaction):
try:
w = await krak("GET", f"/me/worlds/{WORLD_ID}")
await interaction.response.send_message(describe(w))
except RuntimeError as e:
await interaction.response.send_message(f"Could not read the status: {e}", ephemeral=True)
@tree.command(description="Start the world on Krak Server")
@app_commands.default_permissions(manage_guild=True)
async def start(interaction: discord.Interaction):
try:
await krak("POST", f"/me/worlds/{WORLD_ID}/start")
await interaction.response.send_message("Starting the world...")
except RuntimeError as e:
await interaction.response.send_message(f"Could not start: {e}", ephemeral=True)
@tree.command(description="Stop the world")
@app_commands.default_permissions(manage_guild=True)
async def stop(interaction: discord.Interaction):
try:
await krak("POST", f"/me/worlds/{WORLD_ID}/stop")
await interaction.response.send_message("The world is stopping.")
except RuntimeError as e:
await interaction.response.send_message(f"Could not stop: {e}", ephemeral=True)
@client.event
async def on_ready():
await tree.sync()
client.run(DISCORD_TOKEN)
Discord mostra /start e /stop solo ai membri con il permesso Gestisci server; un amministratore può cambiarlo in Impostazioni server > Integrazioni.
Bot Telegram
Comandi /status, /startworld e /stopworld (python-telegram-bot 21). Non sono /start e /stop perché Telegram stesso invia /start quando qualcuno apre un bot. Crea il bot con @BotFather, poi avvialo:
export KRAK_API_KEY="krak_k7q4m2xp_…"
export KRAK_WORLD_ID="12"
export TELEGRAM_TOKEN="…"
export TELEGRAM_ADMINS="123456789"
python telegram_bot.py
# pip install python-telegram-bot
import os
import httpx
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes
API = "https://krak-mp.cc/api/public/v1"
KRAK_KEY = os.environ["KRAK_API_KEY"] # the key from the app: Settings > For developers
WORLD_ID = os.environ["KRAK_WORLD_ID"] # the "id" of your world in GET /me/worlds
TELEGRAM_TOKEN = os.environ["TELEGRAM_TOKEN"]
ADMINS = {int(x) for x in os.environ.get("TELEGRAM_ADMINS", "").split(",") if x} # user ids
async def krak(method, path):
async with httpx.AsyncClient(timeout=15) as http:
r = await http.request(method, API + path, headers={"Authorization": f"Bearer {KRAK_KEY}"})
data = r.json()
if r.is_error:
raise RuntimeError(data["error"]["code"])
return data
def describe(w):
state = "online" if w["online"] else "offline"
lines = [f"{w['namePlain']}: {state}, {w['players']}/{w['maxPlayers']} players"]
for edition, a in (w["address"] or {}).items():
if a:
lines.append(f"{edition.title()}: {a['host']}:{a['port']}")
return "\n".join(lines)
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
try:
w = await krak("GET", f"/me/worlds/{WORLD_ID}")
await update.effective_message.reply_text(describe(w))
except RuntimeError as e:
await update.effective_message.reply_text(f"Could not read the status: {e}")
async def control(update: Update, action: str, done: str):
if update.effective_user.id not in ADMINS:
await update.effective_message.reply_text("Only admins can do that.")
return
try:
await krak("POST", f"/me/worlds/{WORLD_ID}/{action}")
await update.effective_message.reply_text(done)
except RuntimeError as e:
await update.effective_message.reply_text(f"Could not {action}: {e}")
async def start_world(update: Update, context: ContextTypes.DEFAULT_TYPE):
await control(update, "start", "Starting the world...")
async def stop_world(update: Update, context: ContextTypes.DEFAULT_TYPE):
await control(update, "stop", "The world is stopping.")
app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("status", status))
app.add_handler(CommandHandler("startworld", start_world))
app.add_handler(CommandHandler("stopworld", stop_world))
app.run_polling()
Solo gli id utente Telegram in TELEGRAM_ADMINS (separati da virgole) possono avviare e fermare il mondo.
Domande o idee sull’API? Chiedi sul nostro server Discord o scrivi a support@krak-mp.cc.