overlordx26
๐Ÿ“Ž 1 file 16,434 chars
๐Ÿ“„
pasted-code-1776159320342.txt
txt 414 lines
โ–ถ
import discord
from discord.ext import commands
from discord.ui import View, Select, Button
import sqlite3
import asyncio
from datetime import datetime
import os

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.guilds = True
bot = commands.Bot(command_prefix='!', intents=intents)

conn = sqlite3.connect('ticket_data.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tickets (
    channel_id INTEGER PRIMARY KEY,
    user_id INTEGER,
    category TEXT,
    created_at TEXT,
    closed BOOLEAN,
    message_id INTEGER
)''')
conn.commit()

PANEL_CHANNEL_ID = 1491855378445500496
BUY_CATEGORY = 1492055985681072280
CLAIM_CATEGORY = 1492056379618365561
SUPPORT_CATEGORY = 1492056432927834122
LOG_CHANNEL = 1492149580505153676
SUPPORT_TEAM_ROLE = 1448967230019731477
STAFF_ROLE = 1492142509306941557

EMOJIS = {
    'ticket': '<:ticket:1491868067364475004>',
    'info': '',
    'star': '',
    'cash': '',
    'gift': '',
    'settings': '',
    'cross': '',
    'mcheart': '<:mcheart:1491868064478924852>',
    'timer': ''
}

active_timers = {}

class TicketSelect(Select):
    def __init__(self):
        options = [
            discord.SelectOption(label="Buy", description="Purchase hosting plans", emoji="๐Ÿ’ฐ", value="buy"),
            discord.SelectOption(label="Claim", description="Claim giveaways & rewards", emoji="๐ŸŽ", value="claim"),
            discord.SelectOption(label="Support", description="Technical support & billing", emoji="โš™๏ธ", value="support")
        ]
        super().__init__(placeholder="Select any Option from the Dropdown", options=options, custom_id="ticket_select")

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True)
        
        if self.values[0] == "buy":
            cat_id = BUY_CATEGORY
            cat_name = "Buy"
        elif self.values[0] == "claim":
            cat_id = CLAIM_CATEGORY
            cat_name = "Claim"
        else:
            cat_id = SUPPORT_CATEGORY
            cat_name = "Support"
        
        category = interaction.guild.get_channel(cat_id)
        
        overwrites = {
            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            interaction.user: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True, embed_links=True),
            interaction.guild.get_role(SUPPORT_TEAM_ROLE): discord.PermissionOverwrite(read_messages=True, send_messages=True)
        }
        
        if cat_name != "Buy":
            overwrites[interaction.guild.get_role(STAFF_ROLE)] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
        
        channel_name = f"{cat_name.lower()}-{interaction.user.name}"
        channel = await interaction.guild.create_text_channel(channel_name, category=category, overwrites=overwrites)
        
        now = datetime.now()
        time_opened = now.strftime("%I:%M %p, %B %d, %Y")
        
        embed = discord.Embed(
            title=f"Welcome {interaction.user.mention} to Veltrion Hosting",
            description=f"**Category:** {cat_name}\n**Time Opened:** {time_opened}\n\nOur Support team will assist you soon!",
            color=discord.Color.green(),
            timestamp=now
        )
        
        if cat_name == "Buy":
            await channel.send(f"<@&{SUPPORT_TEAM_ROLE}>")
        else:
            await channel.send(
                f"<@&{SUPPORT_TEAM_ROLE}> <@&{STAFF_ROLE}>"
            )
        await channel.send(embed=embed)
        
        view = TicketControl(channel.id, interaction.user.id, cat_name)
        control_msg = await channel.send("### Ticket Controls", view=view)
        
        c.execute("INSERT OR REPLACE INTO tickets VALUES (?, ?, ?, ?, ?, ?)",
                  (channel.id, interaction.user.id, cat_name, now.isoformat(), False, control_msg.id))
        conn.commit()
        
        log_channel = interaction.guild.get_channel(LOG_CHANNEL)
        if log_channel:
            log_embed = discord.Embed(
                title="๐Ÿ“ซ Ticket Created",
                description=f"**User:** {interaction.user.mention}\n**Category:** {cat_name}\n**Channel:** {channel.mention}\n**Time:** {time_opened}",
                color=discord.Color.green(),
                timestamp=now
            )
            await log_channel.send(embed=log_embed)
        
        await interaction.followup.send(f"{EMOJIS['ticket']} Ticket created! Check {channel.mention}", ephemeral=True)
        
        if cat_name in ["Claim", "Support"]:
            task = asyncio.create_task(check_support_response(channel))
            active_timers[channel.id] = task

class TicketControl(View):
    def __init__(self, channel_id, user_id, category):
        super().__init__(timeout=None)
        self.channel_id = channel_id
        self.user_id = user_id
        self.category = category
    
    @discord.ui.button(label="Close", style=discord.ButtonStyle.danger, custom_id="close_btn", emoji="๐Ÿ”’")
    async def close(self, interaction: discord.Interaction, button: Button):
        if not (interaction.user.guild_permissions.administrator or interaction.user.id == self.user_id):
            await interaction.response.send_message(f"{EMOJIS['cross']} You don't have permission!", ephemeral=True)
            return
        
        channel = interaction.guild.get_channel(self.channel_id)
        
        if self.category == "Buy":
            await channel.set_permissions(interaction.guild.get_member(self.user_id), overwrite=None)
        else:
            role = interaction.guild.get_role(STAFF_ROLE)
            member = interaction.guild.get_member(self.user_id)
            if member and role in member.roles:
                await member.remove_roles(role)
        
        if self.channel_id in active_timers:
            active_timers[self.channel_id].cancel()
            del active_timers[self.channel_id]
        
        c.execute("UPDATE tickets SET closed = 1 WHERE channel_id = ?", (self.channel_id,))
        conn.commit()
        
        await channel.edit(name=f"closed-{interaction.user.name}")
        
        embed = discord.Embed(
            title="Ticket Closed",
            description=f"The Ticket is closed by {interaction.user.mention}",
            color=discord.Color.red(),
            timestamp=datetime.now()
        )
        
        view = ReopenDelete(self.channel_id, self.user_id, self.category)
        await channel.send(embed=embed, view=view)
        
        # Disable the close button
        for child in self.children:
            child.disabled = True
        await interaction.response.edit_message(view=self)

class ReopenDelete(View):
    def __init__(self, channel_id, user_id, category):
        super().__init__(timeout=None)
        self.channel_id = channel_id
        self.user_id = user_id
        self.category = category

    @discord.ui.button(label="Reopen", style=discord.ButtonStyle.success, custom_id="reopen_btn", emoji="๐Ÿ”“")
    async def reopen(self, interaction: discord.Interaction, button: Button):
        if not (interaction.user.guild_permissions.administrator or interaction.user.id == self.user_id):
            await interaction.response.send_message(
                f"{EMOJIS['cross']} You don't have permission!",
                ephemeral=True
            )
            return

        channel = interaction.guild.get_channel(self.channel_id)
        member = interaction.guild.get_member(self.user_id)

        c.execute(
            "UPDATE tickets SET closed = 0 WHERE channel_id = ?",
            (self.channel_id,)
        )
        conn.commit()

        await channel.edit(name=f"{self.category.lower()}-{member.name}")

        embed = discord.Embed(
            title="Ticket Reopened",
            description=f"Ticket reopened by {interaction.user.mention}",
            color=discord.Color.green(),
            timestamp=datetime.now()
        )

        await channel.send(embed=embed)

        view = TicketControl(self.channel_id, self.user_id, self.category)
        msg = await channel.send("### Ticket Controls", view=view)

        c.execute(
            "UPDATE tickets SET message_id = ? WHERE channel_id = ?",
            (msg.id, self.channel_id)
        )
        conn.commit()

        await interaction.response.send_message(
            "Ticket reopened!",
            ephemeral=True
        )

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.danger, custom_id="delete_btn", emoji="๐Ÿ—‘๏ธ")
    async def delete(self, interaction: discord.Interaction, button: Button):
        if not interaction.user.guild_permissions.administrator:
            await interaction.response.send_message(
                f"{EMOJIS['cross']} Only administrators can delete tickets!",
                ephemeral=True
            )
            return

        channel = interaction.guild.get_channel(self.channel_id)

        transcript_path = f"transcript_{channel.id}.html"

        html_content = """


    Ticket Transcript


Veltrion Ticket Transcript

""" async for msg in channel.history(limit=None, oldest_first=True): html_content += f"""

[{msg.created_at}] {msg.author}: {msg.content}

""" html_content += "" with open(transcript_path, "w", encoding="utf-8") as f: f.write(html_content) log_channel = interaction.guild.get_channel(LOG_CHANNEL) embed = discord.Embed( title="๐Ÿ—‘๏ธ Ticket Deleted", description=f"Ticket #{channel.name} has been deleted", color=discord.Color.red(), timestamp=datetime.now() ) with open(transcript_path, "rb") as f: file = discord.File( f, filename=f"transcript_{channel.name}.html" ) await log_channel.send(embed=embed, file=file) await interaction.response.send_message( "๐Ÿ—‘๏ธ Deleting ticket...", ephemeral=True ) c.execute( "DELETE FROM tickets WHERE channel_id = ?", (self.channel_id,) ) conn.commit() await channel.delete() if os.path.exists(transcript_path): os.remove(transcript_path) await interaction.response.send_message("Ticket deleted!", ephemeral=True) async def check_support_response(channel): await asyncio.sleep(1800) c.execute("SELECT closed FROM tickets WHERE channel_id = ?", (channel.id,)) result = c.fetchone() if result and not result[0]: responded = False async for msg in channel.history(limit=100): if msg.author.id == bot.user.id: continue for role in msg.author.roles: if role.id in [SUPPORT_TEAM_ROLE, STAFF_ROLE]: responded = True break if responded: break if not responded: embed = discord.Embed( title="Support Team Currently Unavailable", description=f"{EMOJIS['timer']} **It has been 30 minutes since your ticket was opened and our support team has not replied yet.**\n\nPlease do not worry โ€” your ticket is still in queue and will be handled as soon as possible.\n\n{EMOJIS['cross']} Please do not create multiple tickets for the same issue, as this may delay response times.", color=discord.Color.orange(), timestamp=datetime.now() ) await channel.send(embed=embed) @bot.event async def on_ready(): print(f'{bot.user} is online!') print(f'Bot is ready to use!') await bot.change_presence( status=discord.Status.dnd, activity=discord.Streaming(name="Veltrion Hosting", url="https://twitch.tv/veltrion") ) # Register persistent views bot.add_view(TicketControl(0, 0, "Buy")) bot.add_view(ReopenDelete(0, 0, "Buy")) # Restore existing tickets c.execute("SELECT channel_id, user_id, category, message_id FROM tickets WHERE closed = 0") tickets = c.fetchall() for ch_id, u_id, cat, msg_id in tickets: channel = bot.get_channel(ch_id) if channel: try: msg = await channel.fetch_message(msg_id) # Check if message still has the view if not msg.components: view = TicketControl(ch_id, u_id, cat) await msg.edit(view=view) print(f"Restored ticket: {channel.name}") except: view = TicketControl(ch_id, u_id, cat) msg = await channel.send("### Ticket Controls", view=view) c.execute("UPDATE tickets SET message_id = ? WHERE channel_id = ?", (msg.id, ch_id)) conn.commit() print(f"Created new controls for: {channel.name}") # Create panel panel_channel = bot.get_channel(PANEL_CHANNEL_ID) if panel_channel: async for msg in panel_channel.history(limit=50): if msg.author == bot.user: await msg.delete() embed = discord.Embed( title="Veltrion Hosting Ticket System", description=f"{EMOJIS['ticket']} If you need any assistance, please choose the appropriate option from the dropdown menu below to open your ticket.\n\n{EMOJIS['info']} Before opening a ticket, please make sure to read our Rules, Terms of Service, Refund Policy, FAQ, and Status updates for faster assistance.\n\n**{EMOJIS['star']} Please be patient โ€” our staff team will assist you as soon as possible.**\n\n{EMOJIS['cash']} **Buy โ†’** Open a ticket for purchasing any hosting plan or custom service.\n{EMOJIS['gift']} **Claim โ†’** Open a ticket for claiming giveaways, offers, rewards, or service claims.\n{EMOJIS['settings']} **Support โ†’** Open a ticket for technical support, billing help, or issue resolution.\n\n{EMOJIS['cross']} Please do not open multiple tickets for the same issue.\n\n{EMOJIS['mcheart']} Thank you for choosing Veltrion Hosting! We truly appreciate your support.", color=discord.Color.blue() ) view = View(timeout=None) view.add_item(TicketSelect()) await panel_channel.send(embed=embed, view=view) print("โœ… Ticket panel created!") @bot.command(name='ticket') async def ticket_cmd(ctx, action=None, user: discord.Member = None, *, name=None): if not ctx.author.guild_permissions.administrator: await ctx.send(f"{EMOJIS['cross']} You don't have permission!") return if action == "add" and user: await ctx.channel.set_permissions(user, read_messages=True, send_messages=True) await ctx.send(f"โœ… Added {user.mention}") elif action == "remove" and user: await ctx.channel.set_permissions(user, overwrite=None) await ctx.send(f"โœ… Removed {user.mention}") elif action == "rename" and name: await ctx.channel.edit(name=name) await ctx.send(f"โœ… Renamed to {name}") else: await ctx.send("**Commands:**\n`!ticket add @user`\n`!ticket remove @user`\n`!ticket rename name`") @bot.command(name='close') async def close_ticket_cmd(ctx): c.execute("SELECT user_id, category FROM tickets WHERE channel_id = ?", (ctx.channel.id,)) data = c.fetchone() if not data: await ctx.send("โŒ This is not a ticket channel.") return user_id, category = data view = TicketControl(ctx.channel.id, user_id, category) fake_interaction = None await ctx.channel.send("๐Ÿ”’ Closing ticket...") c.execute("UPDATE tickets SET closed = 1 WHERE channel_id = ?", (ctx.channel.id,)) conn.commit() await ctx.channel.edit(name=f"closed-{ctx.channel.name}") embed = discord.Embed( title="Ticket Closed", description=f"Closed by {ctx.author.mention}", color=discord.Color.red() ) await ctx.channel.send(embed=embed, view=ReopenDelete(ctx.channel.id, user_id, category)) bot.run("")
Kodari AI
KodariApr 14 at 9:36 am 9,095 (v2)

Iโ€™ll create a professional Discord ticket management bot based on the provided code.

DiscordTicketBot
An advanced Discord ticket management system for hosting companies and support teams. Features include multi-category tickets (Buy, Claim, Support), automatic response monitoring with 30-minute alerts, ticket closing/reopening controls, HTML transcript generation, dynamic permission management, persistent SQLite storage, and comprehensive admin commands. Includes staff role integration and customizable embeds with animated emojis.

โœ… Created DiscordTicketBot - A complete ticket management system with persistent storage, role-based permissions, automated support monitoring, HTML transcripts, and admin controls. Configure your channel/role IDs in config.py and add your bot token to .env before running.

Kodari can make mistakes. Review important code before using.
Files
bot.py
config.py
requirements.txt
Code
3 393
bot.py
import discord
from discord.ext import commands
from discord.ui import View, Select, Button
import sqlite3
import asyncio
from datetime import datetime
import os
from dotenv import load_dotenv
from config import *

load_dotenv()

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.guilds = True
bot = commands.Bot(command_prefix='!', intents=intents)

conn = sqlite3.connect('ticket_data.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tickets (
    channel_id INTEGER PRIMARY KEY,
    user_id INTEGER,
    category TEXT,
    created_at TEXT,
    closed BOOLEAN,
    message_id INTEGER
)''')
conn.commit()

active_timers = {}

class TicketSelect(Select):
    def __init__(self):
        options = [
            discord.SelectOption(label="Buy", description="Purchase hosting plans", emoji="๐Ÿ’ฐ", value="buy"),
            discord.SelectOption(label="Claim", description="Claim giveaways & rewards", emoji="๐ŸŽ", value="claim"),
            discord.SelectOption(label="Support", description="Technical support & billing", emoji="โš™๏ธ", value="support")
        ]
        super().__init__(placeholder="Select any Option from the Dropdown", options=options, custom_id="ticket_select")

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.defer(ephemeral=True)
        
        if self.values[0] == "buy":
            cat_id = BUY_CATEGORY
            cat_name = "Buy"
        elif self.values[0] == "claim":
            cat_id = CLAIM_CATEGORY
            cat_name = "Claim"
        else:
            cat_id = SUPPORT_CATEGORY
            cat_name = "Support"
        
        category = interaction.guild.get_channel(cat_id)
        
        overwrites = {
            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            interaction.user: discord.PermissionOverwrite(read_messages=True, send_messages=True, attach_files=True, embed_links=True),
            interaction.guild.get_role(SUPPORT_TEAM_ROLE): discord.PermissionOverwrite(read_messages=True, send_messages=True)
        }
        
        if cat_name != "Buy":
            overwrites[interaction.guild.get_role(STAFF_ROLE)] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
        
        channel_name = f"{cat_name.lower()}-{interaction.user.name}"
        channel = await interaction.guild.create_text_channel(channel_name, category=category, overwrites=overwrites)
        
        now = datetime.now()
        time_opened = now.strftime("%I:%M %p, %B %d, %Y")
        
        embed = discord.Embed(
            title=f"Welcome {interaction.user.mention} to Veltrion Hosting",
            description=f"**Category:** {cat_name}\n**Time Opened:** {time_opened}\n\nOur Support team will assist you soon!",
            color=discord.Color.green(),
            timestamp=now
        )
        
        if cat_name == "Buy":
            await channel.send(f"<@&{SUPPORT_TEAM_ROLE}>")
        else:
            await channel.send(f"<@&{SUPPORT_TEAM_ROLE}> <@&{STAFF_ROLE}>")
        await channel.send(embed=embed)
        
        view = TicketControl(channel.id, interaction.user.id, cat_name)
        control_msg = await channel.send("### Ticket Controls", view=view)
        
        c.execute("INSERT OR REPLACE INTO tickets VALUES (?, ?, ?, ?, ?, ?)",
                  (channel.id, interaction.user.id, cat_name, now.isoformat(), False, control_msg.id))
        conn.commit()
        
        log_channel = interaction.guild.get_channel(LOG_CHANNEL)
        if log_channel:
            log_embed = discord.Embed(
                title="๐Ÿ“ซ Ticket Created",
                description=f"**User:** {interaction.user.mention}\n**Category:** {cat_name}\n**Channel:** {channel.mention}\n**Time:** {time_opened}",
                color=discord.Color.green(),
                timestamp=now
            )
            await log_channel.send(embed=log_embed)
        
        await interaction.followup.send(f"{EMOJIS['ticket']} Ticket created! Check {channel.mention}", ephemeral=True)
        
        if cat_name in ["Claim", "Support"]:
            task = asyncio.create_task(check_support_response(channel))
            active_timers[channel.id] = task

class TicketControl(View):
    def __init__(self, channel_id, user_id, category):
        super().__init__(timeout=None)
        self.channel_id = channel_id
        self.user_id = user_id
        self.category = category
    
    @discord.ui.button(label="Close", style=discord.ButtonStyle.danger, custom_id="close_btn", emoji="๐Ÿ”’")
    async def close(self, interaction: discord.Interaction, button: Button):
        if not (interaction.user.guild_permissions.administrator or interaction.user.id == self.user_id):
            await interaction.response.send_message(f"{EMOJIS['cross']} You don't have permission!", ephemeral=True)
            return
        
        channel = interaction.guild.get_channel(self.channel_id)
        
        if self.category == "Buy":
            await channel.set_permissions(interaction.guild.get_member(self.user_id), overwrite=None)
        else:
            role = interaction.guild.get_role(STAFF_ROLE)
            member = interaction.guild.get_member(self.user_id)
            if member and role in member.roles:
                await member.remove_roles(role)
        
        if self.channel_id in active_timers:
            active_timers[self.channel_id].cancel()
            del active_timers[self.channel_id]
        
        c.execute("UPDATE tickets SET closed = 1 WHERE channel_id = ?", (self.channel_id,))
        conn.commit()
        
        await channel.edit(name=f"closed-{interaction.user.name}")
        
        embed = discord.Embed(
            title="Ticket Closed",
            description=f"The Ticket is closed by {interaction.user.mention}",
            color=discord.Color.red(),
            timestamp=datetime.now()
        )
        
        view = ReopenDelete(self.channel_id, self.user_id, self.category)
        await channel.send(embed=embed, view=view)
        
        for child in self.children:
            child.disabled = True
        await interaction.response.edit_message(view=self)

class ReopenDelete(View):
    def __init__(self, channel_id, user_id, category):
        super().__init__(timeout=None)
        self.channel_id = channel_id
        self.user_id = user_id
        self.category = category

    @discord.ui.button(label="Reopen", style=discord.ButtonStyle.success, custom_id="reopen_btn", emoji="๐Ÿ”“")
    async def reopen(self, interaction: discord.Interaction, button: Button):
        if not (interaction.user.guild_permissions.administrator or interaction.user.id == self.user_id):
            await interaction.response.send_message(f"{EMOJIS['cross']} You don't have permission!", ephemeral=True)
            return

        channel = interaction.guild.get_channel(self.channel_id)
        member = interaction.guild.get_member(self.user_id)

        c.execute("UPDATE tickets SET closed = 0 WHERE channel_id = ?", (self.channel_id,))
        conn.commit()

        await channel.edit(name=f"{self.category.lower()}-{member.name}")

        embed = discord.Embed(
            title="Ticket Reopened",
            description=f"Ticket reopened by {interaction.user.mention}",
            color=discord.Color.green(),
            timestamp=datetime.now()
        )

        await channel.send(embed=embed)

        view = TicketControl(self.channel_id, self.user_id, self.category)
        msg = await channel.send("### Ticket Controls", view=view)

        c.execute("UPDATE tickets SET message_id = ? WHERE channel_id = ?", (msg.id, self.channel_id))
        conn.commit()

        await interaction.response.send_message("Ticket reopened!", ephemeral=True)

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.danger, custom_id="delete_btn", emoji="๐Ÿ—‘๏ธ")
    async def delete(self, interaction: discord.Interaction, button: Button):
        if not interaction.user.guild_permissions.administrator:
            await interaction.response.send_message(f"{EMOJIS['cross']} Only administrators can delete tickets!", ephemeral=True)
            return

        channel = interaction.guild.get_channel(self.channel_id)
        transcript_path = f"transcript_{channel.id}.html"