Back to Dev Hub

LookOut

Server Directory Bot — Discord

A custom Discord bot that maintains a live-updating server directory embed. Tracks text & voice channel activity, lets members look up channels with slash commands, and exposes a REST API for website integration.

Step-by-Step Setup

Create a Discord Application

Go to the Discord Developer Portal, create a new application, then add a Bot under the "Bot" tab. Copy your bot token.

Set Up Your Project

Create a new folder, run npm init -y, then install dependencies:
npm install discord.js express dotenv

Create the .env File

Add your bot token, application ID, guild ID, and channel IDs. See the config section in the file explorer below.

Build the Bot Core

Create src/index.js — this sets up the Discord client, registers slash commands on startup, and wires up event listeners.

Build the Directory Embed

Create src/directory/embed.js to build a rich embed grouped by category, showing last activity per channel and voice call status.

Add the Refresh System

Create src/directory/refresh.js — listens for messages and updates the embed live with a cooldown to avoid rate limits.

Track Voice Calls

Create src/directory/voiceTracker.js to monitor who joins/leaves voice channels and log call durations.

Add Slash Commands

Create src/commands/handler.js with /refresh (force update) and /whereis (channel lookup with permission check).

Add the REST API

Create src/api/server.js — an Express server exposing /api/health, /api/directory, and /api/guild endpoints.

Add Keep-Alive (Free Hosting)

Create src/api/keepAlive.js — self-pings the bot's own /api/health endpoint every 14 minutes to prevent Render's free tier from sleeping. Set KEEP_ALIVE_URL in your .env to your deployed URL.

Invite & Run

Generate an invite link with bot + applications.commands scopes, invite to your server, then run npm start.

Source Code Explorer

Click folders to expand, click files to view their source code.

LookOut/
.env
# Discord Bot Token (from Developer Portal) DISCORD_TOKEN=your_bot_token_here CLIENT_ID=000000000000000000 GUILD_ID=000000000000000000 # Channel where the directory embed lives DIRECTORY_CHANNEL_ID=000000000000000000 DIRECTORY_MESSAGE_ID=000000000000000000 # Refresh settings REFRESH_COOLDOWN_SECONDS=10 REFRESH_INTERVAL=5 # API port for website integration API_PORT=3000 # Keep-alive (Render free tier self-ping) KEEP_ALIVE_URL=https://your-bot.onrender.com # Embed customization EMBED_COLOR=#FFD700 EMBED_THUMBNAIL_URL=https://example.com/thumb.png EMBED_IMAGE_URL=https://example.com/banner.png # Categories to hide (comma-separated IDs) HIDDEN_CATEGORY_IDS=000000000000000000 WHEREIS_CHANNEL_ID=000000000000000000 EMBED_LINK_URL=https://example.com/your-link EMBED_LINK_LABEL=Your Link Label
package.json
{ "name": "server-directory-bot", "version": "1.0.0", "description": "Discord bot that maintains a server directory channel with activity info", "main": "src/index.js", "scripts": { "start": "node src/index.js", "dev": "node --watch src/index.js" }, "dependencies": { "discord.js": "14.14.1", "express": "4.18.2", "dotenv": "16.3.1" } }
src/
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], }); // Registers slash commands on startup 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()); // Health check app.get('/api/health', (req, res) => { res.json({ status: 'ok', uptime: process.uptime() }); }); // Get server directory data as JSON 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 }); }); // Get basic guild info 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
/** * Self-ping to prevent Render free tier from spinning down. * Hits the bot's own /api/health endpoint every 14 minutes. */ 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; // 14 minutes 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
/** * Run this file once to register slash commands with Discord. * Usage: node src/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') { // Only allow in the designated channel 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}**. 🔒`, }); } // They can see it — give them the info 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); // Group channels by category 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); } // Sort and build fields 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 {} // Bot doesn't have access — skip } 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); // Initial refresh on boot 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
/** * Tracks voice channel activity — who's in a call, when it started, * and when the last call ended + how long it lasted. */ const activeCalls = new Map(); // channelId -> { startedAt, memberCount } const lastCalls = new Map(); // channelId -> { endedAt, duration } function handleVoiceStateUpdate(oldState, newState) { const leftChannel = oldState.channel; const joinedChannel = newState.channel; // Someone joined a voice 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; } } // Someone left a voice channel 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 };
Free Hosting Options

These platforms offer free tiers perfect for running a Discord bot 24/7.

Join the Community
ThePurpleFox Discord
Support & Demos

Get help setting up the bot, ask questions, and see LookOut in action on a live server.

  • Live bot demos
  • Setup help & support
  • Feature requests & feedback