Build NYXIS as a Python Discord bot plus the public HTTPS HTTP backend used by the NYXEN Minecraft plugin. Inspect the existing project/template files first and preserve its conventions. Deliver feature code/configuration/docs only; do not add tests or test scripts and do not try to build.

PRODUCT / DATA OWNERSHIP This is the sole persistent source of truth for Minecraft/Discord account links, NEX and NYXIUM wallets, rank/multipliers, transaction ledger, Bloodhunt bounties, Blackmarket listings/purchases, spawner ownership receipts, Crucible records, and admin audit logs. Do not keep a separate Discord-only economy. Use durable SQL persistence with schema initialization/migrations and transactions (SQLite is acceptable if the host provides durable storage); parameterized queries, constraints, safe concurrent writes, and idempotency are required. The HTTP API must run in the same bot process and listen on the hosting platform's PORT, so the hosted project exposes it over Kodari HTTPS. Provide environment/config documentation; never log secrets.

PLUGIN API CONTRACT (must match NYXEN exactly) Provide versioned JSON routes:

  • GET /api/v1/health
  • GET /api/v1/players/{uuid} -> {minecraft_name,rank_id,rank_name,multiplier,balances:{NEX,NYXIUM},discord_link?}
  • POST /api/v1/link-codes {minecraft_uuid,minecraft_name} -> {code,expires_at}; expire codes quickly, store only a safe hash if practical. Discord /link <code> consumes code and links the caller. Enforce one Minecraft account per Discord account and one Discord account per Minecraft account by default; no unlimited linking.
  • GET /api/v1/leaderboards/{nex|nyxium|wealth}?limit=10 (wealth must be a documented deterministic calculation and rankings must not issue expensive per-user queries).
  • POST /api/v1/economy/transactions {player_uuid,currency:"NEX"|"NYXIUM",direction:"CREDIT"|"DEBIT",amount,reason,idempotency_key,metadata}. Accept positive integer amounts only; keep currencies entirely separate. Use atomic wallet + ledger updates and unique idempotency keys. Apply configured server-side rank multiplier only to eligible NYXIUM earning reasons; never multiply debits or NEX. Return actual amount, multiplier, and balances. The plugin is trusted to originate requests, normal Discord commands must never let players grant themselves funds.
  • POST /api/v1/bounties {creator_uuid,target_uuid,amount_nex,idempotency_key}; GET /api/v1/bounties?target_uuid={uuid}&status=active; POST /api/v1/bounties/{bounty_id}/claim {hunter_uuid,kill_id}. Debit creator atomically; reject invalid/self bounty, duplicate kill/claim, expired/claimed bounty, and configurable repeat-pair/anti-farming claims. Record ledger and audit entries.
  • GET /api/v1/market/listings?status=active&limit=; POST /api/v1/market/listings {seller_uuid,item_payload,price_nex,expires_at,idempotency_key}; POST /api/v1/market/purchases/prepare {buyer_uuid,listing_id,idempotency_key}; POST /api/v1/market/purchases/{purchase_id}/commit; POST /api/v1/market/purchases/{purchase_id}/cancel. Enforce listing expiry, immutable item payload, seller/buyer validation, atomic listing reservation so concurrent buyers cannot both win, safe charge/refund state transitions, and transaction history. Plugin is the only source of item payload and performs/validates Minecraft item delivery; Discord is browse-only for now.
  • POST /api/v1/spawners/purchases {player_uuid,spawner_type,price_nyxium,idempotency_key}; GET /api/v1/players/{uuid}/spawners. Debit NYXIUM atomically. If supporting plugin tracking calls, provide /api/v1/spawners/register and /api/v1/spawners/remove with ownership/location metadata.
  • POST /api/v1/crucible/kills {killer_uuid,victim_uuid,kind:"PLAYER"|"BOT",kill_id}; GET /api/v1/players/{uuid}/pvp; GET /api/v1/leaderboards/pvp?limit=. Deduplicate kill IDs; enforce server-side all quotas, unlock progress, repeat-pair/alt-abuse protections. Bot kills score 0.5 of a real kill, maximum 12 bot kills per player per rolling/hour window, and each four bot kills require one real player kill before the next four; expose enough stats for the plugin and Discord display. Real kills are authoritative only when submitted by the signed plugin.

API SECURITY Plugin requests use shared HMAC authentication: headers X-NYXEN-Timestamp (Unix seconds), X-NYXEN-Nonce (unique), X-NYXEN-Signature (hex HMAC-SHA256 over timestamp + "\n" + nonce + "\n" + raw_request_body, keyed by configured shared secret). Require HTTPS in production; reject bad signatures, timestamps outside a small configurable window (default 60 sec), and replayed nonces. Use constant-time signature comparison, size/rate limits and safe JSON validation. Configure shared secret via environment/settings, not hardcoded or committed. Error responses should be consistent and must not leak internals. Internal Discord command actions should use the same durable transaction/service layer, not fake client-facing endpoints.

DISCORD BOT Use proper Discord slash commands, defer long-running responses, handle API/DB failures cleanly, and display currency names and amounts unambiguously. Add /link, /balance [player], /wealth [player], /rank [player], /leaderboard for NEX/NYXIUM/wealth and useful PvP stats, /bounties [player], optional /bounty placement for linked users with validated atomic NEX debit, /market browse listings, /pvp [player], and admin-only commands for player inspection, relevant transaction/action logs, rank assignment, audited currency adjustments, punishments/review, announcements, maintenance notices and server status. Ordinary users get read-only economy/market views and optional validated bounty placement; no user-facing money mint/give command. Discord admin operations must check configured role IDs and/or explicit Manage Guild permission on every command, and persist actor Discord ID, action, target, time, and reason. Log currency/rank/ban events without sensitive data. Commands must show rank multiplier from authoritative stored rank.

SECURITY / FUTURE EXTENSIONS NYXIUM earning multiplier defaults: normal/INITIATE 1x, VANGUARD 2x, ASCENDANT 3x; rank IDs/display labels configurable because names are provisional. Rank resolution and multiplier application are entirely backend-side. NEX and NYXIUM are distinct constrained currency identifiers/columns; never accept aliases that mix them. Provide admin-maintained rank config and auditable changes. Keep logs limited to relevant information and enforce permissions. ECLIPSE battle pass is explicitly future work: schema/service extension points and documented possible integration are enough; do not build paid purchases/reward downloads now. The HTTP/service layer should be modular enough for future reuse by a standalone anti-cheat product; do not expose privileged wallet/admin routes without plugin auth or Discord permission checks.

DONE means the hosted Discord bot and same-process authenticated HTTP backend share durable data, implement the specified exact routes/features and concurrency/security rules, and include deployment, environment, API, slash command, and plugin HMAC setup documentation. No separate Discord economy database.

Kodari AI
KodariOct 18 at 9:59 pm 4
NYXIS
NYXIS is a Python Discord bot with an integrated authenticated HTTP backend powering the NYXEN Minecraft plugin economy. It manages account linking, NEX/NYXIUM wallets, rank multipliers, transaction ledgers, Bloodhunt bounties, Blackmarket listings, spawner ownership, Crucible PvP records, and admin audit logs. Features include HMAC-secured REST API routes, atomic transactions with idempotency, slash commands for economy/market/PvP management, and durable SQL persistence with parameterized queries and concurrency safety.
  1. Build the durable SQLite schema and transactional economy, marketplace, bounty, spawner, rank, and PvP services.

  2. Add the same-process HMAC-authenticated HTTP API and Discord slash commands over that shared service layer.

  3. Add dependency, environment, deployment, API, and plugin-authentication documentation.

Built NYXIS as a discord.py bot and same-process aiohttp backend, available when hosted at https://zcd15t0y.kodaribots.com.

  • Added shared SQLite persistence for account links, separate NEX/NYXIUM wallets, ranks, ledger and audits, bounties, market escrow, spawner receipts, Crucible stats, and moderation records.

  • Implemented the versioned plugin API with HMAC authentication, replay protection, rate limits, idempotent transactions, and the requested economy, marketplace, spawner, bounty, leaderboard, and PvP routes.

  • Added slash commands for linking, economy and PvP views, leaderboards, bounties, market browsing, and audited admin actions with permission checks.

  • Added configuration, dependencies, and deployment/API/plugin-signing documentation. The bot uses PORT supplied by hosting and prints KODARI_READY after connecting.

  • No tests or build were run, as requested.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
api.py
bot.py
config.json
config.py
README.md
requirements.txt
storage.py
Code
8 1,881
bot.py
import asyncio
import json
import logging
import os

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

from api import create_app
from config import configure_logging, load_config
from storage import Database, DomainError, normalize_uuid


logger = logging.getLogger("nyxis")


def make_bot(database, settings):
    intents = discord.Intents.default()
    bot = commands.Bot(command_prefix="!", intents=intents)
    admin_roles = settings["admin_role_ids"]
    admin_group = app_commands.Group(name="admin", description="Audited NYXIS administration")

    async def defer(interaction):
        if not interaction.response.is_done():
            await interaction.response.defer(ephemeral=True, thinking=True)

    async def send(interaction, text):
        await interaction.followup.send(text, ephemeral=True, allowed_mentions=discord.AllowedMentions.none())

    async def resolve_player(interaction, player_name=None):
        if player_name:
            try:
                player_uuid = normalize_uuid(player_name)
            except DomainError:
                player_uuid = await database.uuid_for_name(player_name.strip())
                if player_uuid is None:
                    raise DomainError(404, "No linked or known Minecraft player matches that name.")
        else:
            player_uuid = await database.player_for_discord(interaction.user.id)
            if player_uuid is None:
                raise DomainError(404, "Link your Minecraft account first with `/link`.")
        player_data = await database.player(player_uuid)
        if player_data is None:
            raise DomainError(404, "Player was not found.")
        return player_uuid, player_data

    def admin_check(interaction):
        member = interaction.user
        if getattr(getattr(member, "guild_permissions", None), "manage_guild", False):
            return True
        return any(str(role.id) in admin_roles for role in getattr(member, "roles", []))

    def target_identifier(value):
        try:
            return normalize_uuid(value)
        except DomainError:
            return value.strip()

    @bot.event
    async def on_ready():
        try:
            guild_id = settings["guild_id"]
            if guild_id:
                guild = discord.Object(id=int(guild_id))
                bot.tree.copy_global_to(guild=guild)
                await bot.tree.sync(guild=guild)
            elif not getattr(bot, "_nyxis_synced", False):
                await bot.tree.sync()
            bot._nyxis_synced = True
        except Exception:
            logger.exception("Slash-command synchronization failed")
        logger.info("Discord bot connected")
        print("KODARI_READY", flush=True)

    @bot.tree.command(name="link", description="Link your Minecraft account using a plugin-issued code")
    @app_commands.describe(code="The short-lived code from the NYXEN Minecraft plugin")
    async def link(interaction: discord.Interaction, code: str):
        await defer(interaction)
        player_uuid = await database.consume_link_code(code, interaction.user.id)
        player_data = await database.player(player_uuid)
        await send(interaction, f"Linked **{player_data['minecraft_name'] or player_uuid}** to your Discord account.")

    @bot.tree.command(name="balance", description="View NEX and NYXIUM wallet balances")
    @app_commands.describe(player="Minecraft username or UUID (defaults to your linked account)")
    async def balance(interaction: discord.Interaction, player: str = None):
        await defer(interaction)
        player_uuid, data = await resolve_player(interaction, player)
        await send(interaction, f"**{data['minecraft_name'] or player_uuid}**\n"
             f"NEX: **{data['balances']['NEX']:,}**\nNYXIUM: **{data['balances']['NYXIUM']:,}**")

    @bot.tree.command(name="wealth", description="View the combined NEX + NYXIUM nominal balance")
    @app_commands.describe(player="Minecraft username or UUID (defaults to your linked account)")
    async def wealth(interaction: discord.Interaction, player: str = None):
        await defer(interaction)
        player_uuid, data = await resolve_player(interaction, player)
        total = data["balances"]["NEX"] + data["balances"]["NYXIUM"]
        await send(interaction, f"**{data['minecraft_name'] or player_uuid}** wealth: **{total:,} nominal units** "
             f"(NEX {data['balances']['NEX']:,} + NYXIUM {data['balances']['NYXIUM']:,}; 1:1 calculation).")

    @bot.tree.command(name="rank", description="View a player's authoritative rank and NYXIUM earning multiplier")
    @app_commands.describe(player="Minecraft username or UUID (defaults to your linked account)")
    async def rank(interaction: discord.Interaction, player: str = None):
        await defer(interaction)
        player_uuid, data = await resolve_player(interaction, player)
        await send(interaction, f"**{data['minecraft_name'] or player_uuid}** — {data['rank_name']} (`{data['rank_id']}`), "
             f"NYXIUM earning multiplier: **{data['multiplier']}x** on configured eligible earning reasons only.")

    @bot.tree.command(name="leaderboard", description="View NEX, NYXIUM, wealth, or Crucible PvP standings")
    @app_commands.choices(kind=[
        app_commands.Choice(name="NEX", value="nex"),
        app_commands.Choice(name="NYXIUM", value="nyxium"),
        app_commands.Choice(name="Wealth (NEX + NYXIUM)", value="wealth"),
        app_commands.Choice(name="Crucible PvP score", value="pvp"),
    ])
    @app_commands.describe(kind="Leaderboard type", limit="Number of entries (1–25)")
    async def leaderboard(interaction: discord.Interaction, kind: app_commands.Choice[str], limit: app_commands.Range[int, 1, 25] = 10):
        await defer(interaction)
        if kind.value == "pvp":
            rows = await database.pvp_leaderboard(limit)
            title = "Crucible PvP score"
        else:
            rows = await database.leaderboard(kind.value, limit)
            title = {"nex": "NEX", "nyxium": "NYXIUM", "wealth": "Wealth (NEX + NYXIUM; 1:1 nominal units)"}[kind.value]
        if not rows:
            await send(interaction, f"No entries yet for **{title}**.")
            return
        lines = []
        for index, row in enumerate(rows, 1):
            name = row.get("minecraft_name") or row["minecraft_uuid"]
            value = row["value"]
            shown = f"{value:,.1f}" if kind.value == "pvp" else f"{value:,}"
            lines.append(f"**{index}.** {name} — {shown}")
        await send(interaction, f"**{title} leaderboard**\n" + "\n".join(lines))

    @bot.tree.command(name="bounties", description="Browse active Bloodhunt NEX bounties")
    @app_commands.describe(player="Optional target Minecraft username or UUID")
    async def bounties(interaction: discord.Interaction, player: str = None):
        await defer(interaction)
        target = None
        if player:
            target, _ = await resolve_player(interaction, player)
        rows = await database.bounties(target, "active", 20)
        if not rows:
            await send(interaction, "No active Bloodhunt bounties found.")
            return
        lines = [f"`{row['bounty_id']}` — target `{row['target_uuid']}` — **{row['amount_nex']:,} NEX** — "
                 f"expires <t:{int(row['expires_at'])}:R>" for row in rows]
        await send(interaction, "**Active Bloodhunt bounties**\n" + "\n".join(lines))

    @bot.tree.command(name="bounty", description="Place a NEX Bloodhunt bounty on a Minecraft player")
    @app_commands.describe(target="Target Minecraft username or UUID", amount_nex="Positive whole NEX amount")
    async def bounty(interaction: discord.Interaction, target: str, amount_nex: app_commands.Range[int, 1, 2_000_000_000]):
        await defer(interaction)
        creator_uuid, _ = await resolve_player(interaction)
        target_uuid, target_data = await resolve_player(interaction, target)
        result = await database.create_bounty(creator_uuid, target_uuid, amount_nex,
                                              f"discord-bounty:{interaction.id}")
        await send(interaction, f"Placed **{amount_nex:,} NEX** bounty on **{target_data['minecraft_name'] or target_uuid}**. "
             f"It expires <t:{int(result['expires_at'])}:R>.")

    @bot.tree.command(name="market", description="Browse active NYXEN Blackmarket listings (Discord is browse-only)")
    @app_commands.describe(limit="Number of listings to show (1–10)")
    async def market(interaction: discord.Interaction, limit: app_commands.Range[int, 1, 10] = 5):
        await defer(interaction)
        rows = await database.listings("active", limit)
        if not rows:
            await send(interaction, "There are no active Blackmarket listings.")
            return
        lines = []
        for row in rows:
            payload = json.dumps(row["item_payload"], ensure_ascii=False, separators=(",", ":"))
            if len(payload) > 400:
                payload = payload[:397] + "..."
            lines.append(f"`{row['listing_id']}` — **{row['price_nex']:,} NEX** — seller `{row['seller_uuid']}`\n"
                         f"Payload: `{payload}` — expires <t:{int(row['expires_at'])}:R>")
        await send(interaction, "**Active Blackmarket listings** (purchases and item delivery are handled in Minecraft)\n" + "\n".join(lines))

    @bot.tree.command(name="pvp", description="View Crucible kills, score, and bot-kill quota progress")
    @app_commands.describe(player="Minecraft username or UUID (defaults to your linked account)")
    async def pvp(interaction: discord.Interaction, player: str = None):
        await defer(interaction)
        player_uuid, data = await resolve_player(interaction, player)
        stats = await database.pvp_stats(player_uuid)
        await send(interaction, f"**{data['minecraft_name'] or player_uuid} — Crucible**\n"
             f"Score: **{stats['score']:.1f}** · Player kills: **{stats['player_kills']}** · Bot kills: **{stats['bot_kills']}** · Deaths: **{stats['deaths']}**\n"
             f"Bot kills this hour: **{stats['bot_kills_last_hour']}/{stats['bot_kills_hourly_limit']}** · "
             f"Bot kills until a real player kill is required: **{stats['bot_kills_until_real_kill_required']}**")

    @admin_group.command(name="inspect", description="Inspect a player's authoritative account and progression")
    @app_commands.default_permissions(manage_guild=True)
    @app_commands.check(admin_check)
    async def admin_inspect(interaction: discord.Interaction, player: str):
        await defer(interaction)
        player_uuid, data = await resolve_player(interaction, player)
        stats = await database.pvp_stats(player_uuid)
        spawners = await database.player_spawners(player_uuid)
        records = await database.punishments_for(player_uuid, 10)
        await database.record_admin_action(interaction.user.id, "ADMIN_INSPECT", player_uuid, "Player account inspection")