-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
91 lines (71 loc) · 2.43 KB
/
index.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
var https = require('https');
var url = require('url');
var exports = {
channel: '#general',
username: "console.slack.bot",
emoji: ":nerd_face:",
webhook: false
};
exports.checkSettings = function (channel, onSuccess) {
// check to make sure the setting are correct
// If the webhook is not set, we can't post to slack.
if (!exports.webhook) {
throw new Error("Webhook URL not provided. Add it with `slack.webhook = <url>`");
}
// make sure the channel begins with a #
if (!/^#.*/.test(channel)) {
throw new SyntaxError("Channels must start with a #. Yours was " + channel + ". Try '#" + channel + "'.");
}
// make sure that the onSuccess function is actually a function
if (onSuccess && typeof onSuccess !== 'function') {
throw new TypeError('onSuccess must be a function');
}
// make sure the emoji is the correct format
if (!/\:.*\:/.test(exports.emoji)){
throw new SyntaxError("Emoji syntax incorrect. Should be ':emoji_name:'");
}
};
console.slack = function (message, channel, onSuccess) {
if (exports.options) { // this is unfortunate, but we only have to do it once...
exports.channel = exports.options.channel || exports.channel;
exports.username = exports.options.username || exports.username;
exports.emoji = exports.options.emoji || exports.emoji;
exports.webhook = exports.options.webhook || exports.webhook;
}
channel = channel || exports.channel;
exports.checkSettings(channel, onSuccess);
onSuccess = onSuccess || function(){}; // make sure we don't get any undefined errors.
if (exports.webhook == 'test') {
console.log(exports.username + " says " + message + " to " + channel);
return onSuccess('This is simply a test', 200);
}
var requestUrl = url.parse(exports.webhook);
var request = https.request({
protocol : requestUrl.protocol,
hostname : requestUrl.hostname,
path : requestUrl.path,
method : 'POST',
headers : {
'Content-Type' : 'application/json'
}
}, function(res){
var data = [];
res.on('data', function(chunk){
data.push(chunk);
});
res.on('end', function(){
onSuccess(data, res.statusCode);
});
});
request.on('error', function(e){
onSuccess(e.message, e.statusCode);
});
request.write(JSON.stringify({
text: message,
username: exports.username,
icon_emoji: exports.emoji,
channel: channel
}));
request.end();
};
module.exports = exports;