void.mads

can you build a ticket bot? i need 3 interactive buttons, 1 to make a ticket for mads <@661350347050057739> , 1 to make a ticket for cam <@424726066108825600> , and 1 to make a ticket for krynn <@996627646320480276> , it should have a quick setup command, please. I need the panel to say "welcome! make a ticket with one of our devs! 𓏲ּ𝄢" i need to be able to have logs go to my log channel here https://discord.com/channels/771548111843360770/1524175092970684427 and after the ticket closes i need to be able to press 2 buttons, one that says "payment received" and one that says "payment not recieved" and i need it to get logged here https://discord.com/channels/771548111843360770/1537923183468879956 saying @user : $25 or @user: payment not received

Kodari AI
KodariSep 13 at 11:20 pm 2
DevTicketBot
A Discord ticket bot with a quick setup command that creates an interactive panel saying &quot;welcome! make a ticket with one of our devs! 𓏲ּ𝄢&quot; with three buttons to open tickets for mads, cam, and krynn. Each ticket opens a private thread with the user and the assigned dev. When a ticket closes, two buttons appear: &quot;payment received&quot; and &quot;payment not received&quot;. Pressing payment received logs &quot;@user : $25&quot; to the payment log channel, while payment not received logs &quot;@user: payment not received&quot; to the same channel. All ticket activity is logged to a designated log channel. The bot uses Discord's thread and button features for a streamlined support workflow.
  1. Create a persistent discord.py ticket bot with three developer buttons and private ticket channels.

  2. Add /ticketsetup to publish the requested panel and configure the supplied log channels automatically.

  3. Add close, payment-status buttons, transcript logging, permissions, and environment-based configuration.

Built the Discord ticket bot project with:

  • Three interactive developer buttons: Mads, Cam, and Krynn

  • /ticketsetup command for quick panel setup

  • Private ticket channels under an automatically created Tickets category

  • Close-ticket button with permission checks

  • Payment buttons:

    • payment received

    • payment not recieved

  • Ticket transcript logging to channel 1524175092970684427

  • Payment logging to channel 1537923183468879956

  • Persistent ticket state in data/tickets.json

  • .env.example, requirements.txt, .gitignore, and setup README

Copy .env.example to .env, add the bot token, install dependencies, and run:

Shell
pip install -r requirements.txt
python bot.py

Then run /ticketsetup in the desired panel channel.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 694
bot.py
from __future__ import annotations

import io
import json
import logging
import os
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional

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


def env_int(name: str, default: int = 0) -> int:
    value = os.getenv(name, "").strip()
    if not value:
        return default
    try:
        return int(value)
    except ValueError:
        logger.warning("Ignoring invalid integer in %s", name)
        return default


DEFAULT_GUILD_ID = 771548111843360770
DEFAULT_TICKET_LOG_CHANNEL_ID = 1524175092970684427
DEFAULT_PAYMENT_LOG_CHANNEL_ID = 1537923183468879956

GUILD_ID = env_int("GUILD_ID", DEFAULT_GUILD_ID)
TICKET_LOG_CHANNEL_ID = env_int(
    "TICKET_LOG_CHANNEL_ID", DEFAULT_TICKET_LOG_CHANNEL_ID
)
PAYMENT_LOG_CHANNEL_ID = env_int(
    "PAYMENT_LOG_CHANNEL_ID", DEFAULT_PAYMENT_LOG_CHANNEL_ID
)

PANEL_TEXT = "welcome! make a ticket with one of our devs! 𓏲ּ𝄢"

DEVELOPERS: dict[str, dict[str, Any]] = {
    "mads": {"name": "Mads", "id": 661350347050057739},
    "cam": {"name": "Cam", "id": 424726066108825600},
    "krynn": {"name": "Krynn", "id": 996627646320480276},
}


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


class TicketStore:
    def __init__(self, path: Path = Path("data/tickets.json")) -> None:
        self.path = path
        self.data: dict[str, Any] = {"configs": {}, "tickets": {}}
        self._load()

    def _load(self) -> None:
        try:
            loaded = json.loads(self.path.read_text(encoding="utf-8"))
            if isinstance(loaded, dict):
                self.data.update(loaded)
        except FileNotFoundError:
            return
        except (OSError, json.JSONDecodeError):
            logger.warning("Could not read %s; starting with empty storage", self.path)

        if not isinstance(self.data.get("configs"), dict):
            self.data["configs"] = {}
        if not isinstance(self.data.get("tickets"), dict):
            self.data["tickets"] = {}

    def save(self) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.path.write_text(json.dumps(self.data, indent=2), encoding="utf-8")

    def get_config(self, guild_id: int) -> dict[str, Any]:
        return self.data["configs"].setdefault(str(guild_id), {})

    def update_config(self, guild_id: int, values: dict[str, Any]) -> None:
        self.get_config(guild_id).update(values)
        self.save()

    def get_ticket(self, channel_id: int) -> Optional[dict[str, Any]]:
        return self.data["tickets"].get(str(channel_id))

    def create_ticket(self, ticket: dict[str, Any]) -> None:
        self.data["tickets"][str(ticket["channel_id"])] = ticket
        self.save()

    def update_ticket(self, channel_id: int, values: dict[str, Any]) -> None:
        ticket = self.get_ticket(channel_id)
        if ticket is not None:
            ticket.update(values)
            self.save()

    def remove_ticket(self, channel_id: int) -> None:
        self.data["tickets"].pop(str(channel_id), None)
        self.save()

    def find_open_ticket(
        self, guild_id: int, user_id: int, developer_id: int
    ) -> Optional[dict[str, Any]]:
        for ticket in self.data["tickets"].values():
            if (
                ticket.get("guild_id") == guild_id
                and ticket.get("user_id") == user_id
                and ticket.get("developer_id") == developer_id
                and ticket.get("status") == "open"
            ):
                return ticket
        return None


store = TicketStore()


async def resolve_text_channel(
    guild: discord.Guild, channel_id: int
) -> Optional[discord.TextChannel]:
    channel = guild.get_channel(channel_id)
    if channel is None:
        try:
            channel = await guild.fetch_channel(channel_id)
        except (discord.NotFound, discord.Forbidden, discord.HTTPException):
            return None
    if isinstance(channel, discord.TextChannel):
        return channel
    return None


async def resolve_member(guild: discord.Guild, member_id: int) -> Optional[discord.Member]:
    member = guild.get_member(member_id)
    if member is not None:
        return member
    try:
        return await guild.fetch_member(member_id)
    except (discord.NotFound, discord.Forbidden, discord.HTTPException):
        return None


async def send_log(
    guild: discord.Guild,
    channel_id: int,
    embed: discord.Embed,
    file: Optional[discord.File] = None,
) -> bool:
    channel = await resolve_text_channel(guild, channel_id)
    if channel is None:
        logger.warning("Log channel %s is unavailable in guild %s", channel_id, guild.id)
        return False
    try:
        await channel.send(embed=embed, file=file)
        return True
    except (discord.Forbidden, discord.HTTPException):
        logger.exception("Could not send a log to channel %s", channel_id)
        return False


def safe_channel_name(developer_key: str, user: discord.Member) -> str:
    username = re.sub(r"[^a-z0-9-]", "", user.name.lower().replace(" ", "-"))
    username = username[:45] or "user"
    return f"ticket-{developer_key}-{username}"[:100]


async def make_transcript(channel: discord.TextChannel) -> str:
    lines: list[str] = []
    try:
        async for message in channel.history(limit=200, oldest_first=True):
            timestamp = message.created_at.strftime("%Y-%m-%d %H:%M UTC")
            content = message.content or "[no text]"
            if message.attachments:
                content += " | attachments: " + ", ".join(
                    attachment.url for attachment in message.attachments
                )
            lines.append(f"[{timestamp}] {message.author} ({message.author.id}): {content}")
    except (discord.Forbidden, discord.HTTPException):
        lines.append("Transcript could not be fetched because Discord denied history access.")

    transcript = "\n".join(lines) or "No messages were found."
    encoded = transcript.encode("utf-8")
    if len(encoded) > 7_500_000:
        transcript = encoded[:7_500_000].decode("utf-8", errors="ignore")
        transcript += "\n[Transcript truncated]"
    return transcript


def is_ticket_staff(interaction: discord.Interaction, ticket: dict[str, Any]) -> bool:
    if interaction.user.id == ticket.get("user_id"):