Creating a comprehensive Discord ticket bot with features like persistent buttons, logging, transcripts, admin controls, categorized tickets, and appealing visuals can be a rewarding project. Below, I'll guide you through creating such a bot using discord.js v14 (the latest version at the time of writing). This example will cover:
- Setting Up the Bot
- Creating Ticket Channels
- Logging and Transcripts
- Admin Commands
- Good-looking Visuals with Embeds and Dropdowns
- Persistence Across Restarts
Prerequisites
- Node.js Installed: Ensure you have Node.js installed (v16.9.0 or higher is required for discord.js v14).
- Discord Bot Token: Create a bot via the Discord Developer Portal and obtain its token.
- Basic JavaScript Knowledge: Familiarity with JavaScript and asynchronous programming.
Step 1: Setting Up the Project
-
Initialize the Project
mkdir discord-ticket-bot
cd discord-ticket-bot
npm init -y
-
Install Required Dependencies
npm install discord.js @discordjs/rest discord-api-types dotenv
-
Project Structure
discord-ticket-bot/
├── commands/
│ └── deploy-commands.js
├── handlers/
│ └── eventHandler.js
├── data/
│ └── tickets.json
├── .env
└── index.js
-
Create .env File
Create a .env file in the root directory with the following content:
TOKEN=YOUR_BOT_TOKEN_HERE
CLIENT_ID=YOUR_CLIENT_ID
GUILD_ID=YOUR_GUILD_ID
LOG_CHANNEL_ID=YOUR_LOG_CHANNEL_ID
- TOKEN: Your bot's token.
- CLIENT_ID: Your bot's application client ID.
- GUILD_ID: Your server's ID where you'll deploy the commands.
- LOG_CHANNEL_ID: The channel ID where logs will be sent.
Step 2: Deploying Slash Commands
We'll create a /ticket command that users can interact with to create tickets.
// commands/deploy-commands.js
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
require('dotenv').config();
const commands = [
new SlashCommandBuilder()
.setName('ticket')
.setDescription('Open a ticket')
.addStringOption(option =>
option.setName('reason')
.setDescription('Reason for the ticket')
.setRequired(true)),
]
.map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
Run the Command Deployment Once:
node commands/deploy-commands.js
Step 3: Main Bot Logic
// index.js
const { Client, GatewayIntentBits, Partials, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, PermissionsBitField } = require('discord.js');
const fs = require('fs');
require('dotenv').config();
// Initialize client
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
partials: [Partials.Channel],
});
// Load existing tickets or initialize
let tickets = {};
const ticketsFile = './data/tickets.json';
if (fs.existsSync(ticketsFile)) {
tickets = JSON.parse(fs.readFileSync(ticketsFile, 'utf8'));
}
// Save tickets to file
const saveTickets = () => {
fs.writeFileSync(ticketsFile, JSON.stringify(tickets, null, 2));
};
// On Ready
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}`);
});
// Handle Interactions
client.on('interactionCreate', async interaction => {
if (interaction.isChatInputCommand()) {
if (interaction.commandName === 'ticket') {
const reason = interaction.options.getString('reason');
// Create a unique channel name
const channelName = `ticket-${interaction.user.username}-${interaction.user.discriminator}`;
// Check if user already has an open ticket
if (tickets[interaction.user.id]) {
return interaction.reply({ content: 'You already have an open ticket.', ephemeral: true });
}
// Create the ticket channel
const ticketChannel = await interaction.guild.channels.create({
name: channelName,
type: 0, // Guild Text Channel
parent: getCategory(interaction.guild),
permissionOverwrites: [
{
// The channel is visible to the user and admins
id: interaction.guild.roles.everyone.id,
deny: [PermissionsBitField.Flags.ViewChannel],
},
{
id: interaction.user.id,
allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages, PermissionsBitField.Flags.ReadMessageHistory],
},
{
id: client.user.id,
allow: [PermissionsBitField.Flags.ViewChannel, PermissionsBitField.Flags.SendMessages],
},
// Add admin roles if needed
],
});
// Embed for the ticket channel
const embed = new EmbedBuilder()
.setTitle('Support Ticket')
.setDescription(`Hello ${interaction.user}, a member of our support team will be with you shortly.\n**Reason:** ${reason}`)
.setColor('#AF1CA6')
.setTimestamp();
// Button to close the ticket
const closeButton = new ButtonBuilder()
.setCustomId('closeTicket')
.setLabel('Close Ticket')
.setStyle(ButtonStyle.Danger);
const row = new ActionRowBuilder().addComponents(closeButton);
await ticketChannel.send({ embeds: [embed], components: [row] });
// Acknowledge the creation
await interaction.reply({ content: `Your ticket has been created: ${ticketChannel}`, ephemeral: true });
// Log the ticket creation
logAction(interaction.guild, `Ticket created by ${interaction.user.tag}`, ticketChannel);
// Save the ticket
tickets[interaction.user.id] = ticketChannel.id;
saveTickets();
}
} else if (interaction.isButton()) {
if (interaction.customId === 'closeTicket') {
// Check if the user has permission to close the ticket
if (!interaction.member.permissions.has(PermissionsBitField.Flags.ManageChannels)) {
return interaction.reply({ content: 'You do not have permission to close this ticket.', ephemeral: true });
}
const channel = interaction.channel;
const userId = getUserIdFromChannel(channel);
// Create a transcript (simple version)
const messages = await channel.messages.fetch({ limit: 100 });
const transcript = messages.map(msg => `${msg.author.tag}: ${msg.content}`).reverse().join('\n');
// Send transcript to log channel
const logChannel = interaction.guild.channels.cache.get(process.env.LOG_CHANNEL_ID);
if (logChannel) {
logChannel.send({
content: `Transcript for ${channel.name}`,
files: [{ attachment: Buffer.from(transcript, 'utf-8'), name: `${channel.name}-transcript.txt` }],
});
}
// Delete the channel
await channel.delete();
// Remove from tickets
if (userId) {
delete tickets[userId];
saveTickets();
}
// Log the ticket closure
logAction(interaction.guild, `Ticket closed by ${interaction.user.tag}`, channel);
}
}
});
// Helper Functions
// Get or create the ticket category
function getCategory(guild) {
const categoryName = 'Support Tickets';
let category = guild.channels.cache.find(c => c.name === categoryName && c.type === 4); // 4 is for category
if (!category) {
category = guild.channels.create({
name: categoryName,
type: 4,
}).then(c => c);
}
return category;
}
// Log actions to the log channel
function logAction(guild, message, channel) {
const logChannel = guild.channels.cache.get(process.env.LOG_CHANNEL_ID);
if (logChannel) {
const embed = new EmbedBuilder()
.setDescription(message)
.addFields({ name: 'Channel', value: `${channel}`, inline: true })
.setColor('#AF1CA6')
.setTimestamp();
logChannel.send({ embeds: [embed] });
}
}
// Extract user ID from the channel name
function getUserIdFromChannel(channel) {
const regex = /^ticket-(.+)-(\d{4})$/;
const match = channel.name.match(regex);
if (match) {
const username = match[1];
const discriminator = match[2];
const members = channel.guild.members.cache.filter(m => m.user.username === username && m.user.discriminator === discriminator);
if (members.size > 0) return members.first().id;
}
return null;
}
// Handle bot restart persistence
client.on('ready', async () => {
for (const userId in tickets) {
const channelId = tickets[userId];
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel) {
delete tickets[userId];
saveTickets();
}
}
});
// Log in the bot
client.login(process.env.TOKEN);
Step 4: Adding Dropdowns and Interactive Elements
For more advanced interactivity like dropdowns (select menus), you can extend the bot. Here's an example of adding a select menu to choose the type of ticket.
-
Modify the /ticket Command to Include Ticket Types
Update the command deployment to include a select menu.
// Modify the interaction handler for /ticket
if (interaction.commandName === 'ticket') {
// Previous code...
// Create a select menu for ticket types
const ticketSelect = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('ticket_button')
.setLabel('Create Ticket')
.setStyle(ButtonStyle.Primary)
.setEmoji('🎫')
);
await interaction.reply({
content: 'Click the button below to create a ticket.',
components: [ticketSelect],
ephemeral: true,
});
}
-
Handle the Select Menu Interaction
// Inside interactionCreate event
if (interaction.isButton()) {
if (interaction.customId === 'ticket_button') {
// Prompt user for ticket reason or use the one provided earlier
// Can integrate modal for more complex inputs
}
// Existing closeTicket handler...
}
Note: Implementing select menus with multiple options requires additional handling, including parsing the selected option and adjusting the ticket creation accordingly.
Step 5: Ensuring Buttons Work After Restart
Buttons in Discord are tied to the message they belong to. To ensure button interactions work after a bot restart, make sure that:
-
Intents and Partials: The bot has the necessary intents and partials to receive interaction events for cached messages.
-
Consistent State Management: Persist necessary state data (like open tickets) in a database or file (as shown with tickets.json).
-
Re-registering Components: Since Discord buttons are part of messages, as long as the bot can handle interaction events correctly, they should work after a restart.
Step 6: Enhancing Visuals with Embeds
Embeds make messages look more polished. Ensure you use the specified color code #AF1CA6 for all your embeds for consistency.
const embed = new EmbedBuilder()
.setTitle('Your Embed Title')
.setDescription('Your embed description')
.setColor('#AF1CA6') // Use the specified color code
.setTimestamp();
Additional Features and Improvements
-
Transcripts with Better Formatting: Integrate libraries like discord-html-transcripts for better transcript formatting.
-
Database Integration: For scalability and better persistence, consider using databases like SQLite, MongoDB, or PostgreSQL instead of JSON files.
-
Admin Panel: Create additional slash commands for admins to manage tickets, view logs, etc.
-
Permissions Management: Fine-tune channel permissions to include specific support roles.
-
Error Handling: Implement comprehensive error handling to catch and log potential issues.
-
UI/UX Enhancements: Use rich embeds, images, and more interactive components to enhance the user experience.
Conclusion
The provided code offers a foundational Discord ticket bot with essential features such as ticket creation, closing with transcripts, logging, and basic persistence. Depending on your specific needs, you can extend and customize this bot further. Always ensure you handle sensitive data securely and comply with Discord's API terms of service.
Note: This example uses discord.js v14. Ensure that your project dependencies match the version used in the code. For more advanced functionalities and customization, refer to the discord.js documentation and consider looking into additional libraries or frameworks that can aid in bot development.