Krak Multiplayer API
在 Discord、Telegram 或你的网站上显示世界的状态,并让你的机器人启动和停止在 Krak Server 上运行的世界。只需普通的 HTTPS 请求、JSON 响应和在应用中创建的个人密钥。
API 能做什么
- 读取你的世界的状态:是否在线、玩家人数和人数上限、Minecraft 版本、玩家加入用的地址、邀请链接和评分。
- 启动、停止和重启在 Krak Server 上运行的世界。
- 无需任何密钥即可显示一个在目录中公开的世界,用于网站上的状态小组件。
API 不做什么
- 它从不启动 Minecraft 服务器本身。Krak Server 分享的是已经在你机器上运行的服务器,所以“启动”的意思是开启这个世界的开放。
- 从手机或电脑上的应用开放的世界只能读取,不能启动或停止。
- 重启只会重启 Krak 对这个世界的开放,而不是你的 Minecraft 服务器。
- 它从不显示玩家或房主的 IP 地址。地址是世界的 Krak 地址(以 .krakmc.cc 结尾),或外部服务器的所有者填写的地址。
获取密钥
- 打开 Krak Multiplayer,进入“设置”>“面向开发者”。
- 点按“创建密钥”并给它起个名字,例如 Discord 机器人。
- 如果你的机器人需要启动和停止世界,请打开“可以启动和停止我的世界”。不打开的话,密钥只能读取。
- 复制密钥(以 krak_ 开头)。应用只会显示一次。
每个账号最多可以有 5 个密钥。更改或重置密码、在所有设备上退出登录、被封禁或删除账号,都会吊销全部密钥。
请妥善保管密钥:任何拿到它的人都能读取你的世界,开关打开时还能启动和停止它们。千万不要把它写进你分享的代码里,应让机器人从环境变量读取。如果密钥泄露,在应用的同一位置删除它,它会立即失效。
请求
所有端点都在这个地址下:
https://krak-mp.cc/api/public/v1
在每个请求的 Authorization 请求头中发送你的密钥(只有 GET /worlds/{id} 不需要):
Authorization: Bearer krak_k7q4m2xp_…
响应为 JSON。所有 id 都是由数字组成的字符串,时间为 Unix 毫秒。出错时会返回对应的 HTTP 状态码和下面这样的内容;请以 code 为准,message 的文字可能会变:
{"error": {"code": "world_not_found", "message": "…"}}
端点
GET /me
任意密钥
密钥属于谁:你账号的 id 和昵称,以及密钥本身和它的权限范围。可以用来快速检查密钥是否有效。
请求
curl https://krak-mp.cc/api/public/v1/me \
-H "Authorization: Bearer krak_k7q4m2xp_…"
响应 200 OK
{
"id": "100123",
"nickname": "MrKrak",
"key": {"id": "7", "name": "Discord bot", "prefix": "krak_k7q4m2xp", "scopes": ["read", "control"]}
}
GET /me/worlds
任意密钥
你的世界,最多 50 个,最近修改的排在前面。下面的端点需要用到世界的 id:调用一次即可找到你的世界。
请求
curl https://krak-mp.cc/api/public/v1/me/worlds \
-H "Authorization: Bearer krak_k7q4m2xp_…"
响应 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}
任意密钥
你的一个世界,附带 onlinePlayers:现在在世界里的玩家的 Krak 昵称。直接加入服务器的玩家会计入 players,但不会显示名字。
请求
curl https://krak-mp.cc/api/public/v1/me/worlds/12 \
-H "Authorization: Bearer krak_k7q4m2xp_…"
响应 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"]
}
世界字段
POST /me/worlds/{id}/start
打开了“可以启动和停止我的世界”的密钥
在世界所分配的 Krak Server 上开启这个世界的开放。几秒内 hosting.state 会变为 starting,你的 Minecraft 服务器响应后变为 live。已经开启的世界会按原样返回。
响应中的世界与 GET /me/worlds/{id} 返回的相同(这里有所省略)。可能因 not_on_server、agent_offline、host_limit 或 room_blocked 被拒绝:参见“错误”。
请求
curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/start \
-H "Authorization: Bearer krak_k7q4m2xp_…"
响应 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
打开了“可以启动和停止我的世界”的密钥
关闭这个世界的开放。即使 Krak Server 离线也可以使用。
请求
curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/stop \
-H "Authorization: Bearer krak_k7q4m2xp_…"
响应 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
打开了“可以启动和停止我的世界”的密钥
重启 Krak 对这个世界的开放,也就是你的 Minecraft 服务器和中继服务器之间的连接。它从不重启 Minecraft 服务器本身,也不会返回结果。如果开放已关闭,请先启动世界(not_hosting)。
请求
curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/restart \
-H "Authorization: Bearer krak_k7q4m2xp_…"
响应 202 Accepted
{"ok": true, "commandIds": ["f3Kq9xY2LmPa0bCd"]}
GET /worlds/{id}
无需密钥
无需密钥:任何人都能在目录中看到的世界的公开状态,适用于小组件和状态页面。仅限好友或仅限邀请的世界、被隐藏和不存在的世界会返回 404 world_not_found。
不包含房主信息,也不包含玩家名字。响应会缓存 15 秒,任何网站的网页都可以读取它(CORS 已开放)。
请求
curl https://krak-mp.cc/api/public/v1/worlds/12
响应 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}
}
错误
API 返回的所有错误的 HTTP 状态码和代码:
限制
- 每个密钥每分钟 60 个请求。
- 启动、停止和重启:另外每个账号每分钟 10 次,每个密钥每天(UTC)200 次。
- 错误的密钥:同一 IP 地址一分钟内失败 30 次后,该地址会收到 429。
- GET /worlds/{id}:每个 IP 地址每分钟 60 个请求。响应会缓存 15 秒,所以更频繁地请求也拿不到新内容。
机器人示例
两个用 Python 写的小机器人。它们都从环境变量读取密钥和世界 id,所以代码里不会出现密钥。
要找到你的世界的 id,调用一次 GET /me/worlds(上面的 curl 请求),取你的世界的 id。
只用 /status 的话,没有打开开关的密钥就够了;要启动和停止,密钥需要打开“可以启动和停止我的世界”。只有管理员能启动和停止:在 Discord 上是拥有“管理服务器”权限的成员(默认),在 Telegram 上是你列出的用户 id。
Discord 机器人
命令为 /status、/start 和 /stop(discord.py 2)。在 Discord Developer Portal 创建一个带机器人的应用,用 bot 和 applications.commands 范围把它邀请到你的服务器,然后运行:
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 只向拥有“管理服务器”权限的成员显示 /start 和 /stop;管理员可以在“服务器设置”>“集成”中更改。
Telegram 机器人
命令为 /status、/startworld 和 /stopworld(python-telegram-bot 21)。之所以不用 /start 和 /stop,是因为有人打开机器人时 Telegram 自己会发送 /start。用 @BotFather 创建机器人,然后运行:
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()
只有 TELEGRAM_ADMINS(用逗号分隔)中列出的 Telegram 用户 id 才能启动和停止世界。
对 API 有疑问或想法?可以在我们的 Discord 服务器上提问,或写信到 support@krak-mp.cc。