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