forked from sdslabs/slack-github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
94 lines (78 loc) · 2.23 KB
/
app.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
93
94
/* required dependencies */
var request = require("request");
var express = require("express");
var bodyParser = require("body-parser");
/* app instance */
var app = express();
/* app configurations */
// parse application/json
app.use(bodyParser.json());
/* redirects to GitHub Repo of the module */
app.get("/", function (_req, res) {
res.redirect("https://github.com/gadzorg/slack-github");
});
/* config variables */
var channel = process.env.CHANNEL;
var username = process.env.USERNAME;
var url = process.env.URL;
/* returns genarated message to send using request payload by GitHub */
var generateMessage = function (req) {
var result = "";
var data = req.body;
for (var i = 0; i < data.commits.length; i++) {
var { commit } = data.commits[i];
var repo = data.repository;
result +=
"<@" +
commit.author.name +
">" +
" <" +
commit.url +
"|committed> in <" +
repo.url +
"|" +
repo.name +
"> : " +
commit.message;
result += "\n";
}
return result;
};
/*
triggers on a POST request by GitHub webhook
and send message to slack-channel, according to commit detail
*/
app.post("/", function (req, res) {
/* works only, if url config var is there */
if (url) {
console.log("Responding to event '%s'", req.headers["x-github-event"]);
if (req.headers["x-github-event"] === "ping") {
return res.json({ value: "pong" });
}
if (req.headers["x-github-event"] !== "push") {
return res.sendStatus(204);
}
var options = {};
options.url = url;
options.method = "POST";
/* use default channel and username if they are not present in config */
options.body = {};
if (channel) {
options.body["channel"] = "#" + channel;
}
if (username) {
options.body["username"] = "" + username;
}
console.log("Would be sending message '%s'", generateMessage(req));
options.body["text"] = generateMessage(req);
options.json = true;
request(options, function (_err, response, _body) {
var statusCode = response.statusCode;
res.sendStatus(statusCode);
});
}
});
var port = process.env.PORT || 5000;
app.listen(port, function () {
console.log("express server listening on " + port);
});