Plausible analytics reports to Discord (migration 065)

Daily (yesterday) and weekly (Mondays, last 7 days vs the 7 before)
summaries: visitors, pageviews, bounce rate, visit length, top pages
and sources. Each has its own switch in Site settings > Reports; off
until PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL are set. Sent at 8:00
REPORT_TZ (default America/Chicago); analytics_reports keeps one a day.
node src/analyticsReport.js daily|weekly sends one by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-10-04 21:44:25 -05:00
parent b8012c75e9
commit 636388730f
6 changed files with 254 additions and 1 deletions

View file

@ -34,6 +34,8 @@ export const siteSettings = {
text("access_group_viewer"),
text("access_group_editor"),
text("access_group_admin"),
enumeration("report_daily", ["on", "off"]),
enumeration("report_weekly", ["on", "off"]),
],
children: [

View file

@ -0,0 +1,203 @@
/* ═══════════════════════════════════════════════════════════════
ANALYTICS REPORTS
Plausible's numbers for this site, posted to a Discord channel:
daily yesterday: visitors, pageviews, bounce rate, visit
length, top pages and sources
weekly Mondays: the last 7 days, with the change from the 7
before
Each is switched on in Panel → Site settings → Reports. Both go
out at SEND_HOUR in REPORT_TZ, or as soon after as the server is
up that day; analytics_reports (065) keeps it to one a day.
── Configuration (the ngu-api service environment) ──
PLAUSIBLE_API_KEY a Stats API key (Plausible → Account
settings → API keys)
DISCORD_WEBHOOK_URL the channel's webhook (Discord → channel
settings → Integrations → Webhooks)
PLAUSIBLE_URL default http://127.0.0.1:8000, where the
self-hosted Plausible listens
REPORT_TZ default America/Chicago
Off until the first two are set. The site counted is the hostname
of site.json's url, as in pageMeta.js's analyticsTag.
To send one now (eg. to try the setup), whatever the switches say:
DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly
═══════════════════════════════════════════════════════════════ */
import { pathToFileURL } from "node:url";
import { siteFor } from "./pageMeta.js";
const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, "");
const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null;
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null;
const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago";
const SEND_HOUR = 8;
const TICK_MS = 15 * 60 * 1000;
const KINDS = ["daily", "weekly"];
export const reportsReady = () => Boolean(PLAUSIBLE_API_KEY && DISCORD_WEBHOOK_URL);
/* Today's date and the hour in REPORT_TZ, and whether it's Monday. */
function localNow(now = new Date()) {
const parts = Object.fromEntries(
new Intl.DateTimeFormat("en-US", {
timeZone: REPORT_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
hourCycle: "h23",
weekday: "short",
})
.formatToParts(now)
.map((part) => [part.type, part.value]),
);
return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), monday: parts.weekday === "Mon" };
}
/* "2026-10-04" moved by `days`. */
function shift(date, days) {
const d = new Date(`${date}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
/* ── Plausible ─────────────────────────────────────────────── */
async function query(siteId, body) {
const res = await fetch(`${PLAUSIBLE_URL}/api/v2/query`, {
method: "POST",
headers: { Authorization: `Bearer ${PLAUSIBLE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ site_id: siteId, ...body }),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Plausible answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
return (await res.json()).results ?? [];
}
const METRICS = ["visitors", "pageviews", "bounce_rate", "visit_duration"];
async function totals(siteId, range) {
const [row] = await query(siteId, { metrics: METRICS, date_range: range });
return Object.fromEntries(METRICS.map((metric, i) => [metric, row?.metrics[i] ?? 0]));
}
async function top(siteId, dimension, range, limit) {
const rows = await query(siteId, {
metrics: ["visitors"],
dimensions: [dimension],
date_range: range,
order_by: [["visitors", "desc"]],
pagination: { limit },
});
return rows.length ? rows.map((r) => `${r.dimensions[0]}: ${r.metrics[0]}`).join("\n") : "-";
}
/* ── The message ───────────────────────────────────────────── */
const duration = (seconds) => `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
function change(now, before) {
if (!before) return now ? " (new)" : "";
const percent = Math.round(((now - before) / before) * 100);
return ` (${percent >= 0 ? "+" : ""}${percent}%)`;
}
/* The Discord message for `kind` as of `today` (a REPORT_TZ date):
yesterday, or the 7 days ending yesterday. */
export async function buildReport(db, kind, today) {
const siteId = new URL(siteFor(db).url).hostname;
const to = shift(today, -1);
const from = kind === "weekly" ? shift(to, -6) : to;
const range = [from, to];
const limit = kind === "weekly" ? 5 : 3;
const [now, before, pages, sources] = await Promise.all([
totals(siteId, range),
kind === "weekly" ? totals(siteId, [shift(from, -7), shift(to, -7)]) : null,
top(siteId, "event:page", range, limit),
top(siteId, "visit:source", range, limit),
]);
const vs = (metric) => (before ? change(now[metric], before[metric]) : "");
return {
embeds: [
{
title: kind === "weekly" ? `${siteId}: week of ${from} to ${to}` : `${siteId}: ${to}`,
fields: [
{ name: "Visitors", value: `${now.visitors}${vs("visitors")}`, inline: true },
{ name: "Pageviews", value: `${now.pageviews}${vs("pageviews")}`, inline: true },
{ name: "Bounce rate", value: `${now.bounce_rate}%`, inline: true },
{ name: "Visit length", value: duration(now.visit_duration), inline: true },
{ name: "Top pages", value: pages },
{ name: "Top sources", value: sources },
],
},
],
};
}
export async function sendReport(db, kind, today = localNow().date) {
const res = await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(await buildReport(db, kind, today)),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Discord answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
}
/* ── Schedule ──────────────────────────────────────────────── */
export function startAnalyticsReports(db) {
if (!reportsReady()) return;
let running = false;
const tick = async () => {
const { date, hour, monday } = localNow();
if (running || hour < SEND_HOUR) return;
running = true;
try {
const settings = db.prepare(`SELECT report_daily, report_weekly FROM site_settings WHERE id = 'site'`).get() ?? {};
for (const kind of KINDS) {
if (settings[`report_${kind}`] !== "on" || (kind === "weekly" && !monday)) continue;
if (db.prepare(`SELECT 1 FROM analytics_reports WHERE kind = ? AND sent_for = ?`).get(kind, date)) continue;
// Marked before sending: a Plausible or Discord failure is
// logged once that day, not every tick.
db.prepare(
`INSERT INTO analytics_reports (kind, sent_for) VALUES (?, ?)
ON CONFLICT (kind) DO UPDATE SET sent_for = excluded.sent_for`,
).run(kind, date);
try {
await sendReport(db, kind, date);
console.log(`analytics ${kind} report sent for ${date}`);
} catch (err) {
console.error(`analytics ${kind} report failed: ${err.message}`);
}
}
} finally {
running = false;
}
};
tick();
setInterval(tick, TICK_MS).unref();
}
/* ── By hand ───────────────────────────────────────────────── */
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const kind = process.argv[2];
if (!KINDS.includes(kind)) {
console.error("usage: node src/analyticsReport.js daily|weekly");
process.exit(1);
}
if (!reportsReady()) {
console.error("Set PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL first.");
process.exit(1);
}
const { openDatabase } = await import("./db.js");
const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db");
await sendReport(db, kind);
console.log(`Sent the ${kind} report.`);
}

View file

@ -45,6 +45,7 @@ import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
import { ENTITIES } from "./admin-schema.js";
const HOST = process.env.HOST ?? "127.0.0.1";
@ -241,6 +242,7 @@ app.route("/", pages);
startSessionSweeper(db);
startGroupSync(db);
startClipWorker(db);
startAnalyticsReports(db);
console.log(`clips ${CLIPS_DIR}`);
app.notFound((c) => c.json({ error: "Not found" }, 404));

View file

@ -0,0 +1,19 @@
-- ═══════════════════════════════════════════════════════════════
-- 065 ANALYTICS REPORTS
--
-- Plausible's numbers posted to Discord (server/src/analyticsReport.js).
--
-- site_settings.report_daily 'on': yesterday's numbers each morning
-- site_settings.report_weekly 'on': last week's each Monday morning
-- Blank or 'off': not sent
-- analytics_reports the local date each kind was last sent
-- for, so a restart doesn't post twice
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE site_settings ADD COLUMN report_daily TEXT CHECK (report_daily IN ('on', 'off'));
ALTER TABLE site_settings ADD COLUMN report_weekly TEXT CHECK (report_weekly IN ('on', 'off'));
CREATE TABLE analytics_reports (
kind TEXT PRIMARY KEY CHECK (kind IN ('daily', 'weekly')),
sent_for TEXT NOT NULL
) STRICT;