Krak Multiplayer
Discord Telegram API
JA
ダウンロード

Krak Multiplayer API

ワールドの状態をDiscordやTelegram、自分のWebサイトに表示したり、Krak Serverで動いているワールドをボットから起動・停止したりできます。シンプルなHTTPSリクエスト、JSONの応答、アプリで作る個人用キーで使えます。

APIでできること

  • 自分のワールドの状態を読み取る:オンラインかどうか、プレイヤー数と上限、Minecraftのバージョン、参加に使うアドレス、招待リンク、評価。
  • Krak Serverで動いているワールドの起動、停止、再起動。
  • カタログに公開されているワールド1つの状態を、キーなしで表示(Webサイトのステータスウィジェット向け)。

APIでできないこと

  • Minecraftサーバーそのものを起動することはありません。Krak Serverはマシンですでに動いているサーバーを共有するので、「起動」とはそのワールドのホストをオンにすることです。
  • スマホやPCのアプリからホストしているワールドは読み取りのみで、起動や停止はできません。
  • 再起動で再起動されるのはKrakによるワールドのホストで、Minecraftサーバーではありません。
  • プレイヤーやホストのIPアドレスは一切表示しません。アドレスはワールドのKrakアドレス(.krakmc.ccで終わるもの)か、外部サーバーのオーナーが入力したアドレスです。

キーを取得する

  1. Krak Multiplayerを開き、「設定」>「開発者向け」に進みます。
  2. 「キーを作成」をタップし、名前をつけます(例:Discordボット)。
  3. ボットにワールドの起動と停止もさせる場合は、「自分のワールドを起動・停止できる」をオンにします。オフのままだと、キーは読み取りしかできません。
  4. キー(krak_で始まります)をコピーします。アプリに表示されるのは一度だけです。

1つのアカウントで持てるキーは5つまでです。パスワードの変更やリセット、すべてのデバイスからのログアウト、BAN、アカウントの削除を行うと、すべてのキーが無効になります。

キーは秘密にしてください。キーを持っている人は誰でもあなたのワールドを読み取れ、スイッチがオンなら起動や停止もできます。共有するコードには絶対に書かず、ボットには環境変数から読み込ませてください。漏れた場合は、アプリの同じ場所でキーを削除すれば、すぐに使えなくなります。

リクエスト

すべてのエンドポイントはこのアドレスの下にあります:

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です。一度呼び出して、自分のワールドの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}

どのキーでも可

自分のワールド1つと、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"]
}

ワールドのフィールド

name, namePlain
Minecraftの§カラーコードつきの名前と、カラーコードなしの名前。
status
online、offline、hidden、blockedのいずれか(hiddenとblockedはモデレーターによるもので、あなたにはそのワールドも見えます)。
online
statusがonlineのときtrue。
players, maxPlayers
いまワールドにいるプレイヤー数と上限。カタログのカードと同じ数え方で、サーバーに直接参加したプレイヤーも含みます。
version, javaVersion
ワールドのMinecraftバージョン(Bedrockに対応したワールドではBedrockのバージョン)。javaVersionはJavaのバージョンです。不明なときはnull。
hosting.kind
server:自分のKrak Serverのどれかにあり、起動・停止・再起動が使えます。app:スマホやPCのアプリからホストしていて、読み取りのみ。external:外部サーバー。
hosting.state
serverの場合:live、starting、agent_offline(Krak Serverが接続されていない)、disabled(ホストがオフ)。appの場合:liveかoffline。
hosting.server
Krak Server:そのidと名前、接続されているか(online)、このワールドのホストがオンか(enabled)。
address
プレイヤーが参加に使うアドレス(エディションごと)。いまアドレスがないときはnull。プレイヤーが参加できる間はワールドのKrakアドレス、外部サーバーではオーナーが表示しているアドレスです。
inviteUrl
ワールドに招待リンクがある間はそのリンク、なければnull。
rating
カタログに表示される平均評価とレビュー数。レビューが3件たまるまではnull。
onlineSince
ホストが始まった時刻(Unixミリ秒)。ホストしていなければnull。
onlinePlayers
GET /me/worlds/{id}のみ:いまワールドにいるプレイヤーのKrakニックネーム。

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秒間キャッシュされ、どのサイトのWebページからでも読み取れます(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ステータスとコード:

401 api_key_required
Authorization: Bearerヘッダーがありません。
401 invalid_api_key
キーの形式が正しくない、存在しない、削除または無効化されている、またはそのアカウントが有効ではありません。
403 scope_denied
ワールドを起動・停止できないキーで、起動、停止、再起動を呼び出しました。
403 room_blocked
モデレーターがワールドを非表示またはブロックしました。
404 world_not_found
自分のワールドではない、削除された、または存在しません。GET /worlds/{id}の場合:ワールドがカタログに公開されていません。
409 not_on_server
ワールドが自分のKrak Serverのどれにもありません(アプリからホストしている、または外部サーバーです)。
409 agent_offline
Krak Serverが接続されていません。何も変更されていません。
409 host_limit
アカウントがすでに別のワールドをホストしています(一度に1つまで)。detailsにそのワールドが入ります。
409 not_hosting
ホストがオフのまま再起動しようとしました。先にワールドを起動してください。
429 rate_limited
リクエストが多すぎます。Retry-Afterの秒数が過ぎてから再試行してください(details.retryAfterにも入ります)。1日の上限に達した場合はdetails.limit "daily"が付きます。
503 server_agent_disabled
Krak Serverは現在Krak側で停止されています。

制限

  • キーごとに1分あたり60リクエスト。
  • 起動、停止、再起動は、さらにアカウントごとに1分あたり10回、キーごとに1日(UTC)200回まで。
  • 間違ったキー:1つのIPアドレスから1分間に30回失敗すると、そのアドレスには429が返ります。
  • GET /worlds/{id}:IPアドレスごとに1分あたり60リクエスト。応答は15秒間キャッシュされるので、それより頻繁に問い合わせても新しい情報は得られません。

ボットの例

Pythonで書いた小さなボットを2つ紹介します。どちらもキーとワールドの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までご連絡ください。