Files
src
.gitignore
package.json
README.md
Code
10 653
src/index.js
const {
Client,
Collection,
GatewayIntentBits,
Partials,
EmbedBuilder,
ButtonBuilder,
ButtonStyle,
ActionRowBuilder
} = require('discord.js');
const config = require('./config');
const Storage = require('./storage');
const { commands, execute } = require('./commands');
const { COLORS, embed, logEmbed } = require('./embeds');
const { isStaff } = require('./permissions');
if (!config.token) throw new Error('DISCORD_TOKEN is missing. Copy .env.example to .env and configure it.');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
],
partials: [Partials.Channel]
});
client.storage = new Storage(config.dataFile);
client.commands = new Collection(commands.map((command) => [command.name, command]));
const commandCooldowns = new Map();
async function sendGuildLog(guild, title, description, color = COLORS.neutral) {
const settings = client.storage.getGuildSettings(guild.id);
const channelId = settings.logChannelId || config.logChannelId;
if (!channelId) return;
const channel = await client.channels.fetch(channelId).catch(() => null);
if (channel?.isTextBased()) await channel.send({ embeds: [logEmbed(title, description, color)] }).catch(() => null);
}
async function createTicket(interaction) {
const existing = client.storage.getTicket(interaction.guild.id, interaction.user.id);
if (existing) {
const channel = await interaction.guild.channels.fetch(existing.channelId).catch(() => null);
if (channel) return interaction.reply({ content: `You already have an open ticket: ${channel}`, ephemeral: true });
client.storage.deleteTicket(interaction.guild.id, interaction.user.id);
}
const overwrites = [
{ id: interaction.guild.roles.everyone.id, deny: ['ViewChannel'] },
{ id: interaction.user.id, allow: ['ViewChannel', 'SendMessages', 'ReadMessageHistory'] },
{ id: interaction.guild.members.me.id, allow: ['ViewChannel', 'SendMessages', 'ReadMessageHistory', 'ManageChannels'] }
];
if (config.supportRoleId) overwrites.push({ id: config.supportRoleId, allow: ['ViewChannel', 'SendMessages', 'ReadMessageHistory'] });
const channel = await interaction.guild.channels.create({
name: `ticket-${interaction.user.username}`.toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 90) || `ticket-${interaction.user.id}`,
type: 0,
parent: config.ticketCategoryId || client.storage.getGuildSettings(interaction.guild.id).ticketCategoryId || null,
permissionOverwrites: overwrites,
topic: `Support ticket opened by ${interaction.user.tag} (${interaction.user.id})`
});
client.storage.setTicket(interaction.guild.id, interaction.user.id, { channelId: channel.id, openedAt: new Date().toISOString() });
const closeButton = new ButtonBuilder().setCustomId('ticket:close').setLabel('Close ticket').setEmoji('๐').setStyle(ButtonStyle.Danger);
await channel.send({ content: `${interaction.user}${config.supportRoleId ? ` <@&${config.supportRoleId}>` : ''}`, embeds: [embed('Support ticket', 'Please explain what you need help with. A member of the Wellington NZRP team will respond soon.', COLORS.primary)], components: [new ActionRowBuilder().addComponents(closeButton)] });
await interaction.reply({ content: `Your ticket has been created: ${channel}`, ephemeral: true });
await sendGuildLog(interaction.guild, 'Ticket opened', `${channel} opened by ${interaction.user.tag}`);
}
async function handleButton(interaction) {
if (!interaction.guild) return interaction.reply({ content: 'This button only works inside a server.', ephemeral: true });
if (interaction.customId === 'verify') {
const roleId = client.storage.getGuildSettings(interaction.guild.id).verifyRoleId || config.verifyRoleId;
const role = roleId && interaction.guild.roles.cache.get(roleId);
if (!role) return interaction.reply({ content: 'Verification is not configured. Please contact staff.', ephemeral: true });
if (role.position >= interaction.guild.members.me.roles.highest.position) return interaction.reply({ content: 'The verification role is above my highest role.', ephemeral: true });
await interaction.member.roles.add(role);
return interaction.reply({ content: `You are verified and received ${role}.`, ephemeral: true });
}
if (interaction.customId === 'ticket:create') return createTicket(interaction);
if (interaction.customId === 'ticket:close') {
const ticket = client.storage.getTicketByChannel(interaction.channel.id);
if (!ticket || (!isStaff(interaction.member) && ticket.channelId !== interaction.channel.id)) return interaction.reply({ content: 'This ticket cannot be closed here.', ephemeral: true });
if (!isStaff(interaction.member)) {
const topicOwner = interaction.channel.topic?.match(/\((\d+)\)$/)?.[1];
if (topicOwner !== interaction.user.id) return interaction.reply({ content: 'Only the ticket owner or staff can close this ticket.', ephemeral: true });
}
const ownerId = interaction.channel.topic?.match(/\((\d+)\)$/)?.[1];
await interaction.reply('This ticket will close in 5 seconds.');
if (ownerId) client.storage.deleteTicket(interaction.guild.id, ownerId);
await sendGuildLog(interaction.guild, 'Ticket closed', `${interaction.channel.name} closed by ${interaction.user.tag}`);
setTimeout(() => interaction.channel.delete('Ticket closed').catch(() => null), 5000);
}
}
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag} and serving ${client.guilds.cache.size} guild(s).`);
client.user.setActivity('Wellington NZRP | /help');
});
client.on('interactionCreate', async (interaction) => {
try {
if (interaction.isButton()) return await handleButton(interaction);
if (!interaction.isChatInputCommand()) return;
const key = `${interaction.user.id}:${interaction.commandName}`;
const lastUsed = commandCooldowns.get(key) || 0;
if (Date.now() - lastUsed < 2000) return interaction.reply({ content: 'Please wait a moment before using that command again.', ephemeral: true });
commandCooldowns.set(key, Date.now());
await execute(interaction, client);
} catch (error) {
console.error('Interaction error:', error);
const response = { content: 'Something went wrong while processing that request.', ephemeral: true };
if (interaction.replied || interaction.deferred) await interaction.followUp(response).catch(() => null);
else await interaction.reply(response).catch(() => null);
}
});
client.on('messageCreate', async (message) => {
if (!message.guild || message.author.bot || isStaff(message.member)) return;
const invite = config.automodInvites && /(discord(?:app)?\.com\/invite|discord\.gg)\/[-\w]+/i.test(message.content);
const mentionSpam = message.mentions.users.size >= config.automodMentionLimit;
if (!invite && !mentionSpam) return;
await message.delete().catch(() => null);
await message.channel.send({ content: `${message.author}, that message was removed by automoderation.` }).then((sent) => setTimeout(() => sent.delete().catch(() => null), 5000)).catch(() => null);
await sendGuildLog(message.guild, 'Automod action', `Removed a message from ${message.author.tag} in ${message.channel}.\n**Reason:** ${invite ? 'Discord invite link' : 'Mention spam'}`, COLORS.danger);
});
client.on('guildMemberAdd', async (member) => {
const channelId = config.welcomeChannelId || client.storage.getGuildSettings(member.guild.id).welcomeChannelId;
const channel = channelId && await client.channels.fetch(channelId).catch(() => null);
if (channel?.isTextBased()) {
const content = config.welcomeMessage.replaceAll('{user}', member.toString()).replaceAll('{server}', member.guild.name);
await channel.send({ embeds: [embed('New member', content, COLORS.success)] }).catch(() => null);
}
await sendGuildLog(member.guild, 'Member joined', `${member.user.tag} (${member.id}) joined the server.`, COLORS.success);
});
client.on('guildMemberRemove', (member) => sendGuildLog(member.guild, 'Member left', `${member.user.tag} (${member.id}) left or was removed.`, COLORS.warning));
client.on('error', (error) => console.error('Discord client error:', error));
process.on('unhandledRejection', (error) => console.error('Unhandled rejection:', error));
client.login(config.token);