forked from UncannyBingo/easy-peasy-slash-command-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
385 lines (323 loc) · 15.1 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/* Uses the slack button feature to offer a real time bot to multiple teams */
var Botkit = require('botkit');
var Https = require('https');
var moment = require('moment-timezone');
var BeepBoop = require('beepboop-botkit');
var os = require('os');
var config = {}
if (process.env.MONGOLAB_URI) {
var BotkitStorage = require('botkit-storage-mongo');
config = {
storage: BotkitStorage({mongoUri: process.env.MONGOLAB_URI}),
};
} else {
config = {
json_file_store: './db_slackbutton_slash_command/',
};
}
config.debug = true;
config.logLevel = 7;
config.retry = Infinity;
config.hostname = '0.0.0.0';
var controller = Botkit.slackbot(config);
var beepboop = BeepBoop.start(controller, { debug: true });
controller.setupWebserver(process.env.PORT, function (err, webserver) {
controller.createWebhookEndpoints(controller.webserver);
});
var help = "I can help you forget the pain around Cats :cats_bot:" +
"\nTry typing `/cats saveCredentials <username> <password>` to save credentials & test login" +
"\nTry typing `/cats addTime <date in format DD> <order> <sub-order> <hours> <comment>` to book time" +
"\nTry typing `@cats_bot reminder` to remind everyone in the team to book time" +
"\nExample: `/cats saveCredentials bond007 james` - saving credentials " +
"\nExample: `/cats addTime 27 US00000 100 8 created bots` - adding hours" +
"\nExample: `/cats addTime 22 US00000 na 8 created bots` - with no sub-order" +
"\nExample: `/cats addTime today US00000 na 8 created bots` - with today as a date";
controller.on('slash_command', function (slashCommand, message) {
switch (message.command) {
case "/cats":
// but first, let's make sure the token matches!
//if (message.token !== process.env.VERIFICATION_TOKEN) return; //just ignore it.
var text = message.text.trim().split(" ");
switch (text[0]) {
case "help":
slashCommand.replyPrivate(message, help);
break;
case "saveCredentials":
if (!text[1] || !text[2]) {
slashCommand.replyPrivate(message, "I'm afraid you cant save credentials without passing 'em");
break;
}
var incomingUserName = text[1];
var incomingPassword = text[2];
var loginSuccess = true;
slashCommand.replyPrivate(message, "Attempting to login " + "\nCommand: " + message.command + " "+ message.text, function() {
loginSuccess = performLogin(slashCommand, message, incomingUserName, incomingPassword, false);
});
break;
case "addTime":
var addTimeSuccess = true;
slashCommand.replyPrivate(message, "Attempting to add your hours to cats.." + "\nCommand: " + message.command + " "+ message.text, function() {
controller.storage.users.get(message.user, function(err, user) {
if (user && user.userName && user.password) {
var returnStatusCode = performLogin(slashCommand, message, user.userName, user.password, true);
if (true) {
var comment = "";
for (var i = 5; i < text.length; i++) {
comment += text[i] + " ";
}
console.log("Comment:", comment);
var year = moment().year().toString();
var month = (moment().month() + 1).toString();
var date = ((text[1] === 'today') ? moment().format("YYYYMMDD") : year + month + text[1]);
console.log("Date:", date);
if (!date || !(moment(date, "YYYYMMDD", true).isValid()) || !text[2] || !text[3] || !text[4] || !comment) {
slashCommand.replyPrivateDelayed(message, "Please pass data in the form of <date in format DD> <order> <sub-order> <hours> <comment> ");
addTimeSuccess = false;
}
else {
var incomingDate = date;
var incomingOrder = text[2];
var incomingSuborder = text[3];
var incomingHours = text[4];
var formattedComment = comment.substring(0,50);
var postTimeSuccess = true;
slashCommand.replyPrivateDelayed(message, "Attempting to add your time", function() {
controller.storage.users.get(message.user, function(err, user) {
postTimeSuccess = performPostTime(slashCommand, message, incomingDate, incomingOrder, incomingSuborder, incomingHours, formattedComment, user.sid, user.defaultActivity);
});
});
}
}
else {
slashCommand.replyPrivateDelayed(message, "I do not have your right credentials to login, Try typing `/cats login <username> <password>` to login");
}
}
else {
slashCommand.replyPrivateDelayed(message, "I do not have your credentials to login, Try typing `/cats login <username> <password>` to login");
}
});
});
break;
default:
slashCommand.replyPublic(message, "I'm afraid I don't know how to " + message.command + " " + message.text + " yet.");
}
break;
default:
slashCommand.replyPublic(message, "I'm afraid I don't know how to " + message.command + " " + message.text + " yet.");
}
});
beepboop.on('add_resource', function (msg) {
console.log('received request to add bot to team')
});
// Send the user who added the bot to their team a welcome message the first time it's connected
beepboop.on('botkit.rtm.started', function (bot, resource, meta) {
var slackUserId = resource.SlackUserID
if (meta.isNew && slackUserId) {
bot.api.im.open({ user: slackUserId }, function (err, response) {
if (err) {
return console.log("im.open error:",err)
}
var dmChannel = response.channel.id
bot.say({channel: dmChannel, text: 'Thanks for adding me to your team!'})
bot.say({channel: dmChannel, text: 'Just /invite me to a channel!'})
})
}
});
controller.on('bot_channel_join', function (bot, message) {
console.log("bot_channel_join")
bot.reply(message, "I'm here!")
});
controller.hears(['hello', 'hi'], 'direct_mention', function (bot, message) {
bot.reply(message, 'Hello.');
});
controller.hears(['hello', 'hi'], 'direct_message', function (bot, message) {
bot.reply(message, 'Hello.')
bot.reply(message, 'It\'s nice to talk to you directly.')
});
controller.hears('.*', 'mention', function (bot, message) {
bot.reply(message, 'You really do care about me. :heart:')
});
controller.hears(['help'], 'direct_message,direct_mention', function (bot, message) {
bot.reply(message, help)
});
controller.hears(['reminder'], 'direct_message,direct_mention', function (bot, message) {
if (message.user == 'U2K8XK03Z' || message.user == 'U23RT8WQ4') {
bot.reply(message, "On it..");
bot.api.users.list({
}, function(err, list) {
if (err) {
console.log('Failed to get users list :(', err);
}
else {
console.log('users list :', list);
for (var i = 0; i < list.members.length; i++) {
if(list.members[i].is_bot == false) {
bot.startPrivateConversation({user: list.members[i].id}, function(err,convo) {
convo.say("Its Cats Time :heart_eyes_cat: !!");
convo.say("Try typing `@cats_bot help` to find out how I can help Catsing.");
});
}
}
}
});
}
else {
bot.reply(message, 'Sorry <@' + message.user + '>, you are not authorized to spam :wink:');
}
});
controller.hears(['identify yourself', 'who are you', 'what is your name'], 'direct_message,direct_mention,mention', function(bot, message) {
var hostname = os.hostname();
var uptime = formatUptime(process.uptime());
bot.reply(message,
':robot_face: I am a bot named <@' + bot.identity.name +
'>. I have been running for ' + uptime + ' on ' + hostname + '.' +
'\n I have been created by Mr. Ojas Gosar');
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}
function getCurrentTimestamp() {
var current = moment().format("YYYYMMDD HH:mm:ss");
var timezoneid = moment.tz.guess();
return current + " " + timezoneid;
}
function performPostTime(slashCommand, message, incomingDate, incomingOrder, incomingSuborder, incomingHours, formattedComment, incomingSid, incomingDefaultActivity) {
var options = {
host: process.env.CATS_HOST,
path: process.env.POST_TIME_PATH,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'Timestamp': getCurrentTimestamp(),
'Consumer-Id': process.env.CONSUMER_ID,
'Consumer-Key': process.env.CONSUMER_KEY,
'Version': '1.0',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0',
'x-fallback-origin': process.env.FALLBACK_ORIGIN,
'Cache-Control': 'no-cache',
'Accept-Language': 'en',
'sid': incomingSid
}
};
console.log("Start Add time POST Request");
var req = Https.request(options, function(res) {
res.on('data',function(data){
var jsonData = JSON.parse(data);
console.log("JsonData:", jsonData);
httpstatus = jsonData.httpstatus;
switch (httpstatus) {
case 201:
slashCommand.replyPrivateDelayed(message, "Cats entry was successful..");
break;
case 400:
slashCommand.replyPrivateDelayed(message, jsonData.details);
break;
case 500:
slashCommand.replyPrivateDelayed(message, jsonData.message);
break;
default:
console.log("HttpsStatus:", httpstatus);
}
});
});
req.on('error', (e) => {
console.error("Error:", e);
slashCommand.replyPrivateDelayed(message, "something went wrong :(");
return false;;
});
var subOrder = ((incomingSuborder == 'na') ? '' : ',"suborderid":"'+incomingOrder+'-'+incomingSuborder+'"');
var reqData = '{"date":"'+incomingDate+'","workingHours":"'+incomingHours+'","comment":"'+formattedComment+'","orderid":"'+incomingOrder+'"'+subOrder+',"activityid":"'+incomingDefaultActivity+'"}';
console.log("Request Data: ", reqData);
req.write(reqData);
req.end();
}
function performLogin(slashCommand, message, incomingUserName, incomingPassword, silent) {
var httpstatus = null;
var sid = null;
var firstName = null;
var lastName = null;
var defaultActivity = null;
var options = {
host: process.env.CATS_HOST,
path: process.env.LOGIN_PATH,
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8',
'User': incomingUserName,
'Password': incomingPassword,
'Timestamp': getCurrentTimestamp(),
'Consumer-Id': process.env.CONSUMER_ID,
'Consumer-Key': process.env.CONSUMER_KEY,
'Version': '1.0',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0',
'x-fallback-origin': process.env.FALLBACK_ORIGIN,
'Cache-Control': 'no-cache',
'Accept-Language': 'en'
}
};
console.log("Start Login get Request");
var req = Https.request(options, function(res) {
res.on('data',function(data){
var jsonData = JSON.parse(data);
console.log("JsonData:", jsonData);
httpstatus = jsonData.httpstatus;
switch (httpstatus) {
case 200 :
sid = jsonData.meta.sid;
lastName = jsonData.name;
firstName = jsonData.prename;
defaultActivity = jsonData.defaultActivity;
if (!defaultActivity) {
slashCommand.replyPrivateDelayed(message, "You do not have defaultActivity set, please contact Cats Admin.");
};
controller.storage.users.get(message.user, function(err, user) {
if (!user) {
user = {
id: message.user
}
}
user.userName = incomingUserName;
user.password = incomingPassword;
user.firstName = firstName;
user.lastName = lastName;
user.sid = sid;
user.defaultActivity = defaultActivity;
controller.storage.users.save(user);
});
if (!silent) {
slashCommand.replyPrivateDelayed(message, firstName + " " + lastName + " you have successfully logged-in");
}
break;
case 401 :
slashCommand.replyPrivateDelayed(message, jsonData.message);
break;
default:
console.log("HttpsStatus:", httpstatus);
slashCommand.replyPrivateDelayed(message, "could not login for some reason = " + jsonData.message);
}
return httpstatus;
});
});
req.on('error', (e) => {
console.error("Error:", e);
slashCommand.replyPrivateDelayed(message, "something went wrong :(");
});
req.end();
}