Melvin

make a discord bot where i have a ticket system and i can choose from Order , Support , and also in that same bot make a command where i can log sells if someonne sells something u can do /Logdesign ,amount , user , photo, note

Kodari AI
KodariNov 6 at 6:37 pm 2
TicketSalesBot
A Discord bot featuring a ticket system with Order and Support categories, plus a sales logging command. Users open tickets via buttons or commands, selecting their desired category. The /logdesign command records sales transactions with fields for design name, amount, user, photo attachment, and optional note. Logged sales are stored and can be reviewed, providing an organized sales tracking solution within Discord.
  1. Add a persistent ticket panel with Order and Support buttons.

  2. Add /logdesign with an amount, user, photo, and optional note.

  3. Add setup commands for the ticket staff role and sales log channel.

Created the ticket and sales bot.

  • Set DISCORD_TOKEN in .env.

  • Run /ticket_setup to choose the staff role, then /ticket_panel to post the Order and Support buttons.

  • Run /sales_setup to choose a log channel. Staff can then use /logdesign with the amount, seller, photo, and optional note.

Give the bot permission to manage channels and send messages.

Melvin

Design Log Command /logdesign (similar to Dynamix)

  • Amount
  • Customer
  • Photo
  • Note

The bot must display who logged the design.

Partner Log Command /logpartner

  • Server name
  • Server link
  • Members

The bot must display who logged the partnership.

Partner Send Command /partnersend

Description: Sends a partnership announcement to the designated partner channel.

The command must allow you to paste the entire partnership message, which will then be automatically sent to the correct partner channel.

Kodari AI
KodariNov 6 at 6:49 pm 2
  1. Update /logdesign to record the customer and display who logged it.

  2. Add /logpartner with the server details and logger.

  3. Add /partnersend and a way to designate its announcement channel.

  • /logdesign now records the customer and shows who logged the sale.

  • /logpartner records the server name, link, member count, and logger. Set its channel with /partner_log_setup.

  • /partnersend posts a pasted announcement to the channel set with /partner_channel_setup. Announcements can be up to 2,000 characters; mentions won’t ping.

Ticket staff and server managers can use these commands.

Melvin

also do /loarequest ,reoson ,begin date , end date . and then Higher staff can see the loa request and can accept them or deny them , when its accepted or denied they get a dm from the bot

Kodari AI
KodariNov 6 at 8:21 pm 2
  • Add /loarequest with a reason and date range.

  • Add a higher-staff review channel and role, with persistent Accept and Deny buttons.

  • DM the requester when a decision is made.

Added /loarequest with a reason, begin date, and end date. Higher staff can accept or deny requests, and the bot will DM the requester with the decision.

Use /loa_setup to choose the review channel and higher-staff role. Make the channel private to higher staff. Dates must use YYYY-MM-DD.

Melvin

with the Loa request the begin date and end date change it to something where i can type manually and not the date

Kodari AI
KodariNov 8 at 8:11 pm 1

/loarequest now accepts manually typed begin and end dates in any format, such as “next Monday” or “until further notice.”

Melvin

also it can be under 10 characters

Kodari AI
KodariNov 8 at 8:15 pm 1

The LOA reason, begin date, and end date already accept entries under 10 characters—each can be as short as one character.

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

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

load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ticket_bot")

db = sqlite3.connect("bot_data.sqlite3")
db.execute("CREATE TABLE IF NOT EXISTS settings (guild_id INTEGER PRIMARY KEY, staff_role_id INTEGER, log_channel_id INTEGER)")
db.execute("CREATE TABLE IF NOT EXISTS tickets (channel_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL, owner_id INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS partner_settings (guild_id INTEGER PRIMARY KEY, log_channel_id INTEGER, announcement_channel_id INTEGER)")
db.execute("CREATE TABLE IF NOT EXISTS loa_settings (guild_id INTEGER PRIMARY KEY, channel_id INTEGER NOT NULL, reviewer_role_id INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS loa_requests (message_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL, requester_id INTEGER NOT NULL, reason TEXT NOT NULL, begin_date TEXT NOT NULL, end_date TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'Pending')")
db.commit()

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


def get_settings(guild_id: int):
    return db.execute("SELECT staff_role_id, log_channel_id FROM settings WHERE guild_id = ?", (guild_id,)).fetchone() or (None, None)


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

    async def create_ticket(self, interaction: discord.Interaction, ticket_type: str):
        if interaction.guild is None or not isinstance(interaction.user, discord.Member):
            await interaction.response.send_message("Tickets can only be opened in a server.", ephemeral=True)
            return
        await interaction.response.defer(ephemeral=True, thinking=True)
        guild = interaction.guild
        staff_role_id, _ = get_settings(guild.id)
        staff_role = guild.get_role(staff_role_id) if staff_role_id else None
        if staff_role is None:
            await interaction.followup.send("A server administrator must set a valid staff role with `/ticket_setup` first.", ephemeral=True)
            return
        me = guild.me
        if me is None:
            await interaction.followup.send("I couldn't determine my server permissions. Please try again.", ephemeral=True)
            return
        overwrites = {
            guild.default_role: discord.PermissionOverwrite(view_channel=False),
            interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True),
            staff_role: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True),
            me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True, manage_channels=True),
        }
        try:
            channel = await guild.create_text_channel(
                name=f"{ticket_type}-{interaction.user.name}"[:100],
                overwrites=overwrites,
                reason=f"{ticket_type.title()} ticket opened by {interaction.user}",
            )
            db.execute("INSERT INTO tickets (channel_id, guild_id, owner_id) VALUES (?, ?, ?)", (channel.id, guild.id, interaction.user.id))
            db.commit()
            embed = discord.Embed(title=f"{ticket_type.title()} Ticket", description="Please describe what you need. A staff member will help you soon.", color=discord.Color.blurple())
            await channel.send(f"{interaction.user.mention} {staff_role.mention}", embed=embed, view=CloseTicketView(), allowed_mentions=discord.AllowedMentions(users=True, roles=True, everyone=False))
            await interaction.followup.send(f"Your ticket has been created: {channel.mention}", ephemeral=True)
        except discord.HTTPException:
            logger.exception("Failed to create or initialize ticket in guild %s", guild.id)
            await interaction.followup.send("I couldn't create or initialize the ticket. Check my channel and message permissions.", ephemeral=True)

    @discord.ui.button(label="Order", style=discord.ButtonStyle.primary, emoji="🛒", custom_id="tickets:order")
    async def order(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.create_ticket(interaction, "order")

    @discord.ui.button(label="Support", style=discord.ButtonStyle.secondary, emoji="❓", custom_id="tickets:support")
    async def support(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.create_ticket(interaction, "support")


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

    async def decide(self, interaction: discord.Interaction, status: str):
        if interaction.guild is None or not isinstance(interaction.user, discord.Member):
            await interaction.response.send_message("This button only works in a server.", ephemeral=True)
            return
        settings = db.execute("SELECT reviewer_role_id FROM loa_settings WHERE guild_id = ?", (interaction.guild_id,)).fetchone()
        if not settings or not (interaction.user.guild_permissions.manage_guild or any(role.id == settings[0] for role in interaction.user.roles)):
            await interaction.response.send_message("Only higher staff can review LOA requests.", ephemeral=True)
            return
        row = db.execute("SELECT requester_id, reason, begin_date, end_date, status FROM loa_requests WHERE message_id = ? AND guild_id = ?", (interaction.message.id, interaction.guild_id)).fetchone()
        if not row or row[4] != "Pending":
            await interaction.response.send_message("This request has already been reviewed or is no longer available.", ephemeral=True)
            return
        db.execute("UPDATE loa_requests SET status = ? WHERE message_id = ? AND status = 'Pending'", (status, interaction.message.id))
        db.commit()
        embed = interaction.message.embeds[0].copy()
        embed.color = discord.Color.green() if status == "Accepted" else discord.Color.red()
        embed.add_field(name="Decision", value=f"{status} by {interaction.user.mention}", inline=False)
        reviewed_view = LOAReviewView()
        for child in reviewed_view.children:
            child.disabled = True
        await interaction.response.edit_message(embed=embed, view=reviewed_view)
        try:
            user = await bot.fetch_user(row[0])
            await user.send(f"Your LOA request in **{interaction.guild.name}** for {row[2]} to {row[3]} was **{status.lower()}** by {interaction.user}.")
        except discord.HTTPException:
            logger.exception("Could not DM LOA requester %s", row[0])
            await interaction.followup.send("The decision was recorded, but I couldn't DM the requester.", ephemeral=True)

    @discord.ui.button(label="Accept", style=discord.ButtonStyle.success, custom_id="loa:accept")
    async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.decide(interaction, "Accepted")

    @discord.ui.button(label="Deny", style=discord.ButtonStyle.danger, custom_id="loa:deny")
    async def deny(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.decide(interaction, "Denied")


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

    @discord.ui.button(label="Close Ticket", style=discord.ButtonStyle.danger, emoji="🔒", custom_id="tickets:close")
    async def close(self, interaction: discord.Interaction, button: discord.ui.Button):
        if interaction.guild is None or not isinstance(interaction.user, discord.Member):
            await interaction.response.send_message("This button only works in a server.", ephemeral=True)
            return
        row = db.execute("SELECT owner_id FROM tickets WHERE channel_id = ? AND guild_id = ?", (interaction.channel_id, interaction.guild.id)).fetchone()
        if row is None:
            await interaction.response.send_message("This channel is not a tracked ticket.", ephemeral=True)
            return
        staff_role_id, _ = get_settings(interaction.guild.id)
        is_staff = any(role.id == staff_role_id for role in interaction.user.roles)
        if interaction.user.id != row[0] and not is_staff and not interaction.user.guild_permissions.manage_channels:
            await interaction.response.send_message("Only the ticket owner or staff can close this ticket.", ephemeral=True)
            return
        await interaction.response.send_message("Closing this ticket...")
        try:
            await interaction.channel.delete(reason=f"Ticket closed by {interaction.user}")
        except discord.HTTPException:
            logger.exception("Failed to close ticket %s", interaction.channel_id)
            await interaction.followup.send("I couldn't delete this channel. Check my Manage Channels permission.", ephemeral=True)
            return
        db.execute("DELETE FROM tickets WHERE channel_id = ?", (interaction.channel_id,))
        db.commit()


@bot.event
async def on_ready():
    print("KODARI_READY", flush=True)
    logger.info("Logged in as %s", bot.user)


@bot.event
async def on_guild_channel_delete(channel: discord.abc.GuildChannel):
    db.execute("DELETE FROM tickets WHERE channel_id = ?", (channel.id,))
    db.commit()


@bot.event
async def setup_hook():
    bot.add_view(TicketView())
    bot.add_view(CloseTicketView())
    bot.add_view(LOAReviewView())
    await bot.tree.sync()


@bot.tree.command(name="loa_setup", description="Set the LOA review channel and higher staff role")
@app_commands.guild_only()
@app_commands.default_permissions(manage_guild=True)
@app_commands.checks.has_permissions(manage_guild=True)
async def loa_setup(interaction: discord.Interaction, channel: discord.TextChannel, higher_staff: discord.Role):
    if higher_staff.is_default():
        await interaction.response.send_message("Choose a higher staff role other than @everyone.", ephemeral=True)
        return
    db.execute("INSERT INTO loa_settings (guild_id, channel_id, reviewer_role_id) VALUES (?, ?, ?) ON CONFLICT(guild_id) DO UPDATE SET channel_id = excluded.channel_id, reviewer_role_id = excluded.reviewer_role_id", (interaction.guild_id, channel.id, higher_staff.id))
    db.commit()
    await interaction.response.send_message(f"LOA requests will be sent to {channel.mention} for review by {higher_staff.mention}. Make sure the channel is private to higher staff.", ephemeral=True)


@bot.tree.command(name="loarequest", description="Request a leave of absence")
@app_commands.guild_only()
@app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id))
@app_commands.describe(reason="Why you need leave", begin_date="When your leave begins (any format)", end_date="When your leave ends (any format)")
async def loarequest(interaction: discord.Interaction, reason: app_commands.Range[str, 1, 1000], begin_date: app_commands.Range[str, 1, 100], end_date: app_commands.Range[str, 1, 100]):
    settings = db.execute("SELECT channel_id, reviewer_role_id FROM loa_settings WHERE guild_id = ?", (interaction.guild_id,)).fetchone()
    channel = interaction.guild.get_channel(settings[0]) if settings else None
    if not isinstance(channel, discord.TextChannel) or interaction.guild.get_role(settings[1]) is None:
        await interaction.response.send_message("An administrator must configure a valid channel and role with `/loa_setup` first.", ephemeral=True)
        return
    await interaction.response.defer(ephemeral=True, thinking=True)
    embed = discord.Embed(title="Leave of Absence Request", color=discord.Color.blurple(), timestamp=discord.utils.utcnow())
    embed.add_field(name="Requester", value=interaction.user.mention, inline=False)
    embed.add_field(name="Reason", value=reason, inline=False)
    embed.add_field(name="Begin date", value=begin_date, inline=True)
    embed.add_field(name="End date", value=end_date, inline=True)
    try:
        message = await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
        db.execute("INSERT INTO loa_requests (message_id, guild_id, requester_id, reason, begin_date, end_date) VALUES (?, ?, ?, ?, ?, ?)", (message.id, interaction.guild_id, interaction.user.id, reason, begin_date, end_date))