rileywoods2026

Make me a ticket system

Kodari AI
KodariOct 28 at 10:08 pm 1
TicketSystem
A Discord bot that manages a ticket system for support and issue tracking. Users can create tickets with a title and description, view their open tickets, and close resolved ones. The bot supports multiple ticket categories, assigns ticket IDs, tracks status (open/in-progress/closed), and stores data persistently in a JSON file. Staff members can view all tickets, update statuses, and add responses. Includes commands for creating, listing, viewing, closing, and deleting tickets, with role-based permissions for moderation.
  1. Create a discord.py bot with persistent ticket buttons and slash commands.

  2. Add saved per-server setup, dependency list, and a .env token placeholder.

  3. Keep permissions least-privileged and include command error logging.

Created the ticket bot with persistent Open ticket and Close ticket buttons, plus /ticket setup, /ticket close, and /ticket add commands. Setup lets a server admin choose a ticket category and optionally a support role and log channel; settings are saved in config.json.

Add your bot token to .env, install dependencies from requirements.txt, and start bot.py. The bot uses default intents, so no privileged intents need to be enabled.

Kodari can make mistakes. Review important code before using.
Files
bot.py
config.json
requirements.txt
Code
3 349
bot.py
import json
import logging
import os
import re
from pathlib import Path

import discord
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",
)
logger = logging.getLogger("ticket_bot")
CONFIG_PATH = Path("config.json")


def read_config():
    if not CONFIG_PATH.exists():
        return {"guilds": {}}
    with CONFIG_PATH.open("r", encoding="utf-8") as config_file:
        data = json.load(config_file)
    if not isinstance(data, dict) or not isinstance(data.get("guilds"), dict):
        raise ValueError("config.json must contain a 'guilds' object")
    return data


def save_guild_settings(guild_id, settings):
    config = read_config()
    config["guilds"][str(guild_id)] = settings
    temporary_path = CONFIG_PATH.with_suffix(".json.tmp")
    with temporary_path.open("w", encoding="utf-8") as config_file:
        json.dump(config, config_file, indent=2)
    temporary_path.replace(CONFIG_PATH)


def get_guild_settings(guild_id):
    return read_config()["guilds"].get(str(guild_id))


def ticket_owner_id(channel):
    if not channel.topic:
        return None
    match = re.fullmatch(r"ticket-owner:(\d+)", channel.topic)
    return int(match.group(1)) if match else None


def can_manage_ticket(interaction, owner_id):
    if interaction.user.id == owner_id:
        return True
    if not isinstance(interaction.user, discord.Member):
        return False
    return interaction.user.guild_permissions.manage_channels or any(
        role.id == int(role_id)
        for role in interaction.user.roles
        for role_id in get_guild_settings(interaction.guild_id).get("support_role_ids", [])
    )


async def close_ticket(interaction, channel):
    owner_id = ticket_owner_id(channel)
    if owner_id is None:
        await interaction.response.send_message(
            "This command can only be used in a ticket channel.", ephemeral=True
        )
        return
    settings = get_guild_settings(interaction.guild_id) or {}
    if not can_manage_ticket(interaction, owner_id):
        await interaction.response.send_message(
            "Only the ticket owner or support staff can close this ticket.",
            ephemeral=True,
        )
        return

    await interaction.response.send_message("Closing this ticket…", ephemeral=True)
    log_channel_id = settings.get("log_channel_id")
    if log_channel_id:
        log_channel = interaction.guild.get_channel(log_channel_id)
        if isinstance(log_channel, discord.TextChannel):
            embed = discord.Embed(
                title="Ticket closed",
                description=f"{channel.mention} was closed by {interaction.user.mention}.",
                color=discord.Color.red(),
                timestamp=discord.utils.utcnow(),
            )
            embed.add_field(name="Ticket owner", value=f"<@{owner_id}>")
            await log_channel.send(embed=embed)
    await channel.delete(reason=f"Ticket closed by {interaction.user}")


class TicketPanelView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(
        label="Open a ticket",
        style=discord.ButtonStyle.primary,
        custom_id="ticket:open",
        emoji="🎫",
    )
    async def open_ticket(self, interaction: discord.Interaction, button: discord.ui.Button):
        guild = interaction.guild
        if guild is None:
            await interaction.response.send_message(
                "Tickets can only be opened in a server.", ephemeral=True
            )
            return

        settings = get_guild_settings(guild.id)
        if not settings:
            await interaction.response.send_message(
                "Tickets have not been set up yet. Ask a server administrator to run `/ticket setup`.",
                ephemeral=True,
            )
            return

        existing = next(
            (
                channel
                for channel in guild.text_channels
                if ticket_owner_id(channel) == interaction.user.id
            ),
            None,
        )
        if existing:
            await interaction.response.send_message(
                f"You already have an open ticket: {existing.mention}", ephemeral=True
            )
            return

        category = guild.get_channel(settings["category_id"])
        if not isinstance(category, discord.CategoryChannel):
            await interaction.response.send_message(
                "The configured ticket category no longer exists. Ask an administrator to run `/ticket setup` again.",
                ephemeral=True,
            )
            return

        safe_name = re.sub(r"[^a-z0-9-]+", "-", interaction.user.name.lower()).strip("-")
        safe_name = (safe_name or "user")[:40]
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(view_channel=False),
            interaction.user: discord.PermissionOverwrite(
                view_channel=True,
                send_messages=True,
                read_message_history=True,
                attach_files=True,
                embed_links=True,
            ),
        }
        bot_member = guild.me
        if bot_member:
            overwrites[bot_member] = discord.PermissionOverwrite(
                view_channel=True,
                send_messages=True,
                read_message_history=True,
                manage_channels=True,
            )

        support_role_ids = settings.get("support_role_ids", [])
        support_roles = []
        for role_id in support_role_ids:
            role = guild.get_role(role_id)
            if role:
                overwrites[role] = discord.PermissionOverwrite(
                    view_channel=True,
                    send_messages=True,
                    read_message_history=True,
                )
                support_roles.append(role)

        channel = await guild.create_text_channel(
            name=f"ticket-{safe_name}-{str(interaction.user.id)[-4:]}",
            category=category,
            topic=f"ticket-owner:{interaction.user.id}",
            overwrites=overwrites,
            reason=f"Ticket opened by {interaction.user}",
        )
        embed = discord.Embed(
            title="Support ticket",
            description=(
                f"Hello {interaction.user.mention}! Describe your issue here and a member of the team will help you.\n"
                "Use the button below when you are ready to close this ticket."
            ),
            color=discord.Color.blurple(),
        )
        content = " ".join(role.mention for role in support_roles) or None
        await channel.send(
            content=content,
            embed=embed,
            view=TicketCloseView(),
            allowed_mentions=discord.AllowedMentions(roles=True),
        )
        await interaction.response.send_message(
            f"Your ticket has been created: {channel.mention}", ephemeral=True
        )