forked from Ilshidur/action-discord
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
entrypoint.js
92 lines (81 loc) · 2.65 KB
/
entrypoint.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const axios = require('axios');
const fs = require('fs');
const _ = require('lodash');
const { argv } = require('yargs');
const REQUIRED_ENV_VARS = [
'GITHUB_EVENT_PATH',
'GITHUB_REPOSITORY',
'GITHUB_WORKFLOW',
'GITHUB_ACTOR',
'GITHUB_EVENT_NAME',
'GITHUB_ACTION',
'DISCORD_WEBHOOK'
];
process.env.GITHUB_ACTION = process.env.GITHUB_ACTION || '<missing GITHUB_ACTION env var>';
REQUIRED_ENV_VARS.forEach(env => {
if (!process.env[env] || !process.env[env].length) {
console.error(
`Env var ${env} is not defined. Maybe try to set it if you are running the script manually.`
);
process.exit(1);
}
});
const eventContent = fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8');
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
let url;
let payload;
let threadId;
if (process.env.DISCORD_THREAD_ID) {
threadId = process.env.DISCORD_THREAD_ID;
}
if (argv._.length === 0 && !process.env.DISCORD_EMBEDS) {
// If argument and embeds NOT provided, let Discord show the event informations.
url = `${process.env.DISCORD_WEBHOOK}/github`;
payload = JSON.stringify(JSON.parse(eventContent));
} else {
// Otherwise, if the argument or embeds are provided, let Discord override the message.
const args = argv._.join(' ');
const message = _.template(args)({ ...process.env, EVENT_PAYLOAD: JSON.parse(eventContent) });
let embedsObject;
if (process.env.DISCORD_EMBEDS) {
try {
embedsObject = JSON.parse(process.env.DISCORD_EMBEDS);
} catch (parseErr) {
console.error('Error parsing DISCORD_EMBEDS :' + parseErr);
process.exit(1);
}
}
url = process.env.DISCORD_WEBHOOK;
payload = JSON.stringify({
content: message,
...process.env.DISCORD_EMBEDS && { embeds: embedsObject },
...process.env.DISCORD_USERNAME && { username: process.env.DISCORD_USERNAME },
...process.env.DISCORD_AVATAR && { avatar_url: process.env.DISCORD_AVATAR },
});
}
// curl -X POST -H "Content-Type: application/json" --data "$(cat $GITHUB_EVENT_PATH)" $DISCORD_WEBHOOK/github
(async () => {
console.log('Sending message ...');
let finalUrl;
if (threadId) {
finalUrl = `${url}?wait=true&thread_id=${threadId}`
} else {
finalUrl = `${url}?wait=true`;
}
await axios.post(
finalUrl,
payload,
{
headers: {
'Content-Type': 'application/json',
'X-GitHub-Event': process.env.GITHUB_EVENT_NAME,
},
},
);
console.log('Message sent ! Shutting down ...');
process.exit(0);
})().catch(err => {
console.error('Error :', err.response.status, err.response.statusText);
console.error('Message :', err.response ? err.response.data : err.message);
process.exit(1);
});