Build the first complete implementation of the Astra_Shift Discord bot in this new Python Discord-bot project. User requirements (German): bot named Astra_Shift, red/black design, leveling system with configurable level roles that members unlock and automatically receive, counting system, ticket system, moderation, create/manage custom commands, and a dashboard to configure all of it. Aim for a polished, usable implementation rather than a placeholder.

Implement feature code only; do not write tests and do not attempt to build/verify. Inspect the starter project structure and work within its conventions. Use a persistent SQLite database (or the existing project's persistence approach) so settings, XP/levels, counts, tickets, custom commands, and moderation configuration survive restarts. Use discord.py-compatible modern APIs.

Required behavior:

  • Astra_Shift branding and red/black embeds/UI.
  • Leveling: award XP on eligible messages with anti-spam cooldown, calculate levels, configure per-guild level-to-role rewards, automatically assign unlocked roles, and provide a level/profile or leaderboard command. Avoid awarding XP in counting/ticket channels if appropriate.
  • Counting: configurable channel, enforce ascending count and prevent a member from counting twice consecutively, reset or handle invalid counts cleanly, persist current count, provide admin configuration through dashboard/commands.
  • Tickets: configurable panel/channel/category/support roles, persistent create/close controls that survive restart, private ticket channels, safe permissions, close/archive workflow.
  • Moderation: practical slash commands for kick, ban, timeout/untimeout, purge, warn and warning review; permission checks, audit log/reason handling, useful user feedback. Do not permit privilege escalation.
  • Custom commands: dashboard CRUD for guild-scoped trigger/response commands, with safe plain-text/limited embed responses; prevent mentions/everyone abuse and avoid executing arbitrary code. Include a command to invoke them and preserve settings.
  • Dashboard: serve a polished red/black responsive web dashboard via an HTTP server running in the bot process (use the platform's public bot HTTP hosting convention/environment). Include settings pages/sections for leveling and role rewards, counting, tickets, moderation configuration/log channel, and custom commands. Protect admin changes: do not expose an unauthenticated public configuration API. Use a secure dashboard secret/session mechanism sourced from environment/config; if Discord OAuth is supported straightforwardly by the starter, use it and verify guild Manage Server permissions. Otherwise provide secure first-run setup and clearly document required environment variables and guild/admin authorization. Never hardcode credentials or tokens. Dashboard must use real persistent data and be usable after deployment.

Add sensible slash commands for setup/status and core user-facing functions, helpful error handling, and concise setup documentation covering Discord bot intents/permissions, token and dashboard secret configuration, deployment, inviting bot to Astra_Shift, and dashboard access. The bot cannot be invited to the user's server automatically, so make the setup process clear. Preserve existing project config and dependencies as appropriate. Do not claim it has been deployed or joined the server.

Kodari AI
KodariOct 27 at 3:37 pm 3
AstraShiftBot
A comprehensive Discord bot with red/black branding featuring leveling with configurable role rewards, counting system, ticket management, moderation tools, custom commands, and a secure web dashboard. Built with discord.py and SQLite persistence, offering slash commands for setup, user engagement, and admin configuration through an authenticated dashboard interface.
  1. Build persistent SQLite-backed leveling, counting, tickets, moderation, and custom commands.

  2. Add slash-command setup and a responsive dashboard secured with Discord OAuth and guild permission checks.

  3. Add deployment and configuration documentation.

Astra_Shift is implemented with persistent SQLite storage for leveling and role rewards, counting, private tickets, moderation records, and custom commands. The responsive red-and-black dashboard uses Discord OAuth and checks for Manage Server permission.

To deploy, copy .env.example to .env, add your bot token and Discord OAuth credentials, and register https://0a02hr2x.kodaribots.com/auth/callback as the OAuth redirect URI. Enable Message Content Intent and Server Members Intent in the Discord Developer Portal; both are required for XP, counting, and role rewards. Setup details are in README.md.

Dashboard: https://0a02hr2x.kodaribots.com — available while the bot is hosted and running. The bot has not been deployed or joined to a server; invite Astra_Shift after deployment, then use /ticket setup and /ticket panel to publish tickets.

Kodari can make mistakes. Review important code before using.
Files
bot.py
README.md
requirements.txt
Code
3 959
bot.py
import asyncio
import hashlib
import hmac
import html
import json
import logging
import math
import os
import random
import re
import secrets
import sqlite3
import time
from datetime import timedelta
from urllib.parse import urlencode

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

load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("astra_shift")
BRAND = discord.Color.from_rgb(190, 24, 35)
DEFAULTS = {
    "xp_cooldown": 60,
    "xp_min": 15,
    "xp_max": 25,
    "counting_channel_id": None,
    "ticket_panel_channel_id": None,
    "ticket_category_id": None,
    "ticket_support_role_ids": [],
    "ticket_log_channel_id": None,
    "mod_log_channel_id": None,
    "warn_threshold": 0,
}


class Database:
    def __init__(self, path="astra_shift.sqlite3"):
        self.connection = sqlite3.connect(path)
        self.connection.row_factory = sqlite3.Row
        self.connection.executescript("""
            PRAGMA journal_mode=WAL;
            CREATE TABLE IF NOT EXISTS guild_settings (guild_id INTEGER PRIMARY KEY, data TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS xp (guild_id INTEGER NOT NULL, user_id INTEGER NOT NULL, points INTEGER NOT NULL DEFAULT 0, last_award REAL NOT NULL DEFAULT 0, PRIMARY KEY (guild_id, user_id));
            CREATE TABLE IF NOT EXISTS level_roles (guild_id INTEGER NOT NULL, level INTEGER NOT NULL, role_id INTEGER NOT NULL, PRIMARY KEY (guild_id, level));
            CREATE TABLE IF NOT EXISTS counting (guild_id INTEGER PRIMARY KEY, current_count INTEGER NOT NULL DEFAULT 0, last_user_id INTEGER);
            CREATE TABLE IF NOT EXISTS tickets (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id INTEGER NOT NULL, user_id INTEGER NOT NULL, channel_id INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL, created_at REAL NOT NULL);
            CREATE UNIQUE INDEX IF NOT EXISTS one_open_ticket_per_user ON tickets(guild_id, user_id) WHERE status IN ('creating', 'open');
            CREATE TABLE IF NOT EXISTS warnings (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id INTEGER NOT NULL, user_id INTEGER NOT NULL, moderator_id INTEGER NOT NULL, reason TEXT NOT NULL, created_at REAL NOT NULL);
            CREATE TABLE IF NOT EXISTS custom_commands (guild_id INTEGER NOT NULL, trigger TEXT NOT NULL, response TEXT NOT NULL, PRIMARY KEY(guild_id, trigger));
        """)
        self.connection.commit()

    def settings(self, guild_id):
        row = self.connection.execute("SELECT data FROM guild_settings WHERE guild_id=?", (guild_id,)).fetchone()
        if row is None:
            self.connection.execute("INSERT INTO guild_settings(guild_id, data) VALUES (?, ?)", (guild_id, json.dumps(DEFAULTS)))
            self.connection.commit()
            return dict(DEFAULTS)
        data = dict(DEFAULTS)
        data.update(json.loads(row["data"]))
        return data

    def save_settings(self, guild_id, data):
        self.connection.execute("INSERT INTO guild_settings(guild_id, data) VALUES (?, ?) ON CONFLICT(guild_id) DO UPDATE SET data=excluded.data", (guild_id, json.dumps(data)))
        self.connection.commit()

    def count_configure(self, guild_id):
        self.connection.execute("INSERT OR IGNORE INTO counting(guild_id) VALUES (?)", (guild_id,))
        self.connection.commit()

    def count_state(self, guild_id):
        return self.connection.execute("SELECT current_count, last_user_id FROM counting WHERE guild_id=?", (guild_id,)).fetchone()

    def count_update(self, guild_id, count, user_id):
        self.connection.execute("INSERT INTO counting(guild_id, current_count, last_user_id) VALUES (?, ?, ?) ON CONFLICT(guild_id) DO UPDATE SET current_count=excluded.current_count, last_user_id=excluded.last_user_id", (guild_id, count, user_id))
        self.connection.commit()

    def award_xp(self, guild_id, user_id, now, cooldown, amount):
        row = self.connection.execute("SELECT points, last_award FROM xp WHERE guild_id=? AND user_id=?", (guild_id, user_id)).fetchone()
        old_points = row["points"] if row else 0
        if row and now - row["last_award"] < cooldown:
            return None
        new_points = old_points + amount
        self.connection.execute("INSERT INTO xp(guild_id, user_id, points, last_award) VALUES (?, ?, ?, ?) ON CONFLICT(guild_id, user_id) DO UPDATE SET points=excluded.points, last_award=excluded.last_award", (guild_id, user_id, new_points, now))
        self.connection.commit()
        return old_points, new_points

    def xp_points(self, guild_id, user_id):
        row = self.connection.execute("SELECT points FROM xp WHERE guild_id=? AND user_id=?", (guild_id, user_id)).fetchone()
        return row["points"] if row else 0

    def leaderboard(self, guild_id, limit=10):
        return self.connection.execute("SELECT user_id, points FROM xp WHERE guild_id=? ORDER BY points DESC LIMIT ?", (guild_id, limit)).fetchall()

    def level_roles(self, guild_id):
        return self.connection.execute("SELECT level, role_id FROM level_roles WHERE guild_id=? ORDER BY level", (guild_id,)).fetchall()

    def add_level_role(self, guild_id, level, role_id):
        self.connection.execute("INSERT INTO level_roles(guild_id, level, role_id) VALUES (?, ?, ?) ON CONFLICT(guild_id, level) DO UPDATE SET role_id=excluded.role_id", (guild_id, level, role_id))
        self.connection.commit()

    def remove_level_role(self, guild_id, level):
        self.connection.execute("DELETE FROM level_roles WHERE guild_id=? AND level=?", (guild_id, level))
        self.connection.commit()

    def reserve_ticket(self, guild_id, user_id):
        try:
            cursor = self.connection.execute("INSERT INTO tickets(guild_id, user_id, status, created_at) VALUES (?, ?, 'creating', ?)", (guild_id, user_id, time.time()))
            self.connection.commit()
            return cursor.lastrowid
        except sqlite3.IntegrityError:
            return None

    def finish_ticket(self, ticket_id, channel_id):
        self.connection.execute("UPDATE tickets SET channel_id=?, status='open' WHERE id=?", (channel_id, ticket_id))
        self.connection.commit()

    def cancel_ticket(self, ticket_id):
        self.connection.execute("DELETE FROM tickets WHERE id=? AND status='creating'", (ticket_id,))
        self.connection.commit()

    def ticket_for_channel(self, channel_id):
        return self.connection.execute("SELECT * FROM tickets WHERE channel_id=?", (channel_id,)).fetchone()

    def open_ticket(self, guild_id, user_id):
        return self.connection.execute("SELECT * FROM tickets WHERE guild_id=? AND user_id=? AND status IN ('creating', 'open')", (guild_id, user_id)).fetchone()

    def close_ticket(self, ticket_id):
        self.connection.execute("UPDATE tickets SET status='closed' WHERE id=? AND status='open'", (ticket_id,))
        self.connection.commit()

    def add_warning(self, guild_id, user_id, moderator_id, reason):
        self.connection.execute("INSERT INTO warnings(guild_id, user_id, moderator_id, reason, created_at) VALUES (?, ?, ?, ?, ?)", (guild_id, user_id, moderator_id, reason, time.time()))
        self.connection.commit()

    def warnings_for(self, guild_id, user_id):
        return self.connection.execute("SELECT * FROM warnings WHERE guild_id=? AND user_id=? ORDER BY id DESC LIMIT 20", (guild_id, user_id)).fetchall()

    def warning_count(self, guild_id, user_id):
        return self.connection.execute("SELECT COUNT(*) AS n FROM warnings WHERE guild_id=? AND user_id=?", (guild_id, user_id)).fetchone()["n"]

    def custom_commands(self, guild_id):
        return self.connection.execute("SELECT trigger, response FROM custom_commands WHERE guild_id=? ORDER BY trigger", (guild_id,)).fetchall()

    def custom_command(self, guild_id, trigger):
        return self.connection.execute("SELECT response FROM custom_commands WHERE guild_id=? AND trigger=?", (guild_id, trigger)).fetchone()

    def save_custom(self, guild_id, trigger, response):
        self.connection.execute("INSERT INTO custom_commands(guild_id, trigger, response) VALUES (?, ?, ?) ON CONFLICT(guild_id, trigger) DO UPDATE SET response=excluded.response", (guild_id, trigger, response))
        self.connection.commit()

    def delete_custom(self, guild_id, trigger):
        self.connection.execute("DELETE FROM custom_commands WHERE guild_id=? AND trigger=?", (guild_id, trigger))
        self.connection.commit()


db = Database()
intents = discord.Intents.default()
intents.message_content = True
intents.members = True


class AstraBot(commands.Bot):
    async def setup_hook(self):
        self.add_view(TicketPanelView())
        self.add_view(TicketControlsView())
        try:
            await self.tree.sync()
        except discord.HTTPException:
            log.exception("Slash-command synchronization failed")
        await start_dashboard(self)

    async def close(self):
        if dashboard_runner:
            await dashboard_runner.cleanup()
        if http_session and not http_session.closed:
            await http_session.close()
        await super().close()


bot = AstraBot(command_prefix="!", intents=intents)


def level_for_xp(points):
    return int(math.sqrt(max(points, 0) / 100))


def clean_custom_response(text):
    return re.sub(r"@", "@\u200b", text)


async def send_mod_log(guild, title, description):
    channel_id = db.settings(guild.id).get("mod_log_channel_id")
    channel = guild.get_channel(channel_id) if channel_id else None