-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhookHandler.js
64 lines (56 loc) · 2.22 KB
/
webhookHandler.js
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
import "dotenv/config";
import {Webhook, MessageBuilder} from "discord-webhook-node";
import * as gradeNames from "./gradeNames.js";
export const webhooks = {
normal_grades: new Webhook(process.env.DISCORD_WEBHOOK_NORMAL_GRADES),
semestral_grades: new Webhook(process.env.DISCORD_WEBHOOK_SEMESTRAL_GRADES),
errors: new Webhook(process.env.DISCORD_WEBHOOK_ERRORS),
}
/**
* Send embed to discord webhook.
* @param {Webhook} webhook - Webhook object. Get it from **webhooks** const.
* @param {string} title - Title of embed.
* @param {{title: string, content: string}[]} fields - Fields of content.
*/
export function sendEmbed(webhook, title, fields) {
const embed = new MessageBuilder();
embed.setTitle(title);
for(const field of fields) {
embed.addField(field.title, field.content);
}
webhook.send(embed);
}
/**
* Convert diff to discord embed fields
* @param {object} diff - Diff object from **generateDiff()**
* @param {object} gradesBefore - Old grades from **history**. Used to show average change.
*/
export function diffToFields(diff, gradesBefore) {
const fields = [];
for(const subjectName in diff.subjects) {
const subjectData = diff.subjects[subjectName].grades;
let text = "";
for(const gradeName in subjectData) {
const gradeValue = subjectData[gradeName];
if(gradeValue==0) continue;
text += `${gradeValue} ${gradeNames.variant(gradeName, gradeValue)}, `
}
// Remove last comma and space
text = text.slice(0, -2);
const isAverageAvailable = !!diff.subjects[subjectName].average;
// Round current average to 2 decimals
const averageNow = Math.floor(diff.subjects[subjectName].average*100)/100;
// Get previous average from gradesBefore. If it doesn't exist set to 0.
let averageBefore;
if(!gradesBefore || !gradesBefore[subjectName]) {
averageBefore = 0;
} else {
averageBefore = gradesBefore[subjectName].average;
}
if(text.length>0) fields.push({
title: subjectName + (isAverageAvailable ? `(${averageBefore} → ${averageNow})` : ""),
content: text
})
}
return fields;
}