Krak Multiplayer
Discord Telegram API
EN
Download

Krak Multiplayer API

Show your worlds' status in Discord, Telegram or on your website, and let your bot start and stop a world that runs on Krak Server. Plain HTTPS requests, JSON answers and a personal key from the app.

What the API can do

  • Read the status of your worlds: online or offline, players and the player limit, the Minecraft version, the address players join by, the invite link and the rating.
  • Start, stop and restart a world that runs on Krak Server.
  • Show one world that is open in the catalog without any key, for status widgets on websites.
  • Read the coins players tipped you in your worlds or sent you, so your server can give its own currency for them.
  • Reward players on your own server: who joined your worlds through Krak and for how long, your worlds' reviews, the members of your communities, players' public profiles, and whether an Xbox gamertag is verified in Krak.
  • Bridge a chat of your community with your Minecraft server's chat or a Discord channel through a bot, and receive events by webhook instead of asking every few seconds.

What it does not do

  • It never starts the Minecraft server itself. Krak Server shares a server that already runs on your machine, so start means switching hosting of the world on.
  • Worlds hosted from a phone or PC app can only be read, not started or stopped.
  • Restart restarts Krak's hosting of the world, not your Minecraft server.
  • It never shows the IP addresses of players or hosts. The address is the world's Krak address (ending in .krakmc.cc) or the address the owner of an External server entered.

Get a key

  1. Open Krak Multiplayer and go to Settings > For developers.
  2. Tap Create key and give it a name, for example Discord bot.
  3. Turn on Can start and stop my worlds if your bot should start and stop worlds. Without it the key can only read.
  4. Copy the key (it starts with krak_). The app shows it only once.

An account can have up to 5 keys. Changing or resetting your password, signing out everywhere, a ban or deleting the account revokes all of them.

To read who joined your worlds, also turn on Visits of my worlds and tick I accept the developer terms (see Developer terms below). A key without it gets 403 scope_denied on those three endpoints.

Keep the key secret: anyone who has it can read your worlds and, with the switch on, start and stop them. Never put it in code you share; let your bot read it from an environment variable. If it leaks, delete it in the same place in the app and it stops working at once.

Requests

Every endpoint is under this address:

https://krak-mp.cc/api/public/v1

Send your key in the Authorization header of every request (only GET /worlds/{id} needs none):

Authorization: Bearer krak_k7q4m2xp_…

Answers are JSON. Every id is a string of digits and times are Unix milliseconds. An error comes with its HTTP status and a body like this; rely on code, the message may change:

{"error": {"code": "world_not_found", "message": "…"}}

Endpoints

GET /me

Any key

Who the key belongs to: your account's id and nickname, and the key with its scopes. A quick way to check that a key works.

Request

curl https://krak-mp.cc/api/public/v1/me \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "id": "100123",
  "nickname": "MrKrak",
  "key": {"id": "7", "name": "Discord bot", "prefix": "krak_k7q4m2xp", "scopes": ["read", "control"]}
}

GET /me/worlds

Any key

Your worlds, at most 50, the most recently changed first. The id of a world is what the endpoints below take: call this once to find yours.

Request

curl https://krak-mp.cc/api/public/v1/me/worlds \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 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}

Any key

One of your worlds with onlinePlayers: the Krak nicknames of the players in the world now who show themselves in worlds' player lists. Other players, and players who joined the server directly, count in players but are not named.

Request

curl https://krak-mp.cc/api/public/v1/me/worlds/12 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 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"]
}

World fields

name, namePlain
The name with Minecraft's § colour codes, and without them.
status
online, offline, hidden or blocked (hidden and blocked are set by moderators; you still see those worlds).
online
true when status is online.
players, maxPlayers
Players in the world now and the limit, counted as on the catalog card: players who joined the server directly count too.
version, javaVersion
The world's Minecraft version (Bedrock's when the world has Bedrock); javaVersion is the Java version. null when unknown.
hosting.kind
server: on one of your Krak Servers, so start, stop and restart work. app: hosted from a phone or PC app, read only. external: an External server.
hosting.state
For server: live, starting, agent_offline (the Krak Server is not connected) or disabled (hosting is off). For app: live or offline.
hosting.server
The Krak Server: its id and name, whether it is connected (online) and whether hosting of this world is on (enabled).
address
The address players join by, per edition, or null when there is none now: the world's Krak address while players can join, or the address the owner of an External server shows.
inviteUrl
The world's invite link while it has one, else null.
rating
The average and the number of reviews, as the catalog shows them; null until 3 reviews count.
onlineSince
When hosting started (Unix milliseconds), else null.
onlinePlayers
Only in GET /me/worlds/{id}: the Krak nicknames of the players in the world now.

POST /me/worlds/{id}/start

A key with Can start and stop my worlds

Switches hosting of the world on, on the Krak Server it is assigned to. Within seconds hosting.state becomes starting, then live once your Minecraft server answers. A world that is already on is answered as it is.

The answer has the world as GET /me/worlds/{id} returns it (shortened here). Refused with not_on_server, agent_offline, host_limit or room_blocked: see Errors.

Request

curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/start \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 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

A key with Can start and stop my worlds

Switches hosting of the world off. It works even while the Krak Server is offline.

Request

curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/stop \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 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

A key with Can start and stop my worlds

Restarts Krak's hosting of the world: the connection between your Minecraft server and the relay. It never restarts the Minecraft server, and the result is not reported back. If hosting is off, start the world first (not_hosting).

Request

curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/restart \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 202 Accepted

{"ok": true, "commandIds": ["f3Kq9xY2LmPa0bCd"]}

GET /me/coins/received

Any key

The coins players tipped you in your worlds (kind tip, with worldId) or sent you from your profile (kind transfer), oldest first. Keep nextCursor and send it as after next time: you get only what is new. more: true means another page is ready now. kind=tip lists tips only; limit is 1 to 100.

from is the player as you see them in the app: Krak id, nickname and, when their Xbox account verified it and they show it, their gamertag. It is null for a deleted account, a player under 13 or after a block. note is what the player wrote (only from a friend whose messages you accept).

Krak only records the coins. What your server gives back for them is your own promise to your players, not Krak's. Krak coins cannot be bought with money.

Request

curl https://krak-mp.cc/api/public/v1/me/coins/received?after=811 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "id": "812",
      "kind": "tip",
      "amount": 50,
      "note": "Steve",
      "worldId": "12",
      "createdAt": 1764000000000,
      "from": {
        "id": "100042",
        "nickname": "Taras",
        "profileUrl": "https://krak-mp.cc/u/100042",
        "gamertag": "Taras2010",
        "gamertagVerified": true
      }
    }
  ],
  "nextCursor": "812",
  "more": false
}

GET /me/worlds/{id}/players

A key with Visits of my worlds

Who is in your world now: one visit per player whose game is in the world, first joined first. kind is krak (the Krak app), address (joined by the world's address) or xbox (Krak saw them in your Xbox session). player is null for an anonymous visit (see Players' privacy).

others counts the players your world shows in players that are not listed, for example players who joined the server directly. To be sure that a player on your server is that Krak player, compare their verified gamertag with this list.

Request

curl https://krak-mp.cc/api/public/v1/me/worlds/12/players \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "id": "77",
      "worldId": "12",
      "sessionId": "5124",
      "kind": "krak",
      "player": {
        "id": "100042",
        "nickname": "Taras",
        "profileUrl": "https://krak-mp.cc/u/100042",
        "gamertag": "Taras2010",
        "gamertagVerified": true
      },
      "joinedAt": 1764000000000,
      "enteredAt": 1764000020000,
      "leftAt": null,
      "live": true,
      "inWorldMs": 3480000
    }
  ],
  "others": 1
}

GET /me/visits

A key with Visits of my worlds

Every visit of your worlds as a change feed, oldest change first; add worldId for one world. A visit comes again when it changes: the game reached the world, the player left, was kicked or banned, or hosting ended. Each item is the visit as it is now. Keep nextCursor and send it as after next time; more: true means another page is ready now. limit is 1 to 200.

Count rewards from inWorldMs, the time the player's game was really in the world, not from joinedAt and leftAt. Krak keeps visits for 30 days, so poll at least once a day (every 10 to 30 seconds is plenty).

Request

curl https://krak-mp.cc/api/public/v1/me/visits?after=812-76 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "id": "77",
      "worldId": "12",
      "sessionId": "5124",
      "kind": "krak",
      "player": {
        "id": "100042",
        "nickname": "Taras",
        "profileUrl": "https://krak-mp.cc/u/100042",
        "gamertag": "Taras2010",
        "gamertagVerified": true
      },
      "joinedAt": 1764000000000,
      "enteredAt": 1764000020000,
      "leftAt": null,
      "live": true,
      "inWorldMs": 3480000
    },
    {
      "id": "78",
      "worldId": "12",
      "sessionId": "5124",
      "kind": "krak",
      "player": null,
      "joinedAt": 1764000100000,
      "enteredAt": 1764000130000,
      "leftAt": 1764001900000,
      "live": false,
      "inWorldMs": 1770000,
      "outcome": "kicked"
    }
  ],
  "nextCursor": "815-78",
  "more": false
}

GET /me/worlds/{id}/players/{userId}/time

A key with Visits of my worlds

For hours played rewards: how many visits of that player got into the world in the last days (1 to 30, 30 when left out) and their time in the world. 404 user_not_found when the player is unknown or the API does not name them to you.

Request

curl https://krak-mp.cc/api/public/v1/me/worlds/12/players/100042/time?days=7 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{"userId": "100042", "days": 7, "visits": 4, "inWorldMs": 19800000}

GET /me/reviews

Any key

The reviews of your worlds as a change feed, the same way as /me/visits: what the app shows you in the reviews list. author is null for anonymous reviews. A review that disappears after it was shown (hidden by moderators, replaced, its author banned) comes once more with removed: true, so you can take back a reward.

Never make a reward depend on the stars: the developer terms forbid it, and moderators look at worlds that pay for good reviews.

Request

curl https://krak-mp.cc/api/public/v1/me/reviews?after=39-50 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "id": "55",
      "worldId": "12",
      "stars": 5,
      "text": "Great builds",
      "createdAt": 1764000000000,
      "updatedAt": 1764000000000,
      "anonymous": false,
      "author": {"id": "100042", "nickname": "Taras", "profileUrl": "https://krak-mp.cc/u/100042"}
    },
    {"id": "51", "worldId": "12", "removed": true}
  ],
  "nextCursor": "40-55",
  "more": false
}

GET /me/communities

Any key

The communities you own, with their member count and whether they are open or closed.

Request

curl https://krak-mp.cc/api/public/v1/me/communities \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{"items": [{"id": "31", "slug": "reward-club", "name": "Reward Club", "memberCount": 42, "privacy": "open"}]}

GET /me/communities/{id}/members

Any key

The members of one of your communities, oldest first, up to 200 per page; role filters by owner, mod or member, and cursor takes the previous page's nextCursor. others counts the members the API does not name: deleted or banned accounts, players under 13 and anyone with a block between you.

Request

curl https://krak-mp.cc/api/public/v1/me/communities/31/members?limit=200 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "user": {
        "id": "100042",
        "nickname": "Taras",
        "profileUrl": "https://krak-mp.cc/u/100042",
        "gamertag": "Taras2010",
        "gamertagVerified": true
      },
      "role": "member",
      "joinedAt": 1760000000000
    }
  ],
  "nextCursor": "1760000000000-100042",
  "others": 3
}

GET /users/{id}

Any key

A player's public profile as you see it in the app: nickname, level, badges, follower counts, the behaviour rating and, when their Xbox account verified it and they show it, the gamertag. friendsCount is null when the player hides their friends from you.

No presence, bio, photos, links or country. 404 user_not_found for an unknown or deleted account, a block between you or a player under 13.

Request

curl https://krak-mp.cc/api/public/v1/users/100042 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "id": "100042",
  "nickname": "Taras",
  "profileUrl": "https://krak-mp.cc/u/100042",
  "avatarUrl": "https://krak-mp.cc/api/v1/avatars/default/q7Xa.png",
  "createdAt": 1750000000000,
  "level": 3,
  "topBadge": "early_tester",
  "badges": [{"key": "early_tester", "awardedAt": 1750000000000}],
  "followersCount": 30,
  "followingCount": 12,
  "friendsCount": 12,
  "plus": false,
  "behaviorRating": {"score": 4.6, "count": 5},
  "gamertag": "Taras2010",
  "gamertagVerified": true
}

GET /users?ids=

Any key

Up to 50 profiles at once, in the order asked; unknown and hidden ids are left out.

Request

curl https://krak-mp.cc/api/public/v1/users?ids=100042,100043 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{"items": [{"id": "100042", "nickname": "Taras", …}]}

GET /gamertags?name=

Any key

Whether a Krak player verified this Xbox gamertag by linking their Xbox account, and shows it. Names are compared as Xbox compares them (case, spaces and # do not matter). checkedAt is when Xbox last confirmed the name to Krak: gamertags can change, so treat an old one with care.

Every other case (unknown, not verified, hidden, blocked, banned, under 13) gives the same answer with verified: false, so the API never says whether an account exists.

This proves that a Krak account owns this Xbox name. It does not prove that the player joining your server now is that person. Use it only on a server that checks the Xbox sign-in of every player (Bedrock Dedicated Server with online-mode=true, Geyser with Floodgate, PocketMine with Xbox auth). On a server without Xbox sign-in anyone can join under any name. Best of all: the player is also in GET /me/worlds/{id}/players right now with that verified gamertag.

Request

curl https://krak-mp.cc/api/public/v1/gamertags?name=Taras2010 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{"gamertag": "Taras2010", "verified": true, "krakId": "100042", "checkedAt": 1763900000000}
{"gamertag": "Steve", "verified": false}

POST /gamertags/lookup

Any key

Up to 100 names at once; the answers come in the same order.

Request

curl -X POST https://krak-mp.cc/api/public/v1/gamertags/lookup \
  -H "Authorization: Bearer krak_k7q4m2xp_…" \
  -H "Content-Type: application/json" \
  -d '{"names": ["Taras2010", "Steve"]}'

Answer 200 OK

{
  "items": [
    {"gamertag": "Taras2010", "verified": true, "krakId": "100042", "checkedAt": 1763900000000},
    {"gamertag": "Steve", "verified": false}
  ]
}

POST /me/worlds/{id}/status

The world's status token (not an API key)

For an External server that publishes no player count (a Bedrock Dedicated Server in NetherNet mode): your server sends its count, and the world's card shows it as reported by the owner. Make the token in the app, in the world's settings under Player count from your server. It is shown once, works for this one world and can only report the count. Send it as Authorization: Bearer krak_st_… or as the bare token.

online is 0 to max, max is 1 to 1000 (left out: the maximum in the world's settings). One report per 15 seconds at most. A report counts for 3 minutes, then the card shows the count as unknown again, so send one every 30 seconds. If the server's own status has a count, the card keeps it (report.used is false). Our KrakGuard Status pack for Bedrock Dedicated Server does all of this for you.

Request

curl -X POST https://krak-mp.cc/api/public/v1/me/worlds/12/status \
  -H "Authorization: Bearer krak_st_k7q4m2xp_…" \
  -H "Content-Type: application/json" \
  -d '{"online": 7, "max": 20}'

Answer 200 OK

{
  "ok": true,
  "report": {"online": 7, "max": 20, "at": 1764000000000, "freshUntil": 1764000180000, "used": true},
  "world": {"id": "12", "type": "external", "status": "online", "online": true, "players": 7, "maxPlayers": 20, "playersSource": "owner", …}
}

GET /worlds/{id}

No key

No key: the public status of a world that anyone sees in the catalog, for widgets and status pages. Worlds for friends or by invite only, hidden and unknown worlds answer 404 world_not_found.

No host details and no player names. The answer is cached for 15 seconds, and web pages on any site may read it (CORS is open).

Request

curl https://krak-mp.cc/api/public/v1/worlds/12

Answer 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}
}

Community bots

What a bot is

A bot is an account that belongs to you. You attach it to a chat of a community you own or moderate, and your program reads and writes that chat with your own key, for example to connect it with your Minecraft server's chat.

  • Everyone sees that it is a bot: the BOT badge next to its name, a nickname with bot in it, and a line at the top of the chat saying that messages there also reach your server. The bot's profile names you as its owner.
  • When your bridge posts for a player in your game, the apps show the message as Steve via SkyBot.
  • A bot has no DMs, friends or followers, never counts as a member or as online, and writes only in its chats. Its messages send no notifications.
  • It is moderated like any account: members report its messages, the community's moderators delete them, mute the bot or remove it, and Krak's moderators can disable it.

How to start

  1. In the app, open Settings > For developers > Bots, or your community's settings > Bots, and create a bot. Its nickname must contain bot. You need an account with a confirmed email or Google or Apple sign-in, at least 7 days old; you can have up to 3 bots.
  2. Attach it to a chat of a community you own or moderate. A bot can be in up to 10 communities, in one chat of each; a community can have up to 3 bots.
  3. Create a key with Community bots turned on and accept the developer terms. One key drives all your bots: every endpoint names the bot.
  4. Call GET /bots to get the ids of your bots and of their communities.

Skip your bot's own messages or your bridge echoes itself. The messages endpoint lists them too (sender.id is the bot's id); the chat.message webhook leaves them out.

GET /bots

A key with Community bots

Your bots with the community and chat each one is in. active is false while the bot cannot write there: you are no longer an owner or moderator of that community, or your account is restricted. disabled is true when Krak's moderators disabled the bot.

Request

curl https://krak-mp.cc/api/public/v1/bots \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "id": "100500",
      "nickname": "SkyBot",
      "profileUrl": "https://krak-mp.cc/u/100500",
      "disabled": false,
      "communities": [
        {"id": "31", "name": "Reward Club", "chat": {"id": "501", "title": "General"}, "active": true}
      ]
    }
  ]
}

GET /bots/{botId}/communities/{communityId}/messages

A key with Community bots

The chat's messages of the last 24 hours, oldest first. With after (a message id) you get the messages after it; without it, the newest ones. limit is 1 to 100 (50 by default). Keep nextCursor and send it as after next time; more: true means another page is ready now. Poll every 2 to 5 seconds, or use the chat.message webhook.

Text, GIFs, pictures, videos and voice messages. An attachment comes as its type only, without a link, and body is its caption or empty. bridge means another bridge posted the message for a player, and body is then that player's text alone. Messages of players under 13 and of anyone with a block between them and you or the bot are left out. gamertag only when the player's Xbox account verified it and they show it.

Request

curl "https://krak-mp.cc/api/public/v1/bots/100500/communities/31/messages?after=9000" \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 200 OK

{
  "items": [
    {
      "id": "9001",
      "chatId": "501",
      "communityId": "31",
      "kind": "text",
      "sender": {"id": "100042", "nickname": "Taras", "bot": false, "gamertag": "Taras2010", "gamertagVerified": true},
      "body": "hi from the app",
      "createdAt": 1764000000000,
      "replyTo": {"id": "8990"}
    },
    {
      "id": "9002",
      "chatId": "501",
      "communityId": "31",
      "kind": "text",
      "sender": {"id": "100500", "nickname": "SkyBot", "bot": true},
      "body": "hello",
      "createdAt": 1764000004000,
      "bridge": {"name": "Steve"}
    },
    {
      "id": "9003",
      "chatId": "501",
      "communityId": "31",
      "kind": "picture",
      "sender": {"id": "100043", "nickname": "Olena", "bot": false},
      "body": "",
      "createdAt": 1764000009000,
      "attachment": {"type": "picture"}
    }
  ],
  "nextCursor": "9003",
  "more": false
}

POST /bots/{botId}/communities/{communityId}/messages

A key with Community bots

Posts body as the bot: 1 to 1000 characters, new lines allowed. bridge.name is the player in your game (1 to 32 characters, one line, no @); the apps show the message as Steve via SkyBot. replyToId quotes a message of the same chat.

Send a clientMsgId (up to 64 letters, digits and . _ : -) and send the same one again when you retry after a timeout: you get 200 with the message already stored, not a copy. Links on the spam list and sexual solicitation are refused as in the global chat (validation_failed). Bot messages send no push and no mention notification.

Request

curl -X POST https://krak-mp.cc/api/public/v1/bots/100500/communities/31/messages \
  -H "Authorization: Bearer krak_k7q4m2xp_…" \
  -H "Content-Type: application/json" \
  -d '{"body": "hello", "bridge": {"name": "Steve"}, "clientMsgId": "mc-8812"}'

Answer 201 Created

{
  "message": {
    "id": "9002",
    "chatId": "501",
    "communityId": "31",
    "kind": "text",
    "sender": {"id": "100500", "nickname": "SkyBot", "bot": true},
    "body": "hello",
    "createdAt": 1764000004000,
    "bridge": {"name": "Steve"}
  }
}

DELETE /bots/{botId}/messages/{messageId}

A key with Community bots

Deletes one of the bot's own messages, as if its author deleted it. Anyone else's message: 403 not_message_author.

Request

curl -X DELETE https://krak-mp.cc/api/public/v1/bots/100500/messages/9002 \
  -H "Authorization: Bearer krak_k7q4m2xp_…"

Answer 204 No Content

Bot limits and refusals

  • Per bot: 30 messages a minute, 5 in 5 seconds and 3,000 a day (UTC).
  • Per community: 60 bot messages a minute, all its bots together.
  • Reading counts toward your key's 60 requests a minute. Over a limit you get 429 rate_limited with Retry-After; the daily one adds details.limit "daily".

Krak can also refuse a message within the limits: bot_disabled, bot_inactive, community_muted or restricted. Errors below explains each code; details.reason or details.until tells more.

Webhooks

Set up a webhook

Instead of asking every few seconds, your server can receive events. A key has one webhook, and you set it only in the app, never through the API, so a leaked key cannot redirect your events.

  1. In the app, open Settings > For developers, choose a key and open Webhook.
  2. Enter your server's address and choose the events. Only events the key's permissions allow can be chosen.
  3. Save. The app shows the signing secret (it starts with whsec_) only once: put it in your server's settings. Krak sends a ping at once, and the webhook starts working when your server answers it with 2xx.
  4. Send test sends another ping, and the delivery log shows the last 50 attempts. Rotate secret gives a new secret; the old one keeps signing too for 24 hours, so you can switch without losing events.

The address starts with https://, has at most 300 characters and points to a public address, port 443 or 1024 to 65535. Local, private and Krak's own addresses are refused, and redirects are not followed.

Events

Choose the events you need. Each one needs a permission of the key, and its data is what the matching endpoint answers:

visit.started
A player's game entered your world, so they really joined. data is a visit as in /me/visits.A key with Visits of my worlds
visit.ended
The visit ended: the player left, was kicked or banned, or hosting ended. data is the visit with leftAt and the final inWorldMs.A key with Visits of my worlds
review.created, review.updated
A review of your world was written or changed. data is a review as in /me/reviews.Any key
review.removed
A review left your list (hidden, replaced, its author banned). data: id, worldId and removed: true.Any key
member.joined
Someone joined a community you own. data: communityId and member as in /me/communities/{id}/members.Any key
chat.message
A new message in a chat of one of your bots, not the bot's own. data: botId, communityId and message as the bot messages endpoint lists it.A key with Community bots
coins.received
Coins or a tip for you. data is an item of /me/coins/received.Any key
ping
Sent when you save the webhook and by Send test. data: keyId.Any key

A chat.message event

{
  "id": "evt_7Kq9xY2LmPa0bCdE",
  "type": "chat.message",
  "createdAt": 1764000000000,
  "keyId": "7",
  "data": {
    "botId": "100500",
    "communityId": "31",
    "message": {
      "id": "9001",
      "chatId": "501",
      "communityId": "31",
      "kind": "text",
      "sender": {"id": "100042", "nickname": "Taras", "bot": false, "gamertag": "Taras2010", "gamertagVerified": true},
      "body": "hi from the app",
      "createdAt": 1764000000000
    }
  }
}

Events follow the same privacy rules as the endpoints: players who do not share their visits stay anonymous, blocked players are left out, and so on. They start when you add the webhook or the event; nothing older is sent.

Check the signature

Every event comes as a POST to your address with these headers. They follow the open Standard Webhooks spec (standardwebhooks.com), which has ready libraries for Python, JavaScript, Go, Java and PHP; or check it yourself:

POST /krak HTTP/1.1
Host: mc.example.com
Content-Type: application/json
User-Agent: KrakWebhooks/1
webhook-id: evt_7Kq9xY2LmPa0bCdE
webhook-timestamp: 1764000000
webhook-signature: v1,<base64 of the HMAC-SHA256>

{"id":"evt_7Kq9xY2LmPa0bCdE","type":"chat.message","createdAt":1764000000000,"keyId":"7","data":{…}}
  1. Take the part of your secret after whsec_ and decode it from base64: that is the key.
  2. Compute HMAC-SHA256 with that key over webhook-id, a dot, webhook-timestamp, a dot and the raw body exactly as it came, and encode the result in base64.
  3. webhook-signature holds one or more signatures separated by spaces (two for 24 hours after you rotate the secret), each written as v1,<base64>. Accept the event when one of them equals yours, and compare in constant time.
  4. Reject a webhook-timestamp more than 5 minutes away from your clock, so an old delivery cannot be replayed.
  5. A retry sends the same webhook-id: remember the ids you handled and skip repeats. Answer with 2xx within 10 seconds and do slow work after answering.

Python

# Checks that a webhook really comes from Krak (Standard Webhooks), Python standard library only.
import base64
import hashlib
import hmac
import os
import time

SECRET = os.environ["KRAK_WEBHOOK_SECRET"]  # whsec_..., shown once when you save the webhook in the app


def verify(headers, body):
    # headers: the request's headers; body: the raw request body (bytes), exactly as received.
    msg_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 5 * 60:
        return False  # too old or too far ahead: maybe a replay
    key = base64.b64decode(SECRET.removeprefix("whsec_"))
    mac = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest()
    expected = ("v1," + base64.b64encode(mac).decode()).encode()
    return any(hmac.compare_digest(s.encode(), expected) for s in headers.get("webhook-signature", "").split())

Node.js

// Checks that a webhook really comes from Krak (Standard Webhooks), Node.js 18 or newer, no packages.
const crypto = require("node:crypto");
const http = require("node:http");

const SECRET = process.env.KRAK_WEBHOOK_SECRET; // whsec_..., shown once when you save the webhook in the app

// headers: req.headers (Node writes the names in lower case); body: the raw request body (a Buffer), exactly as received.
function verify(headers, body) {
  const id = headers["webhook-id"] || "";
  const timestamp = headers["webhook-timestamp"] || "";
  if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 5 * 60) {
    return false; // too old or too far ahead: maybe a replay
  }
  const key = Buffer.from(SECRET.replace(/^whsec_/, ""), "base64");
  const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
  return (headers["webhook-signature"] || "").split(" ").some((signature) => {
    const [version, value = ""] = signature.split(",");
    const got = Buffer.from(value, "base64");
    return version === "v1" && got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
}

// A receiver behind your HTTPS reverse proxy: answer 2xx at once and skip repeats (a retry has the same webhook-id).
const handled = new Set(); // keep the handled ids in your database in real code
http.createServer((req, res) => {
  const chunks = [];
  req.on("data", (chunk) => chunks.push(chunk));
  req.on("end", () => {
    const body = Buffer.concat(chunks);
    if (!verify(req.headers, body)) {
      res.writeHead(401).end();
      return;
    }
    const id = req.headers["webhook-id"];
    if (!handled.has(id)) {
      handled.add(id);
      const event = JSON.parse(body);
      console.log(event.type, JSON.stringify(event.data));
    }
    res.writeHead(204).end();
  });
}).listen(8080, "127.0.0.1");

Test your code with the spec's own example (skip the time check for it): this secret, id, timestamp and body give this signature.

secret     whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw
webhook-id msg_p5jXN8AQM9LWM0D4loKWxJek
timestamp  1614265330
body       {"test": 2432232314}
signature  v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=

Delivery and retries

  • Every event is delivered at least once and mostly in order, one at a time per webhook. A 2xx answer within 10 seconds counts as delivered; the body of your answer is ignored.
  • Any other answer, a redirect or no answer is retried after 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours and 6 hours; then the event is dropped.
  • 410 Gone switches the webhook off at once. After at least a day of failures (50 failed attempts in a row) it is switched off too and you get a notification in the app. Send test with a 2xx answer switches it back on.
  • At most 10,000 events wait per webhook (the oldest go first). A body is at most 64 KiB. Deleting the webhook drops the waiting events.

The endpoints stay the source of truth. Keep the cursors of the feeds you use: after downtime, or while the webhook was off, read what you missed from /me/visits, /me/reviews, /me/coins/received or the bot messages endpoint.

Players' privacy

The API never shows you more than the app shows you, and for visits it asks the players first:

  • A visit names the player (Krak id, nickname, gamertag) only while they keep Let world owners' tools see my visits on in Settings > Privacy. It is on for players 16 or older and off for younger ones, who may turn it on. Otherwise the visit is anonymous: times only.
  • Players under 13, deleted and banned accounts, and anyone with a block between you are never named. Players who joined by address or through Xbox are named only while they let hosts see their Xbox link. Xbox gamertags of people without a Krak account are never shown.
  • World details tell players that the world's owner receives visits through the Krak API, for 30 days after your key last read them.
  • When a player turns the setting off, their whole history disappears from the API at once. What your server already stored is yours to look after: see Developer terms.

Errors

The HTTP status and the code of every error the API answers:

401 api_key_required
No Authorization: Bearer header.
401 invalid_api_key
The key is malformed, unknown, deleted or revoked, or its account is not active.
403 scope_denied
The key lacks the permission the endpoint needs, named in details.scope: Can start and stop my worlds, Visits of my worlds or Community bots.
403 room_blocked
Moderators hid or blocked the world.
404 world_not_found
Not your world, deleted or unknown. For GET /worlds/{id}: the world is not open in the catalog.
409 not_on_server
The world is not on one of your Krak Servers: it is hosted from an app, or it is an External server.
409 agent_offline
The Krak Server is not connected. Nothing changed.
409 host_limit
Your account already hosts another world (one world at a time); details names it.
409 not_hosting
Restart while hosting is off: start the world first.
429 rate_limited
Too many requests: try again after Retry-After seconds (also in details.retryAfter). The daily cap adds details.limit "daily".
503 server_agent_disabled
Krak Server is switched off on Krak's side for now.
400 validation_failed
A parameter or a field is wrong; details.fields names it.
400 invalid_cursor
after or cursor is not a cursor the API gave you.
404 user_not_found
Unknown player, or one the API does not name to you.
404 community_not_found
Not a community you own, or deleted. On the bot endpoints: the bot is not in that community.
409 visits_unavailable
Visits of an External server: Krak does not see who joins it.
503 players_api_disabled
Visits, profiles and gamertag lookups are switched off on Krak's side for now.
401 status_token_required
Send the world's status token (krak_st_…), not an API key.
401 invalid_status_token
The status token is unknown or replaced, or its world or account no longer allows it.
403 status_token_wrong_world
The status token belongs to another world: check the world id in the path.
503 owner_status_disabled
Player count reports are switched off on Krak's side for now.
403 bot_disabled
Krak's moderators disabled the bot; details.reason says why.
403 bot_inactive
The bot cannot write there now: you are no longer an owner or moderator of the community (owner_not_admin), or your account is banned or restricted (owner_restricted), in details.reason.
403 community_muted
The community's moderators muted the bot; details.until says until when.
403 restricted
The bot account may not send messages for now: an automatic or a moderator's restriction.
403 not_message_author
Only the bot's own messages can be deleted.
404 bot_not_found
Not one of your bots, or deleted.
404 message_not_found
Unknown message, or it is already deleted.
409 client_msg_id_reused
The bot already used this clientMsgId in another chat.
503 bots_disabled
Community bots are switched off on Krak's side for now.

Limits

  • 60 requests per minute per key, 120 per minute for all of your keys together.
  • Start, stop and restart: also 10 per minute per account and 200 per key per day (UTC).
  • Wrong keys: after 30 failed requests in a minute from one IP address, that address gets 429.
  • GET /worlds/{id}: 60 requests per minute per IP address. The answer is cached for 15 seconds, so asking more often brings nothing new.
  • Profiles: 5,000 ids per key per day (UTC). Gamertag lookups: 10,000 names per key per day. A batch counts every id or name, found or not.

Developer terms

You accept them when a key gets Visits of my worlds or Community bots and when you create a bot. They apply to everything you read with a key:

  1. Use the data only for your own world or community.
  2. Do not sell, share or publish it.
  3. Delete a player's data when they ask you to.
  4. Rewards may never depend on the stars of a review.
  5. Krak may revoke keys that are abused and act on the account.
  6. Chat messages your bot receives are only for its bridge: keep them no longer than the bridge needs, and never publish them anywhere else or sell them. You answer for everything your bot posts.

Bot examples

Two small bots in Python. Both read the key and the world id from environment variables, so the key never sits in the code.

To find your world's id, call GET /me/worlds once (the curl request above) and take the id of your world.

For /status a key without the switch is enough; to start and stop, the key needs Can start and stop my worlds. Only admins can start and stop: on Discord members with the Manage Server permission (by default), on Telegram the user ids you list.

Discord bot

Commands /status, /start and /stop (discord.py 2). Create an application with a bot in the Discord Developer Portal, invite it to your server with the bot and applications.commands scopes, then run it:

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 shows /start and /stop only to members with the Manage Server permission; an admin can change that in Server Settings > Integrations.

Telegram bot

Commands /status, /startworld and /stopworld (python-telegram-bot 21). They are not /start and /stop because Telegram itself sends /start when someone opens a bot. Create the bot with @BotFather, then run it:

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()

Only the Telegram user ids in TELEGRAM_ADMINS (separated by commas) can start and stop the world.

Reward script

Gives a reward on your server for every full hour a Krak player spends in your world. It reads the visits feed every 30 seconds and keeps its cursor in a file. The key needs Visits of my worlds:

export KRAK_API_KEY="krak_k7q4m2xp_…"
python rewards.py
# pip install httpx
# Gives a reward on your server for every full hour a Krak player spends in your world.
import json
import os
import time

import httpx

API = "https://krak-mp.cc/api/public/v1"
KRAK_KEY = os.environ["KRAK_API_KEY"]   # a key with "Visits of my worlds": Settings > For developers
STATE = "rewards_state.json"            # the feed's cursor and the hours already rewarded


def load():
    try:
        with open(STATE) as f:
            return json.load(f)
    except FileNotFoundError:
        return {"after": None, "hours": {}}


def reward(player, hours):
    # Replace this with your server's command, for example through RCON.
    name = player.get("gamertag") or player["nickname"]
    print(f"give {name} {hours} reward(s)")


state = load()
while True:
    params = {"limit": 200}
    if state["after"]:
        params["after"] = state["after"]
    r = httpx.get(API + "/me/visits", params=params, headers={"Authorization": f"Bearer {KRAK_KEY}"}, timeout=15)
    data = r.json()
    if r.is_error:
        raise SystemExit(data["error"]["code"])
    for visit in data["items"]:
        player = visit["player"]
        if player is None or visit["live"]:
            continue  # an anonymous visit, or one still going on: wait until it ends
        hours = visit["inWorldMs"] // 3_600_000
        done = state["hours"].get(visit["id"], 0)
        if hours > done:
            reward(player, hours - done)
            state["hours"][visit["id"]] = hours
    state["after"] = data["nextCursor"]
    with open(STATE, "w") as f:
        json.dump(state, f)
    if not data["more"]:
        time.sleep(30)

Replace reward() with your server's command, for example through RCON. Anonymous visits are skipped: the player did not agree to be named.

Minecraft chat bridge

A skeleton of a bridge between a community chat and your Minecraft server's chat, in Python with its standard library only. It receives chat.message events behind your HTTPS reverse proxy, checks the signature and hands each message to send_to_minecraft(); post_from_minecraft() posts what a player wrote in the game as Steve via your bot. The key needs Community bots and its webhook the chat.message event:

export KRAK_API_KEY="krak_k7q4m2xp_…"
export KRAK_WEBHOOK_SECRET="whsec_…"
export KRAK_BOT_ID="100500"
export KRAK_COMMUNITY_ID="31"
python bridge.py
# A skeleton of a bridge between a Krak community chat and your Minecraft server's chat, Python 3.9+ standard library.
# Krak -> Minecraft: Krak posts chat.message events here. Run it behind your HTTPS reverse proxy, for example Caddy:
#   mc.example.com { reverse_proxy /krak 127.0.0.1:8080 }
# and set https://mc.example.com/krak as the key's webhook in the app, with the event chat.message.
# Minecraft -> Krak: your server's chat hook calls post_from_minecraft(player, text).
import base64
import hashlib
import hmac
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

API = "https://krak-mp.cc/api/public/v1"
KRAK_KEY = os.environ["KRAK_API_KEY"]          # a key with "Community bots": Settings > For developers
SECRET = os.environ["KRAK_WEBHOOK_SECRET"]     # whsec_..., shown once when you save the webhook
BOT_ID = os.environ["KRAK_BOT_ID"]             # GET /bots lists your bots and their communities
COMMUNITY_ID = os.environ["KRAK_COMMUNITY_ID"]
handled = {}                                   # webhook-id -> when: a retry of the same event is skipped


def send_to_minecraft(name, text):
    # Replace this with your server's command, for example tellraw through RCON.
    print(f"[Krak] <{name}> {text}")


def post_from_minecraft(player, text):
    body = json.dumps({"body": text[:1000], "bridge": {"name": player[:32]}}).encode()
    req = urllib.request.Request(f"{API}/bots/{BOT_ID}/communities/{COMMUNITY_ID}/messages", data=body, method="POST",
                                 headers={"Authorization": f"Bearer {KRAK_KEY}", "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            return json.load(r)["message"]
    except urllib.error.HTTPError as e:  # for example 429 rate_limited (wait Retry-After seconds) or 403 community_muted
        print("Krak refused the message:", e.code, e.read().decode(errors="replace")[:300])


def verified(headers, body):
    msg_id, timestamp = headers.get("webhook-id", ""), headers.get("webhook-timestamp", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 5 * 60:
        return False
    key = base64.b64decode(SECRET.removeprefix("whsec_"))
    mac = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest()
    expected = ("v1," + base64.b64encode(mac).decode()).encode()
    return any(hmac.compare_digest(s.encode(), expected) for s in headers.get("webhook-signature", "").split())


class Webhook(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(min(int(self.headers.get("Content-Length") or 0), 65536))
        if not verified(self.headers, body):
            self.send_response(401)
            self.end_headers()
            return
        self.send_response(204)  # answer at once: Krak waits at most 10 seconds
        self.end_headers()
        msg_id, now = self.headers["webhook-id"], time.time()
        if msg_id in handled:
            return
        handled[msg_id] = now
        for old in [k for k, t in list(handled.items()) if t < now - 12 * 3600]:  # retries end within 9 hours
            handled.pop(old, None)
        event = json.loads(body)
        if event["type"] != "chat.message":
            return  # ping and the other events
        m = event["data"]["message"]
        if m["sender"]["id"] == BOT_ID:
            return  # the bot's own message: skip it, or the bridge echoes itself
        name = m["bridge"]["name"] if "bridge" in m else m["sender"]["nickname"]
        send_to_minecraft(name, m["body"] or f"[{m['kind']}]")


server = ThreadingHTTPServer(("127.0.0.1", 8080), Webhook)
threading.Thread(target=server.serve_forever, daemon=True).start()
for line in sys.stdin:  # to try it, type "Steve: hello" and it is posted as Steve via your bot
    player, _, text = line.strip().partition(": ")
    if player and text:
        post_from_minecraft(player, text)
threading.Event().wait()  # no terminal (a service): keep receiving webhooks

Replace send_to_minecraft() with your server's command (for example tellraw through RCON) and call post_from_minecraft() from your server's chat hook. To try it, type Steve: hello in the terminal.

Questions or ideas about the API? Ask on our Discord server or write to support@krak-mp.cc.