No chat to show

This project's files are all here to explore.

Files
src
deploy-commands.js
package.json
README.md
Code
7 583
src/index.js
const path = require('node:path');
const {
  Client,
  GatewayIntentBits,
  Partials,
  ActivityType,
  ChannelType,
  PermissionFlagsBits,
  EmbedBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle
} = require('discord.js');
const config = require('./config');
const Store = require('./store');

if (!config.token) throw new Error('DISCORD_TOKEN is missing. Add it to .env.');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildModeration,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ],
  partials: [Partials.GuildMember, Partials.User, Partials.Channel]
});
const store = new Store(path.join(__dirname, '..', 'data', 'server-data.json'));
const colors = { red: 0xE74C3C, orange: 0xF39C12, green: 0x2ECC71, blue: 0x3498DB, purple: 0x9B59B6, dark: 0x18212B };

function baseEmbed(color = colors.blue) {
  return new EmbedBuilder().setColor(color).setTimestamp().setFooter({ text: config.serverName });
}

function rulesEmbed() {
  return baseEmbed(colors.red)
    .setTitle(`${config.serverName} โ€” Rules`)
    .setDescription([
      '**1. Respect everyone**\nNo harassment, hate speech, threats, or targeted abuse.',
      '**2. No cheating**\nDo not use cheats, exploits, dupes, combat logging, or unauthorized clients.',
      '**3. Keep it appropriate**\nNo spam, malicious links, advertising, or unsafe content.',
      '**4. Use the right channels**\nKeep support, reports, and general chat in their intended places.',
      '**5. Follow staff direction**\nDo not evade punishments or interfere with an active investigation.',
      '**6. Have fun**\nPvP is encouraged; ruining the community is not.'
    ].join('\n\n'))
    .addFields({ name: 'Enforcement', value: 'Punishments can include warnings, timeouts, kicks, bans, and blacklist actions depending on severity.' });
}

function isStaff(interaction) {
  return interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) ||
    interaction.memberPermissions?.has(PermissionFlagsBits.ManageGuild) ||
    Boolean(config.staffRoleId && interaction.member?.roles?.cache?.has(config.staffRoleId));
}

function hasHigherOrEqualRole(interaction, target) {
  if (!interaction.member?.roles?.highest || !target.roles?.highest) return true;
  return interaction.member.roles.highest.comparePositionTo(target.roles.highest) > 0;
}

function getMember(interaction, userId) {
  return interaction.guild.members.cache.get(userId) || null;
}

async function sendLog(guild, title, description, color = colors.dark) {
  if (!config.logChannelId) return;
  const channel = await guild.channels.fetch(config.logChannelId).catch(() => null);
  if (channel?.isTextBased()) await channel.send({ embeds: [baseEmbed(color).setTitle(title).setDescription(description)] }).catch(() => null);
}

async function replyEphemeral(interaction, content) {
  if (interaction.replied || interaction.deferred) return interaction.followUp({ content, ephemeral: true });
  return interaction.reply({ content, ephemeral: true });
}

async function handleRules(interaction) {
  await interaction.reply({ embeds: [rulesEmbed()] });
}

async function handleVerifyPanel(interaction) {
  const row = new ActionRowBuilder().addComponents(
    new ButtonBuilder().setCustomId('verify-member').setLabel('Verify me').setEmoji('โœ…').setStyle(ButtonStyle.Success)
  );
  const embed = baseEmbed(colors.green)
    .setTitle('Member verification')
    .setDescription('Click **Verify me** to receive access to the community. If the button does not work, open a ticket.');
  await interaction.reply({ embeds: [embed], components: [row] });
}

async function handleBoost(interaction) {
  const boostRole = config.boostRoleId ? `<@&${config.boostRoleId}>` : 'the Booster role';
  const embed = baseEmbed(colors.purple)
    .setTitle('Support the server with a boost')
    .setDescription(`Boosting helps keep ${config.serverName} online and growing.\n\nBoosters receive ${boostRole} and our appreciation. Thanks for supporting the wasteland!`)
    .addFields({ name: 'Server address', value: `\`${config.serverIp}\``, inline: true }, { name: 'Version', value: config.serverVersion, inline: true });
  await interaction.reply({ embeds: [embed] });
}

async function handleTicket(interaction) {
  const existing = Object.values(store.guild(interaction.guildId).tickets).find((ticket) => ticket.userId === interaction.user.id);
  if (existing) {
    const channel = interaction.guild.channels.cache.get(existing.channelId);
    if (channel) return replyEphemeral(interaction, `You already have an open ticket: ${channel}`);
    store.deleteTicket(interaction.guildId, existing.channelId);
  }

  const safeName = interaction.user.username.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 16) || 'user';
  const permissionOverwrites = [
    { id: interaction.guild.id, deny: [PermissionFlagsBits.ViewChannel] },
    { id: interaction.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory] }
  ];
  if (config.staffRoleId) {
    permissionOverwrites.push({ id: config.staffRoleId, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory] });
  }

  const channel = await interaction.guild.channels.create({
    name: `ticket-${safeName}`,
    type: ChannelType.GuildText,
    parent: config.ticketCategoryId || undefined,
    topic: `Support ticket opened by ${interaction.user.tag}`,
    permissionOverwrites
  });
  store.setTicket(interaction.guildId, channel.id, { userId: interaction.user.id, username: interaction.user.tag, reason: interaction.options.getString('reason'), createdAt: new Date().toISOString(), channelId: channel.id });

  const closeRow = new ActionRowBuilder().addComponents(
    new ButtonBuilder().setCustomId('close-ticket').setLabel('Close ticket').setEmoji('๐Ÿ”’').setStyle(ButtonStyle.Danger)
  );
  const embed = baseEmbed(colors.orange)
    .setTitle(`Support ticket โ€” ${interaction.user.username}`)
    .setDescription(`${config.supportMessage}\n\n**Reason:** ${interaction.options.getString('reason')}`)
    .addFields({ name: 'Opened by', value: `${interaction.user}`, inline: true }, { name: 'Staff', value: config.staffRoleId ? `<@&${config.staffRoleId}>` : 'Staff team', inline: true });
  await channel.send({ content: `${interaction.user} ${config.staffRoleId ? `<@&${config.staffRoleId}>` : ''}`, embeds: [embed], components: [closeRow] });
  await interaction.reply({ content: `Your ticket has been created: ${channel}`, ephemeral: true });
  await sendLog(interaction.guild, 'Ticket opened', `${interaction.user} opened ${channel} for: ${interaction.options.getString('reason')}`, colors.orange);
}

async function handleStaff(interaction) {
  if (!isStaff(interaction)) return replyEphemeral(interaction, 'You do not have permission to use staff tools.');
  const action = interaction.options.getSubcommand();
  const guild = interaction.guild;
  const user = interaction.options.getUser('user');
  const member = user ? getMember(interaction, user.id) : null;
  const reason = interaction.options.getString('reason') || 'No reason provided';

  if (['kick', 'timeout', 'ban'].includes(action) && (!member || !hasHigherOrEqualRole(interaction, member))) {
    return replyEphemeral(interaction, 'That member is not available or has an equal/higher role than you.');
  }

  if (action === 'blacklist-add') {
    const entry = store.addBlacklist(guild.id, user.id, user.tag, reason, interaction.user.id);
    await interaction.reply({ content: `Added **${user.tag}** to the staff blacklist. Entry ID: \\`${entry.createdAt}\\``, ephemeral: true });
    return sendLog(guild, 'Blacklist entry added', `${user} was blacklisted by ${interaction.user}.\n**Reason:** ${reason}`, colors.red);
  }
  if (action === 'blacklist-remove') {
    const removed = store.removeBlacklist(guild.id, user.id);
    await interaction.reply({ content: removed ? `Removed **${user.tag}** from the staff blacklist.` : `${user.tag} was not on the staff blacklist.`, ephemeral: true });
    return sendLog(guild, 'Blacklist entry removed', `${user} was removed from the blacklist by ${interaction.user}.`, colors.green);
  }
  if (action === 'blacklist-list') {
    const entries = store.getBlacklist(guild.id);
    const description = entries.length ? entries.map((entry) => `โ€ข **${entry.username}** (<@${entry.userId}>) โ€” ${entry.reason}`).join('\n') : 'The staff blacklist is empty.';
    return interaction.reply({ embeds: [baseEmbed(colors.red).setTitle('Staff blacklist').setDescription(description).setFooter({ text: `${entries.length} entr${entries.length === 1 ? 'y' : 'ies'}` })], ephemeral: true });
  }
  if (action === 'warn') {
    const warning = store.addWarning(guild.id, user.id, user.tag, reason, interaction.user.id);
    await interaction.reply({ content: `Warned **${user.tag}**. Warning ID: \\`${warning.id}\\``, ephemeral: true });
    await user.send(`You received a warning in **${guild.name}**.\nReason: ${reason}`).catch(() => null);
    return sendLog(guild, 'Member warned', `${user} was warned by ${interaction.user}.\n**Reason:** ${reason}\n**ID:** ${warning.id}`, colors.orange);
  }
  if (action === 'warnings') {
    const warnings = store.getWarnings(guild.id, user.id);
    const description = warnings.length ? warnings.map((warning, index) => `**${index + 1}. ${warning.id}** โ€” ${warning.reason}\nIssued <t:${Math.floor(new Date(warning.createdAt).getTime() / 1000)}:R> by <@${warning.moderatorId}>`).join('\n\n') : 'This player has no warnings.';
    return interaction.reply({ embeds: [baseEmbed(colors.orange).setTitle(`Warnings โ€” ${user.tag}`).setDescription(description)], ephemeral: true });
  }
  if (action === 'unwarn') {
    const warning = store.removeWarning(guild.id, user.id, interaction.options.getString('warning_id'));
    await interaction.reply({ content: warning ? `Removed warning **${warning.id}** from ${user.tag}.` : 'No matching warning was found.', ephemeral: true });
    if (warning) return sendLog(guild, 'Warning removed', `Warning ${warning.id} for ${user} was removed by ${interaction.user}.`, colors.green);
    return undefined;
  }
  if (action === 'clearwarnings') {
    const count = store.clearWarnings(guild.id, user.id);
    await interaction.reply({ content: `Cleared ${count} warning${count === 1 ? '' : 's'} for ${user.tag}.`, ephemeral: true });
    return sendLog(guild, 'Warnings cleared', `${interaction.user} cleared warnings for ${user}.`, colors.green);
  }
  if (action === 'kick') {
    await member.kick(reason);
    await interaction.reply({ content: `Kicked **${user.tag}**.`, ephemeral: true });
    return sendLog(guild, 'Member kicked', `${user} was kicked by ${interaction.user}.\n**Reason:** ${reason}`, colors.red);
  }
  if (action === 'timeout') {
    const minutes = interaction.options.getInteger('minutes');
    await member.timeout(minutes * 60 * 1000, reason);
    await interaction.reply({ content: `Timed out **${user.tag}** for ${minutes} minute${minutes === 1 ? '' : 's'}.`, ephemeral: true });
    return sendLog(guild, 'Member timed out', `${user} was timed out by ${interaction.user} for ${minutes} minutes.\n**Reason:** ${reason}`, colors.orange);
  }
  if (action === 'ban') {
    await member.ban({ reason });
    await interaction.reply({ content: `Banned **${user.tag}**.`, ephemeral: true });
    return sendLog(guild, 'Member banned', `${user} was banned by ${interaction.user}.\n**Reason:** ${reason}`, colors.red);