forked from TomDotBat/youtrack-discord-webhook
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpayload.js
76 lines (67 loc) · 1.87 KB
/
payload.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
65
66
67
68
69
70
71
72
73
74
75
76
const http = require("@jetbrains/youtrack-scripting-api/http");
/**
* Represents an Payload sent by a Discord webhook.
*/
class Payload {
/**
* @constructor
* @param {string} [message] A message that will be put in chat by the webhook.
* @param {string} [username] The username of the webhook sender.
* @param {Embed[]} [embeds] An array of Embeds to send.
*/
constructor(message, username, embeds) {
this._message = message;
this._username = username;
this._embeds = embeds || [];
}
/**
* @param {string} message
*/
set message(message) {
this._message = message;
}
/**
* @param {string} username
*/
set username(username) {
this._username = username;
}
/**
* @param {Embed[]} embeds
*/
set embeds(embeds) {
this._embeds = embeds;
}
/**
* Adds an Embed to the webhook Payload.
* @param {Embed} embed The embed to add.
*/
addEmbed(embed) {
this._embeds.push(embed);
}
/**
* Returns a JSON.stringify friendly object in the format used by Discord.
* @returns {object} Payload as a JSON object.
*/
toJSON() {
return {
content: this._message,
username: this._username,
embeds: this._embeds
};
}
/**
* Sends the payload to a Discord webhook URL
*/
send(webhookUrl) {
let connection = new http.Connection(webhookUrl, null, 2000);
connection.addHeader("Content-Type", "application/json");
try {
let response = connection.postSync("", null, JSON.stringify(this));
if (!response.isSuccess) console.warn("Discord webhook payload failed to send.\n" + response.toString());
} catch (exception) {
console.error(exception);
}
}
}
module.exports = {Payload};