stunnaempire._

TICKET BOT /REOPEN /TICKET PANEL /CLOSE

Kodari AI
KodariSep 25 at 1:43 am 1
TicketManager
A Discord ticket system bot built with discord.py. Features slash commands for creating ticket panels, opening tickets via button interactions, closing tickets with optional reason, and reopening closed tickets. Includes automatic channel creation, permission management, ticket transcripts saved to files, and an admin-only panel setup command. Supports multiple ticket categories and configurable support roles.
  1. Create a discord.py bot with /ticket panel, /close, and /reopen.

  2. Add private ticket channels, persistent panel buttons, and owner/support permissions.

  3. Add environment-based configuration and dependencies.

Created the discord.py ticket bot with /ticket panel, /close, and /reopen. Ticket channels are private to their creator and configured support role; panel buttons persist across restarts.

Install dependencies from requirements.txt, copy .env.example to .env, set DISCORD_TOKEN and optional role/category IDs, then run python bot.py. The bot needs permission to manage channels and send messages.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 269
bot.py
import logging
import os

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

TOKEN = os.getenv("DISCORD_TOKEN")
SUPPORT_ROLE_ID = int(os.getenv("SUPPORT_ROLE_ID", "0"))
TICKET_CATEGORY_ID = int(os.getenv("TICKET_CATEGORY_ID", "0"))


def ticket_topic(owner_id: int, status: str) -> str:
    return f"ticket-owner:{owner_id};status:{status}"


def ticket_details(channel: discord.abc.GuildChannel) -> tuple[int, str] | None:
    topic = getattr(channel, "topic", None) or ""
    values = dict(part.split(":", 1) for part in topic.split(";") if ":" in part)
    try:
        return int(values["ticket-owner"]), values["status"]
    except (KeyError, ValueError):
        return None


def is_support_or_admin(member: discord.Member) -> bool:
    if member.guild_permissions.manage_channels or member.guild_permissions.administrator:
        return True
    return bool(SUPPORT_ROLE_ID and any(role.id == SUPPORT_ROLE_ID for role in member.roles))


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

    @discord.ui.button(
        label="Create a ticket",
        style=discord.ButtonStyle.primary,
        emoji="🎫",
        custom_id="tickets:create",
    )
    async def create_ticket(
        self, interaction: discord.Interaction, button: discord.ui.Button
    ) -> None:
        if interaction.guild is None or not isinstance(interaction.user, discord.Member):
            await interaction.response.send_message(
                "Tickets can only be created in a server.", ephemeral=True
            )
            return

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

        category = guild.get_channel(TICKET_CATEGORY_ID) if TICKET_CATEGORY_ID else None
        if category is not None and not isinstance(category, discord.CategoryChannel):
            category = None

        overwrites: dict[discord.Role | discord.Member, discord.PermissionOverwrite] = {
            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,
            ),
        }
        support_role = guild.get_role(SUPPORT_ROLE_ID) if SUPPORT_ROLE_ID else None
        if support_role is not None:
            overwrites[support_role] = discord.PermissionOverwrite(
                view_channel=True,
                send_messages=True,
                read_message_history=True,
            )

        channel_name = f"ticket-{interaction.user.name}".lower()
        channel_name = "".join(
            char if char.isalnum() or char == "-" else "-" for char in channel_name
        ).strip("-")[:90]
        await interaction.response.defer(ephemeral=True, thinking=True)
        try:
            ticket_channel = await guild.create_text_channel(
                name=channel_name or f"ticket-{interaction.user.id}",
                category=category,
                overwrites=overwrites,
                topic=ticket_topic(interaction.user.id, "open"),
                reason=f"Ticket opened by {interaction.user} ({interaction.user.id})",
            )
            support_mention = support_role.mention if support_role else "Support team"
            await ticket_channel.send(
                f"{interaction.user.mention} {support_mention} — describe your issue here. "
                "A team member will be with you shortly. Use `/close` when your ticket is resolved."
            )
            await interaction.followup.send(
                f"Your ticket is ready: {ticket_channel.mention}", ephemeral=True
            )
        except discord.Forbidden:
            await interaction.followup.send(
                "I don't have permission to create ticket channels. Check my Manage Channels permission.",
                ephemeral=True,
            )
        except discord.HTTPException:
            logger.exception("Failed to create a ticket for user %s", interaction.user.id)
            await interaction.followup.send(
                "I couldn't create your ticket. Please try again later.", ephemeral=True
            )


class TicketBot(commands.Bot):
    async def setup_hook(self) -> None:
        self.add_view(TicketPanelView())
        await self.tree.sync()
        logger.info("Synced application commands")


intents = discord.Intents.default()
bot = TicketBot(command_prefix="!", intents=intents)


@bot.event
async def on_ready() -> None:
    logger.info("Logged in as %s (%s)", bot.user, bot.user.id if bot.user else "unknown")


class TicketCommands(app_commands.Group):
    def __init__(self) -> None:
        super().__init__(name="ticket", description="Ticket panel commands")

    @app_commands.command(name="panel", description="Post the ticket creation panel")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def panel(self, interaction: discord.Interaction) -> None:
        if interaction.channel is None:
            await interaction.response.send_message(
                "This command must be used in a server channel.", ephemeral=True
            )
            return
        embed = discord.Embed(
            title="Need help?",
            description="Click the button below to open a private support ticket.",
            color=discord.Color.blurple(),
        )
        await interaction.channel.send(embed=embed, view=TicketPanelView())
        await interaction.response.send_message("Ticket panel posted.", ephemeral=True)


bot.tree.add_command(TicketCommands())


async def update_ticket_status(
    interaction: discord.Interaction, new_status: str
) -> None:
    channel = interaction.channel
    member = interaction.user
    if not isinstance(channel, discord.TextChannel) or not isinstance(member, discord.Member):
        await interaction.response.send_message(
            "This command must be used in a ticket channel.", ephemeral=True
        )
        return

    details = ticket_details(channel)
    if details is None:
        await interaction.response.send_message(
            "This channel isn't a ticket.", ephemeral=True
        )
        return

    owner_id, status = details
    if member.id != owner_id and not is_support_or_admin(member):
        await interaction.response.send_message(
            "Only the ticket owner or support team can do that.", ephemeral=True
        )
        return
    if status == new_status:
        await interaction.response.send_message(
            f"This ticket is already {new_status}.", ephemeral=True
        )
        return