index.js
require('dotenv').config();
const { Client, GatewayIntentBits, Partials, REST, Routes, SlashCommandBuilder } = require('discord.js');
const { startApi } = require('./api/server');
const { startKeepAlive } = require('./api/keepAlive');
const { scheduleDirectoryRefresh, refreshDirectory } = require('./directory/refresh');
const { handleInteraction } = require('./commands/handler');
const { handleVoiceStateUpdate } = require('./directory/voiceTracker');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
],
partials: [Partials.Channel],
});
async function registerCommands() {
const commands = [
new SlashCommandBuilder()
.setName('refresh')
.setDescription('Force-refresh the server directory embed'),
new SlashCommandBuilder()
.setName('whereis')
.setDescription('Find out about a channel and check if you can access it')
.addChannelOption((option) =>
option.setName('channel').setDescription('Which channel?').setRequired(true)
),
].map((cmd) => cmd.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands }
);
console.log('Slash commands registered.');
}
client.once('ready', async () => {
console.log(`Logged in as ${client.user.tag}`);
await registerCommands();
scheduleDirectoryRefresh(client);
startApi(client);
startKeepAlive();
});
client.on('interactionCreate', async (interaction) => {
await handleInteraction(interaction, client);
});
client.on('voiceStateUpdate', (oldState, newState) => {
handleVoiceStateUpdate(oldState, newState);
refreshDirectory(client);
});
client.login(process.env.DISCORD_TOKEN);
api/
server.js
const express = require('express');
const { getChannelActivity } = require('../directory/refresh');
function startApi(client) {
const app = express();
const port = parseInt(process.env.API_PORT, 10) || 3000;
app.use(express.json());
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', uptime: process.uptime() });
});
app.get('/api/directory', async (req, res) => {
const guild = client.guilds.cache.get(process.env.GUILD_ID);
if (!guild) return res.status(500).json({ error: 'Guild not found' });
const activity = await getChannelActivity(guild);
res.json({ guild: guild.name, channels: activity });
});
app.get('/api/guild', (req, res) => {
const guild = client.guilds.cache.get(process.env.GUILD_ID);
if (!guild) return res.status(500).json({ error: 'Guild not found' });
res.json({
name: guild.name,
memberCount: guild.memberCount,
icon: guild.iconURL({ size: 256 }),
channelCount: guild.channels.cache.size,
});
});
app.listen(port, () => {
console.log(`API running on http://localhost:${port}`);
});
}
module.exports = { startApi };
keepAlive.js
function startKeepAlive() {
const url = process.env.RENDER_EXTERNAL_URL || process.env.KEEP_ALIVE_URL;
if (!url) {
console.log('No KEEP_ALIVE_URL set — keep-alive disabled.');
return;
}
const interval = 14 * 60 * 1000;
setInterval(async () => {
try {
const res = await fetch(`${url}/api/health`);
if (res.ok) console.log(`Keep-alive ping OK (${new Date().toISOString()})`);
} catch (err) {
console.error('Keep-alive ping failed:', err.message);
}
}, interval);
console.log(`Keep-alive pinging ${url}/api/health every 14 minutes.`);
}
module.exports = { startKeepAlive };
commands/
deploy.js
require('dotenv').config();
const { REST, Routes, SlashCommandBuilder } = require('discord.js');
const commands = [
new SlashCommandBuilder()
.setName('refresh')
.setDescription('Force-refresh the server directory embed'),
new SlashCommandBuilder()
.setName('whereis')
.setDescription('Find out about a channel and check if you can access it')
.addChannelOption((option) =>
option.setName('channel').setDescription('Which channel?').setRequired(true)
),
].map((cmd) => cmd.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
(async () => {
console.log('Registering slash commands...');
await rest.put(
Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
{ body: commands }
);
console.log('Done! Commands registered.');
})();
handler.js
const { refreshDirectory } = require('../directory/refresh');
const { PermissionsBitField } = require('discord.js');
async function handleInteraction(interaction, client) {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'refresh') {
await interaction.deferReply({ ephemeral: true });
await refreshDirectory(client);
await interaction.editReply('✅ Directory refreshed!');
}
if (commandName === 'whereis') {
const allowedChannel = process.env.WHEREIS_CHANNEL_ID;
if (allowedChannel && interaction.channel.id !== allowedChannel) {
return interaction.reply({
content: `This command can only be used in <#${allowedChannel}>.`,
ephemeral: true,
});
}
const targetChannel = interaction.options.getChannel('channel');
const member = interaction.member;
const permissions = targetChannel.permissionsFor(member);
const canView = permissions && permissions.has(PermissionsBitField.Flags.ViewChannel);
if (!canView) {
return interaction.reply({
content: `Sorry, you don't have permission to visit **#${targetChannel.name}**. 🔒`,
});
}
let lastActivity = 'No messages yet';
try {
const messages = await targetChannel.messages.fetch({ limit: 1 });
const lastMsg = messages.first();
if (lastMsg) {
const timestamp = Math.floor(lastMsg.createdTimestamp / 1000);
lastActivity = `<@${lastMsg.author.id}> — <t:${timestamp}:R>`;
}
} catch { lastActivity = 'Could not fetch messages'; }
const category = targetChannel.parent?.name || 'No category';
const topic = targetChannel.topic || 'No topic set';
return interaction.reply({
content: `**Channel:** <#${targetChannel.id}>\n**Category:** ${category}\n**Topic:** ${topic}\n**Last activity:** ${lastActivity}`
});
}
}
module.exports = { handleInteraction };
directory/
embed.js
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, time, TimestampStyles } = require('discord.js');
function formatDuration(ms) {
if (!ms || ms <= 0) return '0m';
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
if (hours > 0) return `${hours}h ${minutes}m`;
if (minutes > 0) return `${minutes}m`;
return `${totalSeconds}s`;
}
function buildDirectoryEmbed(activity) {
const color = parseInt((process.env.EMBED_COLOR || '#FFD700').replace('#', ''), 16);
const embed = new EmbedBuilder()
.setTitle('📂 Server Directory')
.setDescription('All channels at a glance. See who spoke last and how long ago.')
.setColor(color)
.setTimestamp()
.setFooter({ text: 'Last updated' });
if (process.env.EMBED_LINK_URL) embed.setURL(process.env.EMBED_LINK_URL);
if (process.env.EMBED_THUMBNAIL_URL) embed.setThumbnail(process.env.EMBED_THUMBNAIL_URL);
if (process.env.EMBED_IMAGE_URL) embed.setImage(process.env.EMBED_IMAGE_URL);
const categories = {};
for (const entry of activity) {
const cat = entry.categoryName;
if (!categories[cat]) categories[cat] = { position: entry.categoryPosition, channels: [] };
categories[cat].channels.push(entry);
}
const sorted = Object.entries(categories).sort((a, b) => a[1].position - b[1].position);
for (const [categoryName, { channels }] of sorted) {
const lines = channels.map((ch) => {
if (ch.type === 'voice') {
if (ch.isActive) return `🔊 <#${ch.channelId}> — **${ch.memberCount}** in call`;
if (ch.endedAt) {
const endedTime = time(Math.floor(ch.endedAt / 1000), TimestampStyles.RelativeTime);
return `🔇 <#${ch.channelId}> — ended ${endedTime} (${formatDuration(ch.duration)})`;
}
return `🔇 <#${ch.channelId}> — *No recent calls*`;
}
if (!ch.lastMessageTimestamp) return `💬 <#${ch.channelId}> — *No messages yet*`;
const relativeTime = time(Math.floor(ch.lastMessageTimestamp / 1000), TimestampStyles.RelativeTime);
return `💬 <#${ch.channelId}> — <@${ch.lastAuthorId}> ${relativeTime}`;
});
embed.addFields({ name: `📁 ${categoryName}`, value: lines.join('\n') || 'Empty' });
}
return embed;
}
function buildDirectoryComponents() {
const components = [];
if (process.env.EMBED_LINK_URL) {
const label = process.env.EMBED_LINK_LABEL || 'Visit Link';
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel(label).setStyle(ButtonStyle.Link)
.setURL(process.env.EMBED_LINK_URL).setEmoji('🔗')
);
components.push(row);
}
return components;
}
module.exports = { buildDirectoryEmbed, buildDirectoryComponents };
refresh.js
const { buildDirectoryEmbed, buildDirectoryComponents } = require('./embed');
const { getVoiceActivity } = require('./voiceTracker');
let directoryMessageId = process.env.DIRECTORY_MESSAGE_ID || null;
async function getChannelActivity(guild) {
const hiddenCategories = (process.env.HIDDEN_CATEGORY_IDS || '')
.split(',').map((id) => id.trim()).filter(Boolean);
const textChannels = guild.channels.cache
.filter((ch) => ch.isTextBased() && !ch.isThread() && !ch.isVoiceBased())
.filter((ch) => !hiddenCategories.includes(ch.parentId))
.sort((a, b) => a.position - b.position);
const voiceChannels = guild.channels.cache
.filter((ch) => ch.isVoiceBased() && !ch.isThread())
.filter((ch) => !hiddenCategories.includes(ch.parentId))
.sort((a, b) => a.position - b.position);
const activity = [];
for (const [, channel] of textChannels) {
try {
const messages = await channel.messages.fetch({ limit: 1 });
const lastMsg = messages.first();
activity.push({
type: 'text', channelId: channel.id, channelName: channel.name,
categoryName: channel.parent?.name || 'No Category',
categoryPosition: channel.parent?.position ?? -1,
lastAuthorId: lastMsg?.author?.id || null,
lastMessageTimestamp: lastMsg?.createdTimestamp || null,
});
} catch {}
}
for (const [, channel] of voiceChannels) {
const voiceInfo = getVoiceActivity(channel.id, channel);
activity.push({
type: 'voice', channelId: channel.id, channelName: channel.name,
categoryName: channel.parent?.name || 'No Category',
categoryPosition: channel.parent?.position ?? -1,
...voiceInfo,
});
}
return activity;
}
async function refreshDirectory(client) {
const guild = client.guilds.cache.get(process.env.GUILD_ID);
if (!guild) return;
const directoryChannel = guild.channels.cache.get(process.env.DIRECTORY_CHANNEL_ID);
if (!directoryChannel) return;
const activity = await getChannelActivity(guild);
const embed = buildDirectoryEmbed(activity);
const components = buildDirectoryComponents();
if (directoryMessageId) {
try {
const existing = await directoryChannel.messages.fetch(directoryMessageId);
await existing.edit({ embeds: [embed], components });
return;
} catch (err) { return; }
}
const sent = await directoryChannel.send({ embeds: [embed], components });
directoryMessageId = sent.id;
console.log(`New directory message: ${sent.id}`);
}
function scheduleDirectoryRefresh(client) {
const cooldownMs = parseInt(process.env.REFRESH_COOLDOWN_SECONDS, 10) * 1000 || 10000;
const fallbackMinutes = parseInt(process.env.REFRESH_INTERVAL, 10) || 15;
let lastRefresh = 0;
let pendingTimeout = null;
refreshDirectory(client);
client.on('messageCreate', (message) => {
if (!message.guild) return;
if (message.channel.id === process.env.DIRECTORY_CHANNEL_ID) return;
const now = Date.now();
if (now - lastRefresh >= cooldownMs) {
lastRefresh = now;
refreshDirectory(client);
} else if (!pendingTimeout) {
const remaining = cooldownMs - (now - lastRefresh);
pendingTimeout = setTimeout(() => {
pendingTimeout = null;
lastRefresh = Date.now();
refreshDirectory(client);
}, remaining);
}
});
setInterval(() => refreshDirectory(client), fallbackMinutes * 60 * 1000);
}
module.exports = { scheduleDirectoryRefresh, refreshDirectory, getChannelActivity };
voiceTracker.js
const activeCalls = new Map();
const lastCalls = new Map();
function handleVoiceStateUpdate(oldState, newState) {
const leftChannel = oldState.channel;
const joinedChannel = newState.channel;
if (joinedChannel) {
const memberCount = joinedChannel.members.size;
if (!activeCalls.has(joinedChannel.id)) {
activeCalls.set(joinedChannel.id, { startedAt: Date.now(), memberCount });
} else {
activeCalls.get(joinedChannel.id).memberCount = memberCount;
}
}
if (leftChannel) {
const memberCount = leftChannel.members.size;
if (memberCount === 0) {
const session = activeCalls.get(leftChannel.id);
const endedAt = Date.now();
const duration = session ? endedAt - session.startedAt : 0;
lastCalls.set(leftChannel.id, { endedAt, duration });
activeCalls.delete(leftChannel.id);
} else if (activeCalls.has(leftChannel.id)) {
activeCalls.get(leftChannel.id).memberCount = memberCount;
}
}
}
function getVoiceActivity(channelId, channel) {
const active = activeCalls.get(channelId);
if (active || channel.members.size > 0) {
const memberCount = channel.members.size;
if (memberCount > 0 && !active) {
activeCalls.set(channelId, { startedAt: Date.now(), memberCount });
}
return { isActive: true, memberCount: memberCount || active?.memberCount || 0, startedAt: active?.startedAt || Date.now() };
}
const last = lastCalls.get(channelId);
if (last) return { isActive: false, endedAt: last.endedAt, duration: last.duration };
return { isActive: false, endedAt: null, duration: null };
}
module.exports = { handleVoiceStateUpdate, getVoiceActivity };