forked from slack-samples/deno-github-functions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics.ts
More file actions
208 lines (183 loc) · 6.54 KB
/
analytics.ts
File metadata and controls
208 lines (183 loc) · 6.54 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
/**
* Módulo de analytics para monitorar o uso do bot.
*/
interface CommandLog {
timestamp: string;
command: string;
user_id: string;
response_time_ms: number;
success: boolean;
error?: string;
}
interface DailyStats {
commands: number;
avg_time: number;
}
interface AnalyticsData {
commands: Record<string, number>;
response_times: CommandLog[];
errors: Record<string, number>;
daily_stats: Record<string, DailyStats>;
last_updated: string;
}
export class BotAnalytics {
private dataFile: string;
private data: AnalyticsData;
constructor(dataFile = "analytics_data.json") {
this.dataFile = dataFile;
this.data = this.loadData();
}
private loadData(): AnalyticsData {
try {
const content = Deno.readTextFileSync(this.dataFile);
return JSON.parse(content);
} catch {
return {
commands: {},
response_times: [],
errors: {},
daily_stats: {},
last_updated: new Date().toISOString(),
};
}
}
private saveData(): void {
const dataToSave: AnalyticsData = {
commands: this.data.commands,
response_times: this.data.response_times.slice(-1000), // Manter últimos 1000
errors: this.data.errors,
daily_stats: this.data.daily_stats,
last_updated: new Date().toISOString(),
};
Deno.writeTextFileSync(this.dataFile, JSON.stringify(dataToSave, null, 2));
}
logCommand(
commandType: string,
userId: string,
responseTimeMs: number,
success = true,
error?: string
): void {
const timestamp = new Date();
// Contador de comandos
this.data.commands[commandType] = (this.data.commands[commandType] || 0) + 1;
// Tempo de resposta
this.data.response_times.push({
timestamp: timestamp.toISOString(),
command: commandType,
user_id: userId,
response_time_ms: responseTimeMs,
success,
error,
});
// Erros
if (!success && error) {
this.data.errors[error] = (this.data.errors[error] || 0) + 1;
}
// Estatísticas diárias
const dayKey = timestamp.toISOString().split("T")[0];
const dayStats = this.data.daily_stats[dayKey] || { commands: 0, avg_time: 0 };
dayStats.commands += 1;
dayStats.avg_time = (dayStats.avg_time * (dayStats.commands - 1) + responseTimeMs) / dayStats.commands;
this.data.daily_stats[dayKey] = dayStats;
this.saveData();
}
getSummary(days = 7): Record<string, unknown> {
const now = new Date();
const since = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
const recentCommands = this.data.response_times.filter(
(rt) => new Date(rt.timestamp) > since
);
if (recentCommands.length === 0) {
return { message: "Nenhum dado disponível para o período" };
}
const totalCommands = Object.values(this.data.commands).reduce((a, b) => a + b, 0);
const avgResponseTime = this.data.response_times.reduce((sum, rt) => sum + rt.response_time_ms, 0) / this.data.response_times.length;
const topCommands = Object.entries(this.data.commands)
.sort((a, b) => b[1] - a[1])
.slice(0, 5);
const totalErrors = Object.values(this.data.errors).reduce((a, b) => a + b, 0);
const successRate = totalCommands > 0 ? ((totalCommands - totalErrors) / totalCommands) * 100 : 100;
return {
period: `${days} dias`,
total_commands: totalCommands,
recent_commands: recentCommands.length,
avg_response_time_ms: Math.round(avgResponseTime * 100) / 100,
top_commands: Object.fromEntries(topCommands),
total_errors: totalErrors,
success_rate: Math.round(successRate * 100) / 100,
};
}
getDashboardHtml(): string {
const summary = this.getSummary();
const topCommandsEntries = Object.entries((summary as { top_commands: Record<string, number> }).top_commands || {});
return `
<!DOCTYPE html>
<html>
<head>
<title>Bot Analytics Dashboard - Deno</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; }
.card { background: white; padding: 20px; margin: 10px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; }
.stat-value { font-size: 2em; color: #4A154B; font-weight: bold; }
.stat-label { color: #666; margin-top: 5px; }
h1 { color: #4A154B; }
h2 { color: #333; border-bottom: 2px solid #4A154B; padding-bottom: 10px; }
table { width: 100%; border-collapse: collapse; margin-top: 10px; }
th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
th { background: #4A154B; color: white; }
tr:hover { background: #f5f5f5; }
.success { color: green; }
.warning { color: orange; }
</style>
</head>
<body>
<div class="container">
<h1>🤖 Slack Bot Analytics Dashboard (Deno)</h1>
<p>Última atualização: ${this.data.last_updated}</p>
<div class="card">
<h2>📊 Resumo (${summary.period || "N/A"})</h2>
<div class="stats">
<div class="card">
<div class="stat-value">${summary.total_commands || 0}</div>
<div class="stat-label">Total de Comandos</div>
</div>
<div class="card">
<div class="stat-value">${summary.avg_response_time_ms || 0}ms</div>
<div class="stat-label">Tempo Médio de Resposta</div>
</div>
<div class="card">
<div class="stat-value success">${summary.success_rate || 100}%</div>
<div class="stat-label">Taxa de Sucesso</div>
</div>
<div class="card">
<div class="stat-value warning">${summary.total_errors || 0}</div>
<div class="stat-label">Total de Erros</div>
</div>
</div>
</div>
<div class="card">
<h2>🔥 Comandos Mais Populares</h2>
<table>
<tr>
<th>Comando</th>
<th>Execuções</th>
</tr>
${topCommandsEntries.map(([cmd, count]) => `
<tr>
<td>${cmd}</td>
<td>${count}</td>
</tr>
`).join("")}
</table>
</div>
</div>
</body>
</html>
`;
}
}
// Instância global
export const analytics = new BotAnalytics();