Files
config.json
index.js
package.json
README.md
Code
4 495
index.js
'use strict';
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField } = require('discord.js');
const axios = require('axios');
const Database = require('better-sqlite3');
const fs = require('fs');
// ─── CONFIG ────────────────────────────────────────────────────────────────
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
const PANEL_URL = config.pterodactyl.panelUrl.replace(/\/$/, '');
const API_KEY = config.pterodactyl.apiKey;
const TOKEN = config.token;
const EMOJI_ONLINE_SUMMARY = '<a:Online1:1499292890143395862>';
const EMOJI_OFFLINE = '<:OFFLINE:1499298170122014852>';
const EMBED_COLOR = 0x2b2d31;
const REFRESH_MS = 15_000;
// ─── DATABASE ──────────────────────────────────────────────────────────────
const db = new Database('./titan_monitor.db');
db.pragma('journal_mode = WAL');
db.exec(`
CREATE TABLE IF NOT EXISTS uptime (
entity_id TEXT PRIMARY KEY,
total_checks INTEGER DEFAULT 0,
successful_checks INTEGER DEFAULT 0,
first_seen INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS state (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
`);
const stmtEnsure = db.prepare(
`INSERT OR IGNORE INTO uptime (entity_id, total_checks, successful_checks, first_seen)
VALUES (?, 0, 0, ?)`
);
const stmtRecord = db.prepare(
`UPDATE uptime SET total_checks = total_checks + 1, successful_checks = successful_checks + ? WHERE entity_id = ?`
);
const stmtGetRow = db.prepare(`SELECT * FROM uptime WHERE entity_id = ?`);
const stmtAllRows = db.prepare(`SELECT * FROM uptime`);
const stmtGetState = db.prepare(`SELECT value FROM state WHERE key = ?`);
const stmtSetState = db.prepare(`INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)`);
function recordCheck(id, success) {
stmtEnsure.run(id, Date.now());
stmtRecord.run(success ? 1 : 0, id);
}
function uptimeDuration(id) {
const row = stmtGetRow.get(id);
if (!row) return '0d 0h 0m';
const ms = Date.now() - row.first_seen;
const d = Math.floor(ms / 86_400_000);
const h = Math.floor((ms % 86_400_000) / 3_600_000);
const m = Math.floor((ms % 3_600_000) / 60_000);
return `${d}d ${h}h ${m}m`;
}
function getCumulativeUptime() {
const rows = stmtAllRows.all();
if (!rows.length) return '0.00';
const total = rows.reduce((s, r) => s + r.total_checks, 0);
const success = rows.reduce((s, r) => s + r.successful_checks, 0);
if (total === 0) return '0.00';
return ((success / total) * 100).toFixed(2);
}
function getState(key) { const r = stmtGetState.get(key); return r ? r.value : null; }
function setState(key, value) { stmtSetState.run(key, String(value)); }
// ─── AXIOS INSTANCE ────────────────────────────────────────────────────────
const panelApi = axios.create({
baseURL: `${PANEL_URL}/api/application`,
headers: {
Authorization: `Bearer ${API_KEY}`,
Accept: 'application/json',
'Content-Type': 'application/json'
},
timeout: 10_000
});
// ─── POLL HELPERS ──────────────────────────────────────────────────────────
async function checkPanel() {
const t0 = Date.now();
try {
await axios.get(PANEL_URL, { timeout: 8_000 });
return { online: true, ping: Date.now() - t0 };
} catch (err) {
// A non-2xx response still means the panel is reachable
if (err.response) return { online: true, ping: Date.now() - t0 };
return { online: false, ping: null };
}
}
async function fetchAllNodes() {
try {
const res = await panelApi.get('/nodes?per_page=100');
return res.data.data ?? [];
} catch (err) {
console.error(`[API] fetchAllNodes failed: ${err.message}`);
return [];
}
}
async function checkNodeDaemon(node) {
const { fqdn, daemon_listen: port = 8080, scheme = 'https' } = node.attributes;
const t0 = Date.now();
try {
await axios.get(`${scheme}://${fqdn}:${port}`, { timeout: 8_000 });
return { online: true, ping: Date.now() - t0 };
} catch (err) {
if (err.response) return { online: true, ping: Date.now() - t0 };
return { online: false, ping: null };
}
}
async function fetchTotalServers() {
try {
const res = await panelApi.get('/servers?per_page=1');
const meta = res.data.meta?.pagination;
return meta ? meta.total : res.data.data.length;
} catch (err) {
console.error(`[API] fetchTotalServers failed: ${err.message}`);
return null;
}
}
async function pollAll() {
const [panelResult, rawNodes, totalServers] = await Promise.all([
checkPanel(),
fetchAllNodes(),
fetchTotalServers()
]);
recordCheck('panel', panelResult.online);
const daemonResults = await Promise.all(rawNodes.map(n => checkNodeDaemon(n)));
const nodes = rawNodes.map((n, i) => {
const daemon = daemonResults[i];
const entityId = `node_${n.attributes.id}`;
recordCheck(entityId, daemon.online);
return {
label: `Node ${i + 1}`,
entityId,
online: daemon.online,
ping: daemon.ping
};
});
return { panel: panelResult, nodes, totalServers };
}
// ─── EMBED BUILDER ─────────────────────────────────────────────────────────
function pad(str, len) {
return String(str).padEnd(len);
}
function buildEmbed({ panel, nodes, totalServers }) {
const onlineNodes = nodes.filter(n => n.online).length;
const offlineNodes = nodes.length - onlineNodes;
// Estimate online/offline servers proportionally across online/offline nodes
const totalSvr = totalServers !== null ? totalServers : '?';
const onlineSvr = totalServers !== null
? Math.round(totalServers * (onlineNodes / Math.max(nodes.length, 1)))
: '?';
const offlineSvr = totalServers !== null ? totalSvr - onlineSvr : '?';
const panelStatus = panel.online ? 'ONLINE' : `${EMOJI_OFFLINE} OFFLINE`;
const panelPing = panel.online && panel.ping !== null ? `${panel.ping}ms` : '—';
const panelUptime = uptimeDuration('panel');
// Each service row
const panelRow = `🖥️ **Panel** \`${pad(panelStatus, 9)}\` \`${pad(panelUptime, 12)}\` \`${panelPing}\` 📶`;
const nodeRows = nodes.map(node => {
const status = node.online ? 'ONLINE' : `${EMOJI_OFFLINE} OFFLINE`;
const ping = node.online && node.ping !== null ? `${node.ping}ms` : '—';
const uptime = uptimeDuration(node.entityId);
return `🖥️ **${node.label}** \`${pad(status, 9)}\` \`${pad(uptime, 12)}\` \`${ping}\` 📶`;
}).join('\n\n');
const cumulative = getCumulativeUptime();
const nowUnix = Math.floor(Date.now() / 1000);
const lines = [
'```',
'SERVICE STATUS UPTIME RESPONSE',
'```',
panelRow,