-
Notifications
You must be signed in to change notification settings - Fork 1
/
slacklog.js
79 lines (70 loc) · 2.04 KB
/
slacklog.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
SlackLog = {
_token: function() {
if (Meteor.settings.slackLog && Meteor.settings.slackLog.token) {
return Meteor.settings.slackLog.token;
} else {
throw new Meteor.Error('[SlackLog] missing token settings, i.e. Meteor.settings.slackLog.token');
}
},
_api: function(method, params) {
var token = this._token();
var url = 'https://slack.com/api/' + method;
_.extend(params, {
token: token
});
var response;
try {
response = HTTP.post(url, {
params: params
});
} catch (e) {
throw new Meteor.Error('[SlackLog] Request Error: ' + e);
}
if (response.statusCode === 200 && response.data.ok) {
return response.data;
} else {
throw new Meteor.Error('[SlackLog] Improper response: ' + JSON.stringify(response), ", request: ", JSON.stringify(params));
}
},
_createChannel: function(name) {
var self = this;
var channel = self._api('channels.create', {name: name});
return channel;
},
_channelByName: function(name, createIfNotExists) {
var self = this;
var channelList = self._channels();
var channel = _.find(channelList, function(channel) {
return channel.name === name;
});
if (channel) {
return channel;
}
if (createIfNotExists) {
channel = self._createChannel(name);
}
return channel;
},
_channels: function() {
var data = this._api('channels.list', {});
var channelList = data.channels;
return channelList;
},
/*
* @param {String} channelName
* @param {Object} options Ref: https://api.slack.com/methods/chat.postMessage
* channel and token will be filled automatically
*/
log: function(channelName, options) {
var self = this;
var channel = self._channelByName(channelName, true);
var defaultOptions = {
channel: channel.id,
as_user: false,
username: 'SlackLog',
icon_emoji: ':paperclip:'
};
options = _.extend({}, defaultOptions, options);
self._api('chat.postMessage', options);
}
}