Build the Discord side of a coordinated Minecraft-to-Discord account linking feature for the new Python Discord bot project. This is paired with CheckBan Bukkit plugin KDR-202610-MTK1DXQV. Exact shared API contract: implement a public HTTPS-compatible HTTP endpoint POST /api/link/request (listen on 0.0.0.0 and use the project’s hosting port convention) secured with header X-API-Key, whose value must match required environment variable LINK_API_KEY. JSON request body: {"minecraft_uuid":"<canonical UUID string>","minecraft_name":"<name>"}. On success return HTTP 200 JSON {"code":"<8 uppercase alphanumeric characters>","expires_in":600}. Store pending codes in SQLite with creation/expiration, Minecraft UUID and current name; make them cryptographically random, one-time, expire after 10 minutes, and enforce one pending/linked relationship safely (reject or invalidate stale conflicts). Add a Discord slash command /link with required code string option. It must atomically validate and consume an unexpired pending code, associate invoking Discord user ID with that Minecraft UUID/name, and reply privately/ephemerally with success and the Minecraft name, or a clear invalid/expired/already-linked error. Persist completed account links in SQLite across restarts; prevent a code from being claimed twice and avoid silently overwriting another account association. Require DISCORD_TOKEN and LINK_API_KEY environment variables; fail safely if API key is absent (do not expose an unauthenticated request endpoint). Keep the Discord bot and HTTP server running together using the existing project scaffold; include clear setup documentation/config descriptions for deployment. Do not build or claim verification. Plugin calls the fixed URL https://98mu2ino.kodaribots.com/api/link/request. Make changes only.

Kodari AI
KodariOct 14 at 8:08 pm 1
DiscordLinkBridge
Implements the Discord side of a Minecraft-to-Discord account linking system. Provides an HTTPS HTTP endpoint POST /api/link/request secured with X-API-Key header, accepting Minecraft UUID and name to generate cryptographically random one-time codes stored in SQLite with 10-minute expiration. Includes a /link Discord slash command that atomically validates and consumes pending codes, associating Discord user IDs with Minecraft accounts. Persists completed links across restarts, prevents code reuse and account overwrites. Requires DISCORD_TOKEN and LINK_API_KEY environment variables, failing safely if API key is absent. Runs Discord bot and HTTP server concurrently using existing project scaffold.
  1. Build the authenticated link-request API and transactional SQLite storage.

  2. Add the ephemeral /link command and run it alongside the Discord bot.

  3. Document required secrets, hosting, and deployment setup.

Implemented the Discord account-linking bot with an authenticated POST /api/link/request endpoint and an ephemeral /link slash command. Pending codes expire after 10 minutes, can only be claimed once, and SQLite persists links and prevents overwriting existing associations.

Created bot.py, requirements.txt, .env.example, and README.md. Set DISCORD_TOKEN and LINK_API_KEY before startup; the server uses the hosting-provided SERVER_PORT and binds to 0.0.0.0. The documented public endpoint is https://98mu2ino.kodaribots.com/api/link/request.

Add configurable Discord bot presence/status to the existing account-linking bot in this project. Read existing bot.py, README.md, requirements.txt and preserve all current linking/API behavior. Create a root config.json (or another simple documented config file) with defaults for Discord presence status (online/idle/dnd/invisible), activity type (playing/listening/watching/competing/none), and activity text. Load it safely at startup; if missing, create/use sensible defaults, and validate values so bad config falls back safely rather than preventing the bot/API from starting. Apply presence when the bot is ready and document exact options and examples in README.md. Do not change required environment secrets or HTTP endpoint behavior. Make code changes only; do not build or claim verification.

Kodari AI
KodariOct 14 at 8:11 pm 1
  1. Add a safe config.json loader with validated defaults.

  2. Apply configured status and activity on ready without disturbing linking/API behavior.

  3. Document every supported value and show a config example in the README.

Added configurable Discord presence with safe startup defaults. config.json now defaults to online with a “Minecraft account linking” playing activity; README.md documents all supported options and fallback behavior. Presence is applied when the bot is ready, and the existing linking/API behavior and required secrets are unchanged.

Kodari can make mistakes. Review important code before using.
Files
bot.py
config.json
README.md
requirements.txt
Code
4 440
bot.py
import asyncio
import hmac
import json
import logging
import os
import re
import secrets
import sqlite3
import string
import time
from uuid import UUID

import discord
from aiohttp import web
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("kodari-link-bot")

CODE_LENGTH = 8
CODE_ALPHABET = string.ascii_uppercase + string.digits
CODE_PATTERN = re.compile(r"^[A-Z0-9]{8}$")
MINECRAFT_NAME_PATTERN = re.compile(r"^[A-Za-z0-9_]{1,16}$")
CODE_TTL_SECONDS = 600
DEFAULT_PRESENCE_CONFIG = {
    "status": "online",
    "activity_type": "playing",
    "activity_text": "Minecraft account linking",
}
VALID_STATUSES = {"online", "idle", "dnd", "invisible"}
VALID_ACTIVITY_TYPES = {"playing", "listening", "watching", "competing", "none"}


def load_presence_config(path="config.json"):
    try:
        with open(path, "r", encoding="utf-8") as config_file:
            config = json.load(config_file)
    except FileNotFoundError:
        config = DEFAULT_PRESENCE_CONFIG.copy()
        try:
            with open(path, "w", encoding="utf-8") as config_file:
                json.dump(config, config_file, indent=2)
                config_file.write("\n")
        except OSError:
            logger.warning("Could not create %s; using default Discord presence", path)
        return config
    except (OSError, UnicodeDecodeError, json.JSONDecodeError):
        logger.warning("Could not read %s; using default Discord presence", path)
        return DEFAULT_PRESENCE_CONFIG.copy()

    if not isinstance(config, dict):
        logger.warning("%s must contain a JSON object; using default Discord presence", path)
        return DEFAULT_PRESENCE_CONFIG.copy()

    validated = DEFAULT_PRESENCE_CONFIG.copy()
    for key, allowed_values in (
        ("status", VALID_STATUSES),
        ("activity_type", VALID_ACTIVITY_TYPES),
    ):
        value = config.get(key)
        if isinstance(value, str) and value.strip().lower() in allowed_values:
            validated[key] = value.strip().lower()
        elif key in config:
            logger.warning("Invalid %s in %s; using default %s", key, path, validated[key])

    activity_text = config.get("activity_text")
    if isinstance(activity_text, str) and activity_text.strip():
        validated["activity_text"] = activity_text.strip()[:128]
    elif "activity_text" in config:
        logger.warning("Invalid activity_text in %s; using the default", path)
    return validated


class LinkStore:
    def __init__(self, database_path):
        self.database_path = database_path

    def _connect(self):
        return sqlite3.connect(self.database_path, timeout=10)

    def initialize(self):
        connection = self._connect()
        try:
            connection.executescript(
                """
                CREATE TABLE IF NOT EXISTS pending_codes (
                    code TEXT PRIMARY KEY,
                    minecraft_uuid TEXT NOT NULL UNIQUE,
                    minecraft_name TEXT NOT NULL,
                    created_at INTEGER NOT NULL,
                    expires_at INTEGER NOT NULL
                );
                CREATE TABLE IF NOT EXISTS account_links (
                    discord_user_id TEXT PRIMARY KEY,
                    minecraft_uuid TEXT NOT NULL UNIQUE,
                    minecraft_name TEXT NOT NULL,
                    linked_at INTEGER NOT NULL
                );
                """
            )
        finally:
            connection.close()

    def create_pending(self, minecraft_uuid, minecraft_name):
        now = int(time.time())
        expires_at = now + CODE_TTL_SECONDS
        connection = self._connect()
        try:
            connection.execute("BEGIN IMMEDIATE")
            connection.execute("DELETE FROM pending_codes WHERE expires_at <= ?", (now,))

            linked = connection.execute(
                "SELECT 1 FROM account_links WHERE minecraft_uuid = ?",
                (minecraft_uuid,),
            ).fetchone()
            if linked:
                connection.execute(
                    "DELETE FROM pending_codes WHERE minecraft_uuid = ?",
                    (minecraft_uuid,),
                )
                connection.commit()
                return None

            connection.execute(
                "DELETE FROM pending_codes WHERE minecraft_uuid = ?",
                (minecraft_uuid,),
            )
            for _ in range(10):
                code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LENGTH))
                try:
                    connection.execute(
                        """INSERT INTO pending_codes
                           (code, minecraft_uuid, minecraft_name, created_at, expires_at)
                           VALUES (?, ?, ?, ?, ?)""",
                        (code, minecraft_uuid, minecraft_name, now, expires_at),
                    )
                    connection.commit()
                    return code
                except sqlite3.IntegrityError:
                    continue

            raise sqlite3.IntegrityError("Unable to allocate a unique link code")
        finally:
            connection.close()

    def claim_code(self, code, discord_user_id):
        now = int(time.time())
        connection = self._connect()
        try:
            connection.execute("BEGIN IMMEDIATE")
            pending = connection.execute(
                """SELECT minecraft_uuid, minecraft_name, expires_at
                   FROM pending_codes WHERE code = ?""",
                (code,),
            ).fetchone()
            if pending is None:
                connection.commit()
                return "invalid_or_expired", None

            minecraft_uuid, minecraft_name, expires_at = pending
            if expires_at <= now:
                connection.execute("DELETE FROM pending_codes WHERE code = ?", (code,))
                connection.commit()
                return "invalid_or_expired", None

            uuid_linked = connection.execute(
                "SELECT 1 FROM account_links WHERE minecraft_uuid = ?",
                (minecraft_uuid,),
            ).fetchone()
            discord_linked = connection.execute(
                "SELECT 1 FROM account_links WHERE discord_user_id = ?",
                (discord_user_id,),
            ).fetchone()
            if uuid_linked:
                connection.execute("DELETE FROM pending_codes WHERE code = ?", (code,))
                connection.commit()
                return "already_linked", None
            if discord_linked:
                connection.commit()
                return "already_linked", None

            connection.execute(
                """INSERT INTO account_links
                   (discord_user_id, minecraft_uuid, minecraft_name, linked_at)
                   VALUES (?, ?, ?, ?)""",
                (discord_user_id, minecraft_uuid, minecraft_name, now),
            )
            connection.execute("DELETE FROM pending_codes WHERE code = ?", (code,))
            connection.commit()
            return "success", minecraft_name
        finally:
            connection.close()