Tarek BK

Project: ASCND Ticket & Vouch Discord Bot

You are an experienced Python developer specializing in Discord bots, discord.py, application commands, SQLite databases, and reliable production-ready bot architecture.

Your task is to build a complete, functional Discord bot named ASCND Ticket & Vouch Bot from scratch.

Do not provide incomplete code, placeholders for core functionality, pseudocode, or isolated snippets. Deliver the complete project with every required file.

  1. Technology Requirements
  • Python 3.11 or newer.
  • "discord.py" 2.x.
  • SQLite for persistent storage.
  • Slash commands using Discord application commands.
  • Discord UI components, including buttons, select menus, and modals where appropriate.
  • An ".env" file for secrets and configuration.
  • UTF-8 encoding for every source file.
  • The bot must be runnable on Android using Termux, as well as on a normal computer.
  • Keep the project simple enough for a beginner to install and operate.
  1. Ticket System

Create a professional ticket system for the ASCND Discord server.

Ticket categories

Administrators must be able to create, list, and remove ticket categories.

Each category should support:

  • Category name.
  • Emoji.
  • Description.
  • Optional Discord support role ID.
  • Optional ticket category channel ID.

Slash commands

Implement these commands:

  • "/ticket setup" — configure the ticket system.
  • "/ticket panel" — publish the ticket creation panel.
  • "/ticket category_add" — add a ticket category.
  • "/ticket category_list" — list configured categories.
  • "/ticket category_remove" — remove a category.

Use proper Discord slash-command groups and register every group and command correctly.

Ticket creation

When a user selects a category:

  1. Create a private text channel for the ticket.
  2. Allow the ticket creator and authorized staff to view and send messages.
  3. Deny access to unauthorized users.
  4. Send an embed containing the category, ticket number, creator, and instructions.
  5. Include a close-ticket button.
  6. Store the ticket in SQLite.
  7. Handle permission errors and missing configuration gracefully.

Prevent users from opening unlimited duplicate tickets if a configurable limit is enabled.

Closing tickets

  • Only the ticket creator or authorized staff may close a ticket.
  • Ask for confirmation before closing.
  • Update the database status.
  • Prevent users from using an old ticket button incorrectly.
  • Optionally provide a transcript feature if it can be implemented reliably.
  • Ensure persistent buttons continue working after bot restarts.
  1. Vouch System

Implement a user review system for completed trades, commissions, and services.

Commands

  • "/vouch" — submit a vouch for another user after a completed transaction.
  • "/vouches" — view a user's vouch statistics and recent reviews.
  • "/vouchadmin setup" — configure the vouch system.

Vouch requirements

Each vouch should contain:

  • The reviewer.
  • The reviewed user.
  • A rating from 1 to 5.
  • An optional written comment.
  • A timestamp.
  • The related ticket ID, if applicable.

Rules:

  • Users cannot vouch for themselves.
  • Users cannot submit duplicate vouches for the same completed ticket.
  • Only eligible participants of a completed ticket may submit a ticket-linked vouch.
  • Validate all inputs.
  • Display the total number of vouches and average rating.
  • Use attractive Discord embeds.
  • Store all data persistently in SQLite.

If ticket-linked vouches are implemented, verify ticket participation and completion using the database rather than trusting user-provided IDs.

  1. Discord Commands and Permissions
  • Use "discord.app_commands" correctly.
  • Ensure slash commands actually appear in the Discord server.
  • Support an optional "GUILD_ID" environment variable for fast guild-specific command synchronization during development.
  • Synchronize commands only once using a clean, consistent strategy.
  • Do not register the same command group twice.
  • Restrict administrative commands to authorized administrators or configured staff.
  • Send ephemeral responses for private configuration feedback where appropriate.
  • Include useful error messages for missing permissions and invalid arguments.
  1. Database

Use SQLite with tables for:

  • Ticket categories.
  • Tickets.
  • Vouches.
  • Bot configuration.

Requirements:

  • Create tables automatically on startup.
  • Use parameterized SQL queries.
  • Persist data after restarts.
  • Enable appropriate foreign-key constraints.
  • Handle missing or outdated database schemas safely.
  • Do not delete existing user data when the bot restarts or updates.
  1. Configuration and Security

Use environment variables rather than hardcoding credentials.

Provide a ".env.example" file containing:

DISCORD_TOKEN=YOUR_BOT_TOKEN_HERE GUILD_ID=YOUR_DISCORD_SERVER_ID STAFF_ROLE_ID=YOUR_STAFF_ROLE_ID TICKET_CATEGORY_ID=YOUR_TICKET_CATEGORY_CHANNEL_ID VOUCH_CHANNEL_ID=YOUR_VOUCH_CHANNEL_ID

Optional IDs may be left empty when unused.

Security rules:

  • Never print the Discord token to the console.
  • Never include a real token in the source code.
  • Validate configuration on startup.
  • Explain which Discord Developer Portal intents and bot permissions are required.
  • Never expose credentials in error messages.
  • Include ".gitignore" entries for ".env", SQLite database files, virtual environments, and Python cache files.
  1. Error Handling and Reliability
  • Print clear startup messages.
  • Print a clear error if the token is missing or invalid.
  • Handle Discord API errors gracefully.
  • Handle database exceptions.
  • Avoid silently swallowing exceptions.
  • Make persistent views work after restarting the bot.
  • Ensure every required command is defined before command synchronization.
  • Ensure the main entry point actually starts the bot.
  • Use UTF-8-compatible source code and avoid malformed or replacement characters.
  • Avoid unnecessary dependencies.
  1. Required Project Files

Generate the complete project with this structure:

ASCND_Ticket_Vouch_Bot/ ├── bot.py ├── database.py ├── requirements.txt ├── .env.example ├── .gitignore └── README.md

You may use fewer files if that makes the project more reliable, but every required feature must still be implemented.

  1. Installation Instructions

The README must include beginner-friendly instructions for Android Termux:

  1. Install Python and required system packages.
  2. Navigate to the project folder.
  3. Install dependencies with "pip install -r requirements.txt".
  4. Create ".env" from ".env.example".
  5. Edit ".env" and enter the user's own Discord bot token and IDs.
  6. Enable the required bot settings in the Discord Developer Portal.
  7. Start the bot using "python bot.py".
  8. Troubleshoot missing slash commands, invalid tokens, missing permissions, and dependency errors.

Also provide instructions for Windows and macOS if practical.

  1. Final Validation

Before delivering the project:

  • Check every Python file for syntax errors.
  • Verify imports and function names.
  • Verify all slash commands and groups are registered correctly.
  • Verify database initialization.
  • Verify that the main entry point runs.
  • Verify that the project does not require hardcoded secrets.
  • Check that no feature is referenced but left unimplemented.
  • If you cannot run a real Discord integration test, explicitly state that limitation instead of claiming the bot was fully tested.

Final Deliverables

Provide:

  1. The complete project files.
  2. The full source code, not just an explanation.
  3. A ZIP archive if file generation is supported.
  4. Exact Android Termux installation and startup commands.
  5. A short checklist of Discord Developer Portal settings and required permissions.

Priority: A working, complete, beginner-friendly bot is more important than unnecessary complexity. Do not stop after generating a partial "bot.py". Deliver the entire implementation.

Kodari AI
KodariOct 23 at 11:59 pm 2
ASCNDTicketVouchBot
ASCND Ticket & Vouch Bot is a comprehensive Discord bot for the ASCND server, featuring a full ticket system and user review system. It allows administrators to create and manage ticket categories with custom emojis, descriptions, and support roles. Users can open private ticket channels, which are automatically created with proper permissions and close-ticket buttons. The vouch system enables users to rate completed transactions from 1-5 stars with optional comments, with strict validation preventing self-vouching and duplicate entries. The bot includes slash commands for ticket management, vouch submission, and configuration, all backed by a persistent SQLite database. It features persistent UI components that survive bot restarts, ephemeral responses for private feedback, and comprehensive error handling. The bot is designed to be beginner-friendly and runs on Android Termux, Windows, and macOS.
  1. Build the SQLite layer for persistent categories, tickets, configuration, and vouches.

  2. Implement the discord.py bot, slash-command groups, ticket UI, permission checks, and restart-safe views.

  3. Add environment templates, dependencies, ignore rules, and beginner-friendly setup instructions.

Created the complete project in ASCND_Ticket_Vouch_Bot/: the ticket and vouch bot, SQLite database layer, dependency list, environment template, .gitignore, and setup guide.

Android Termux startup

Shell
pkg update -y && pkg upgrade -y
pkg install python libsqlite -y
cd ~/ASCND_Ticket_Vouch_Bot
python -m pip install --upgrade pip
pip install -r requirements.txt
cp .env.example .env
nano .env
python bot.py

In .env, enter your own DISCORD_TOKEN; the server, staff-role, ticket-category, and vouch-channel IDs are optional.

Discord setup checklist: Invite the bot with the bot and applications.commands scopes. Grant View Channels, Send Messages, Read Message History, Embed Links, Attach Files, and Manage Channels. Privileged Gateway Intents are not required. After startup, configure categories and publish the panel with /ticket commands; configure vouch posting with /vouchadmin setup.

A ZIP archive was not generated. I could not run a live Discord integration test or an automated syntax check in this environment.

Kodari can make mistakes. Review important code before using.
Files
ASCND_Ticket_Vouch_Bot
Code
5 1,060
ASCND_Ticket_Vouch_Bot/bot.py
import logging
import os
import re
import sys

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

from database import Database


load_dotenv()
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("ascnd")


def read_optional_id(name: str) -> int | None:
    value = os.getenv(name, "").strip()
    if not value:
        return None
    try:
        return int(value)
    except ValueError:
        logger.warning("Ignoring invalid numeric value in %s.", name)
        return None


def stars(rating: int | float) -> str:
    rounded = int(round(rating))
    return "★" * rounded + "☆" * (5 - rounded)


class CategorySelect(discord.ui.Select):
    def __init__(self, categories: list[dict | object]) -> None:
        options = []
        for category in categories:
            description = category["description"][:100] if category["description"] else None
            option = discord.SelectOption(
                label=category["name"][:100],
                value=str(category["id"]),
                description=description,
            )
            if category["emoji"]:
                option.emoji = category["emoji"]
            options.append(option)
        super().__init__(
            placeholder="Choose the kind of help you need...",
            min_values=1,
            max_values=1,
            options=options,
            custom_id="ascnd:ticket:category",
        )

    async def callback(self, interaction: discord.Interaction) -> None:
        if interaction.guild is None:
            await interaction.response.send_message("Tickets can only be opened in a server.", ephemeral=True)
            return
        bot = interaction.client
        category = bot.db.get_category(interaction.guild.id, int(self.values[0]))
        if category is None:
            await interaction.response.send_message(
                "That ticket category is no longer available. Please use the current panel.", ephemeral=True
            )
            return
        await bot.open_ticket(interaction, category)


class TicketPanelView(discord.ui.View):
    def __init__(self, categories: list[dict | object]) -> None:
        super().__init__(timeout=None)
        self.add_item(CategorySelect(categories))


class TicketCloseView(discord.ui.View):
    def __init__(self, ticket_id: int, disabled: bool = False) -> None:
        super().__init__(timeout=None)
        self.ticket_id = ticket_id
        button = discord.ui.Button(
            label="Close ticket",
            style=discord.ButtonStyle.danger,
            emoji="🔒",
            custom_id=f"ascnd:ticket:close:{ticket_id}",
            disabled=disabled,
        )
        button.callback = self.close_callback
        self.add_item(button)

    async def close_callback(self, interaction: discord.Interaction) -> None:
        bot = interaction.client
        await bot.request_ticket_close(interaction, self.ticket_id, interaction.message)


class CloseConfirmationView(discord.ui.View):
    def __init__(self, ticket_id: int, requester_id: int, ticket_message: discord.Message | None) -> None:
        super().__init__(timeout=60)
        self.ticket_id = ticket_id
        self.requester_id = requester_id
        self.ticket_message = ticket_message

    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        if interaction.user.id != self.requester_id:
            await interaction.response.send_message("Only the person who requested this confirmation can use it.", ephemeral=True)
            return False
        return True

    @discord.ui.button(label="Confirm close", style=discord.ButtonStyle.danger)
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        bot = interaction.client
        await bot.confirm_ticket_close(interaction, self.ticket_id, self.ticket_message)

    @discord.ui.button(label="Cancel", style=discord.ButtonStyle.secondary)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        await interaction.response.edit_message(content="Ticket closure cancelled.", view=None)


class AscndBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
        self.db = Database()
        self.panel_views_loaded = False

    async def setup_hook(self) -> None:
        try:
            self.db.initialize()
            for ticket in self.db.list_tickets():
                self.add_view(TicketCloseView(int(ticket["id"]), disabled=ticket["status"] != "open"))
            guild_id = read_optional_id("GUILD_ID")
            if os.getenv("GUILD_ID", "").strip() and guild_id is None:
                raise RuntimeError("GUILD_ID must be a numeric Discord server ID.")
            if guild_id:
                guild = discord.Object(id=guild_id)
                self.tree.copy_global_to(guild=guild)
                await self.tree.sync(guild=guild)
                logger.info("Slash commands synchronized to development server %s.", guild_id)
            else:
                await self.tree.sync()
                logger.info("Global slash commands synchronized.")
        except Exception:
            logger.exception("Bot startup setup failed.")
            raise

    async def on_ready(self) -> None:
        if not self.panel_views_loaded:
            for guild in self.guilds:
                categories = self.db.list_categories(guild.id)
                panel_id = self.db.get_config(guild.id, "ticket_panel_message_id")
                if categories and panel_id:
                    self.add_view(TicketPanelView(categories), message_id=int(panel_id))
            self.panel_views_loaded = True
        logger.info("Connected as %s (%s).", self.user, self.user.id if self.user else "unknown")
        print("KODARI_READY", flush=True)

    def configured_id(self, guild_id: int, key: str, env_name: str) -> int | None:
        saved = self.db.get_config(guild_id, key)
        if saved:
            try:
                return int(saved)
            except ValueError:
                logger.error("Ignoring invalid saved %s for server %s.", key, guild_id)
        return read_optional_id(env_name)

    async def open_ticket(self, interaction: discord.Interaction, category: object) -> None:
        guild = interaction.guild
        creator = interaction.user
        if guild is None or not isinstance(creator, discord.Member):
            await interaction.response.send_message("Tickets can only be opened by server members.", ephemeral=True)
            return

        max_open_raw = self.db.get_config(guild.id, "max_open_tickets")
        try:
            max_open = int(max_open_raw) if max_open_raw is not None else 1
        except ValueError:
            max_open = 1
        if max_open > 0 and self.db.count_open_tickets(guild.id, creator.id) >= max_open:
            await interaction.response.send_message(
                f"You already have the maximum of {max_open} open ticket(s).", ephemeral=True
            )
            return

        category_role_id = int(category["support_role_id"]) if category["support_role_id"] else None
        staff_role_id = self.configured_id(guild.id, "staff_role_id", "STAFF_ROLE_ID")
        support_role_id = category_role_id or staff_role_id
        ticket_category_id = (
            int(category["discord_category_id"])
            if category["discord_category_id"]
            else self.configured_id(guild.id, "ticket_category_id", "TICKET_CATEGORY_ID")
        )
        support_role = guild.get_role(support_role_id) if support_role_id else None
        if support_role_id and support_role is None:
            await interaction.response.send_message(
                "The configured support role no longer exists. Ask an administrator to run `/ticket setup`.",
                ephemeral=True,
            )
            return
        channel_category = guild.get_channel(ticket_category_id) if ticket_category_id else None