-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
223 lines (205 loc) · 6.63 KB
/
index.js
File metadata and controls
223 lines (205 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
require("dotenv").config();
const fetch = require("node-fetch");
// Configuration
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL;
const FATHOM_API_TOKEN = process.env.FATHOM_API_TOKEN;
const REACTFLOW_SITE_ID = process.env.REACTFLOW_SITE_ID;
const SVELTEFLOW_SITE_ID = process.env.SVELTEFLOW_SITE_ID;
// Date range helpers
function getPreviousWeekRange() {
const now = new Date();
let isoDay = now.getUTCDay();
if (isoDay === 0) isoDay = 7;
const currentMonday = new Date(now);
currentMonday.setUTCDate(now.getUTCDate() - (isoDay - 1));
const prevMonday = new Date(currentMonday);
prevMonday.setUTCDate(currentMonday.getUTCDate() - 7);
const prevSunday = new Date(prevMonday);
prevSunday.setUTCDate(prevMonday.getUTCDate() + 6);
return { start: prevMonday, end: prevSunday };
}
function getWeekBeforeRange() {
const lastWeek = getPreviousWeekRange();
const start = new Date(lastWeek.start);
start.setUTCDate(start.getUTCDate() - 7);
const end = new Date(lastWeek.end);
end.setUTCDate(end.getUTCDate() - 7);
return { start, end };
}
function formatDate(date) {
return (
date.getUTCFullYear() +
"-" +
String(date.getUTCMonth() + 1).padStart(2, "0") +
"-" +
String(date.getUTCDate()).padStart(2, "0") +
" " +
String(date.getUTCHours()).padStart(2, "0") +
":" +
String(date.getUTCMinutes()).padStart(2, "0") +
":" +
String(date.getUTCSeconds()).padStart(2, "0")
);
}
// Fetch Fathom data
async function fetchAggregation(params) {
const url = `https://api.usefathom.com/v1/aggregations?${params.toString()}`;
const response = await fetch(url, {
method: "GET",
headers: { Authorization: `Bearer ${FATHOM_API_TOKEN}` },
});
if (!response.ok) throw new Error(`API Error: ${response.statusText}`);
return response.json();
}
// Generate the report for a specific site
async function generateSiteReport(siteId, siteName) {
try {
const lastWeek = getPreviousWeekRange();
const weekBefore = getWeekBeforeRange();
const date_from_last = formatDate(lastWeek.start);
const date_to_last = formatDate(lastWeek.end);
const date_from_before = formatDate(weekBefore.start);
const date_to_before = formatDate(weekBefore.end);
// Fetch popular pages for last week
const popParamsLast = new URLSearchParams({
entity: "pageview",
entity_id: siteId,
aggregates: "pageviews",
field_grouping: "pathname",
sort_by: "pageviews:desc",
limit: "15",
date_from: date_from_last,
date_to: date_to_last,
timezone: "UTC",
});
const lastPages = (await fetchAggregation(popParamsLast)) || [];
// Fetch popular pages for week before last
const popParamsBefore = new URLSearchParams({
entity: "pageview",
entity_id: siteId,
aggregates: "pageviews",
field_grouping: "pathname",
sort_by: "pageviews:desc",
limit: "15",
date_from: date_from_before,
date_to: date_to_before,
timezone: "UTC",
});
const beforePages = (await fetchAggregation(popParamsBefore)) || [];
const beforeMap = new Map();
beforePages.forEach((page) => {
if (page.pathname) beforeMap.set(page.pathname, Number(page.pageviews));
});
// Fetch total hits for last week
const totParamsLast = new URLSearchParams({
entity: "pageview",
entity_id: siteId,
aggregates: "pageviews",
date_from: date_from_last,
date_to: date_to_last,
timezone: "UTC",
});
const totalLastData = await fetchAggregation(totParamsLast);
const totalLast =
totalLastData && totalLastData[0] && totalLastData[0].pageviews
? Number(totalLastData[0].pageviews)
: 0;
// Fetch total hits for week before last
const totParamsBefore = new URLSearchParams({
entity: "pageview",
entity_id: siteId,
aggregates: "pageviews",
date_from: date_from_before,
date_to: date_to_before,
timezone: "UTC",
});
const totalBeforeData = await fetchAggregation(totParamsBefore);
const totalBefore =
totalBeforeData && totalBeforeData[0] && totalBeforeData[0].pageviews
? Number(totalBeforeData[0].pageviews)
: 0;
// Calculate changes
const totalDelta = totalLast - totalBefore;
const totalDeltaSign = totalDelta > 0 ? "+" : "";
return {
title: `${siteName} Traffic Report`,
fields: [
{
name: "🌐 Total Pageviews",
value: `${totalLast.toLocaleString()} (${totalDeltaSign}${totalDelta.toLocaleString()})`,
inline: true,
},
{
name: "📅 Date Range",
value: `${date_from_last.split(" ")[0]} to ${
date_to_last.split(" ")[0]
}`,
inline: true,
},
{
name: "🔝 Top Pages",
value: lastPages
.slice(0, 15)
.map((page) => {
const lastViews = Number(page.pageviews);
const prevViews = beforeMap.get(page.pathname) || 0;
const delta = lastViews - prevViews;
const deltaSign = delta > 0 ? "+" : "";
return `→ ${
page.pathname
}: ${lastViews.toLocaleString()} (${deltaSign}${delta.toLocaleString()})`;
})
.join("\n"),
},
],
};
} catch (error) {
throw new Error(
`Failed to generate report for ${siteName}: ${error.message}`
);
}
}
// Generate combined report for both sites
async function generateReport() {
try {
const reactflowEmbed = await generateSiteReport(
REACTFLOW_SITE_ID,
"reactflow.dev"
);
const svelteflowEmbed = await generateSiteReport(
SVELTEFLOW_SITE_ID,
"svelteflow.dev"
);
// Compile the final message with both sites as separate embeds
const message = {
username: "weekly fathom roundup bot",
embeds: [reactflowEmbed, svelteflowEmbed],
};
return message;
} catch (error) {
return {
username: "Traffic Bot - Error",
content: `❌ Failed to generate report: ${error.message}`,
};
}
}
// Send to Discord via webhook
async function sendWebhook(message) {
try {
const response = await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(message),
});
if (!response.ok) throw new Error(`Webhook failed: ${response.status}`);
console.log("✅ Report sent successfully");
} catch (error) {
console.error("❌ Webhook error:", error);
}
}
// Schedule and run
async function runScheduledReport() {
const report = await generateReport();
await sendWebhook(report);
}
runScheduledReport();