route.js
18.7 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
const MongoClient = require('mongodb').MongoClient;
const SlackBot = require('slackbots'); //link : https://github.com/mishk0/slack-bot-api
const dbname = 'jokeapi';
const emoji = require('../slack_emoji');
const url = 'mongodb://13.124.65.242:27017/';
const url2 = 'mongodb://13.124.65.242:27017/userdb';
const fs=require('fs');
message_recieved = 0;
ary_size=0;
exports.startbot = ()=>{
// Get authorization to use the slackbot
const bot = new SlackBot({
token : "Your Token",
name : "jokebot"
});
// Start the slackbot
bot.on('start', () =>{
//Figure out user's all current channels in the team
channel = bot.getChannels();
channel.then((data)=>{
channel_length = data.channels.length;
for(i=0; i< channel_length; ++i){
//postMessageToChannel(name, message [, params, callback]) (return: promise) - posts a message to channel by name.
bot.postMessageToChannel(data.channels[i].name, 'Have some fun with @Joker!\nFor commands write @jokebot --help',
emoji.emojis('bowtie'));
}
return data;
})
.then((data)=>{
console.log('Sucessfully started app to all channels');
})
});
// Error Handler
bot.on('error', (err) => console.log(err));
//Message Handler
bot.on('message', (data) => {
if(data.type !== 'message'){
return;
}
status = data;
//Figure out which channel the user is sending message
//If it's first input from the user, go through this loop to store the data of channel names and ids
if(message_recieved == 0){
channel_length;
channel_names = [];
channel_ids = [];
//bot.getChannels() returns a list of all channels in the team
channel = bot.getChannels();
channel.then((data)=>{
channel_length = data.channels.length;
for(i=0; i< channel_length; ++i){
channel_names.push(data.channels[i].name);
channel_ids.push(data.channels[i].id);
}
return data;
})
.then((result)=>{
++message_recieved;
console.log("User Channel list: " + channel_names)
for(i=0; i< channel_length; ++i){
if(channel_ids[i] == status.channel){
handleMessage(status.text, channel_names[i]);
}
}
})
}
console.log(status);
//If it's not the first user input, goes through simple loop to shorten response time
if(message_recieved > 0){
for(i=0; i< channel_length; ++i){
if(channel_ids[i] == status.channel)
handleMessage(status.text, channel_names[i]);
}
}
//handleMessage(data.text);
});
// Responding to Data
function handleMessage(message, current_channel){
console.log(message);
//Handles message response depending on the user message
if(message.includes(' tell me') || message.includes(' Tell me')){
if(message.includes(' knock')){
knockknockJoke(current_channel);
}
else if(message.includes(' general')){
generalJoke(current_channel);
}
else if(message.includes(' random') || message.includes(' some joke') || message.includes(' funny joke')){
randomJoke(current_channel);
}
else if(message.includes(' programming')){
programmingJoke(current_channel);
}
else if(message.includes(' reddit')){;
redditJoke(current_channel);
}
else if(message.includes(' funny story')){
Funnystory(current_channel);
}
else if(message.includes(' my joke') || message.includes(' myjoke')){
UserMakeJoke(message,current_channel);
}
else if(message.includes(' me')){
comment = "Please use @jokebot --help to know what I can do!:smile::smile::smile:\n You can write type of joke[knock-knock, general, programming, funny story, reddit]";
bot.postMessageToChannel(current_channel, "Tell you what??? :no_mouth:", emoji.emojis('no_mouth'));
bot.postMessageToChannel(current_channel, comment, emoji.emojis('flushed'));
}
}
else if(message.includes(' -help')){
runHelp(current_channel);
}
else if(message.includes(' what jokes')){
jokeTypes = ["general", 'programming', 'knock-knock','reddit','funny story'];
bot.postMessageToChannel(current_channel, `I have ${jokeTypes[0]}, ${jokeTypes[1]}, ${jokeTypes[2]},${jokeTypes[3]},${jokeTypes[4]} jokes!! :thumbsup: :thumbsup:`, emoji.emojis('thumbsup'));
return;
}
else if(message.includes(' make joke : '))
{
MakeJoke(message,current_channel);
}
}
function MakeJoke(message,user_channel){
var obj={
table:[]
}
var input=message.split(':');
var msg=input[1].split(',');
var temp=message.split(' ');
var user=temp[0].substring(2,temp[0].length-1);
console.log('유저 => '+user);
var path='./joke_data/user.json';
fs.exists(path,function(exists){
if(exists){
console.log("yes file exists");
fs.readFile(path,function readFileCallback(err,data){
if(err){
console.log(err);
}
else{
obj=JSON.parse(data);
var length=obj.table.length;
obj.table.push({id : length+1, type : user, setup : msg[0], punchline : msg[1]});
//var myobj = {id : length+1, type : user, setup : msg[0], punchline : msg[1]};
MongoClient.connect(url,function(err,db){
if(err) throw err;
var dbo = db.db("userdb");
var array = dbo.collection('user').find({type : user}).toArray(function(err,docs){
if(err){
callback(err,null);
return ;
}
console.log(docs.length);
var myobj = {id : docs.length+1, type : user, setup : msg[0], punchline : msg[1]};
dbo.collection("user").insertOne(myobj, function(err,res){
if(err) throw err;
console.log("1 insert!!");
db.close();
})
});
})
var json=JSON.stringify(obj);
fs.writeFile(path,json,'utf8',function(err){
if(err){
console.log(err);
}
console.log('완료');
});
}
});
comment="Sucess making joke!!:+1::thumbsup:\nWhen you want to show your joke, please enter @jokebot tell-me-my-joke";
bot.postMessageToChannel(user_channel,`${comment}:kissing_heart:`,emoji.emojis('nerd_face'));
}
else{
console.log("file not exists");
obj.table.push({id : 1, type : user, setup : msg[0], punchline : msg[1]});
var myobj = {id : 1, type : user, setup : msg[0], punchline : msg[1]};
MongoClient.connect(url,{ useNewUrlParser: true },function(err,db){
if(err) throw err;
var dbo = db.db("userdb");
dbo.collection("user").insertOne(myobj, function(err,res){
if(err) throw err;
console.log("1 insert!!");
db.close();
})
});
var json=JSON.stringify(obj);
fs.writeFile(path,json,'utf8',function(err){
if(err){
console.log(err);
}
console.log('완료');
});
comment="Sucess making joke!!:+1::thumbsup:\nWhen you want to show your joke, please enter @jokebot tell-me-userjoke";
bot.postMessageToChannel(user_channel,`${comment}:kissing_heart:`,emoji.emojis('nerd_face'));
}
})
}
//Gets a random integer
function getRandomInt(start,end) {
return Math.floor((Math.random() * 100)%(end-start))+start;
}
//Function for giving out random joke
randomJoke= (user_channel)=>{
//Connect to mongodb client
MongoClient.connect('mongodb://13.124.65.242:27017/', function (err, client){
if (err) throw err;
//go into database name jokeapi
var db = client.db('jokeapi');
//set the maximum number of api formats and get a random integer
random = getRandomInt(1,377);
//Go to jokes collection inside jokeapi database and find one joke randomly by putting a random number
result = db.collection('jokes').findOne({id: random});
user = result;
//After finding one joke, use promise to run codes synchronously
user.then(function(total){
question = total.setup;
bot.postMessageToChannel(user_channel, question, emoji.emojis('laughing'));
console.log("질문 불려짐");
return total;
})
.then((all)=>{
joke=all.punchline;
//Use setTimeout function to delay the code execution, making sure the user reads the question first and then see the final funny joke
setTimeout(function secondFunction(){
bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
console.log("허무개그 전송~~~~~~!");
},3000);
})
//close mongodb
client.close();
})
}
// Function for giving out users making joke
UserMakeJoke= (message,user_channel)=>{
var temp=message.split(' ');
var user=temp[0].substring(2,temp[0].length-1);
console.log('유저 => '+user);
MongoClient.connect('mongodb://13.124.65.242:27017', function (err, client){
if (err) throw err;
//go into database name jokeapi
var db = client.db('userdb');
var array = db.collection('user').find({type: user}).toArray(function(err,docs){
if(err){
callback(err,null);
return;
}
ary_size=docs.length;
console.log(docs.length);
var random=getRandomInt(1,ary_size+1);
console.log(random);
var result=docs[random-1];
user = result;
console.log(user);
question = user.setup;
joke=user.punchline;
bot.postMessageToChannel(user_channel, question, emoji.emojis('laughing'));
console.log("질문 불려짐");
setTimeout(function secondFunction(){
bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
console.log("허무개그 전송~~~~~~!");
},3000);
// //After finding one joke, use promise to run codes synchronously
// user.then(function(total){
// question = total.setup;
// bot.postMessageToChannel(user_channel, question, emoji.emojis('laughing'));
// console.log("질문 불려짐");
// return total;
// })
// .then((all)=>{
// joke=all.punchline;
// //Use setTimeout function to delay the code execution, making sure the user reads the question first and then see the final funny joke
// setTimeout(function secondFunction(){
// bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
// console.log("허무개그 전송~~~~~~!");
// },3000);
// })
});
//var random=getRandomInt(1,ary_size+1);
// console.log(ary_size);
// var result=db.collection('user').findOne({type : user ,id : random});
// user = result;
// //After finding one joke, use promise to run codes synchronously
// user.then(function(total){
// question = total.setup;
// bot.postMessageToChannel(user_channel, question, emoji.emojis('laughing'));
// console.log("질문 불려짐");
// return total;
// })
// .then((all)=>{
// joke=all.punchline;
// //Use setTimeout function to delay the code execution, making sure the user reads the question first and then see the final funny joke
// setTimeout(function secondFunction(){
// bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
// console.log("허무개그 전송~~~~~~!");
// },3000);
// })
//close mongodb
client.close();
})
}
//Function for giving out random joke after filtering only general type jokes
generalJoke= (user_channel)=>{
MongoClient.connect(url, function (err, client){
if (err) throw err;
var db = client.db('jokeapi');
random = getRandomInt(24,377);
result = db.collection('jokes').findOne({id: random});
user = result;
//if the random picked api type is not general execute the function from the start to get another format for general type
user.then(function(total){
question = total.setup;
bot.postMessageToChannel(user_channel,question,emoji.emojis('laughing'));
console.log('질문 불려짐');
return total;
})
.then((all)=>{
joke=all.punchline;
//Use setTimeout function to delay the code execution, making sure the user reads the question first and then see the final funny joke
setTimeout(function secondFunction(){
bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
console.log("허무개그 전송~~~~~~!");
},3000);
})
client.close();
})
};
//Function for giving out random joke after filtering only programming type jokes
programmingJoke= (user_channel)=>{
MongoClient.connect(url, function (err, client){
if (err) throw err;
var db = client.db('jokeapi');
random = getRandomInt(1,19);
result = db.collection('jokes').findOne({id: random});
user = result;
user.then(function(total){
question = total.setup;
bot.postMessageToChannel(user_channel,question,emoji.emojis('laughing'));
console.log("질문 불려짐");
return total;
})
.then((all)=>{
joke=all.punchline;
//Use setTimeout function to delay the code execution, making sure the user reads the question first and then see the final funny joke
setTimeout(function secondFunction(){
bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
console.log("허무개그 전송~~~~~~!");
},3000);
})
client.close();
})
};
//Function for giving out funny story
Funnystory= (user_channel)=>{
MongoClient.connect(url, function (err, client){
if (err) throw err;
var db = client.db('FunnyStoryapi');
random = getRandomInt(1,201);
result = db.collection('FunnyStory').findOne({id: random});
user = result;
//if the random picked api type is not general execute the function from the start to get another format for general type
user.then(function(total){
cate = total.category;
story = total.body;
category_story=cate+'\n'+story+':stuck_out_tongue_winking_eye::laughing:';
bot.postMessageToChannel(user_channel, category_story, emoji.emojis('smiley'));
console.log("Funny story~~~");
})
client.close();
})
};
//Function for giving out random joke after filtering only reddit jokes
redditJoke= (user_channel)=>{
MongoClient.connect(url, function (err, client){
if (err) throw err;
var db = client.db('redditjoke');
random = getRandomInt(1,71);
result = db.collection('reddit').findOne({id: random});
user = result;
//if the random picked api type is not general execute the function from the start to get another format for general type
user.then(function(total){
title = total.title;
bot.postMessageToChannel(user_channel, title, emoji.emojis('smiliey'));
console.log("질문 불려짐");
return total;
})
.then((all)=>{
joke=all.body;
//Use setTimeout function to delay the code execution, making sure the user reads the question first and then see the final funny joke
setTimeout(function secondFunction(){
bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
console.log("허무개그 전송~~~~~~!");
},3000);
})
client.close();
})
};
//Function for giving out random joke after filtering only knock-knock type jokes
knockknockJoke= (user_channel)=>{
MongoClient.connect(url, function (err, client){
if (err) throw err;
var db = client.db('jokeapi');
random = getRandomInt(19,24);
result = db.collection('jokes').findOne({id: random});
user = result;
user.then(function(total){
question = total.setup;
bot.postMessageToChannel(user_channel, question, emoji.emojis('laughing'));
console.log("질문 불려짐");
return total;
})
.then((all)=>{
joke=all.punchline;
setTimeout(function secondFunction(){
bot.postMessageToChannel(user_channel,`${joke}:stuck_out_tongue_winking_eye::laughing:`,emoji.emojis('laughing'));
console.log("허무개그 전송~~~~~~!");
},3000);
})
client.close();
})
}
//Function for giving out information to user to control the bot
runHelp = (user_channel) =>{
comment = "Thanks for using jokebot bot!:ghost::ghost:laugh:\nBot info: type '@jokebot help' for infos\nBot functions: '@jokebot tell-me [something] joke' will send related jokes, if I don't have what you mentioned, I will tell you I don't have that joke:smile:\n"
current_jokes = "Joke types I have: 1)general , 2)knock-knock , 3)programming , 4)reddit, 5)funny story:laughing:\n";
ownJoke = "Wanna add your own joke? Just type '@jokebot [make joke : (question), (your joke)]' ! Want to check what jokes you added? Just simply type '@jokebot tell me my joke:smiley:'";
bot.postMessageToChannel(user_channel, comment + current_jokes + ownJoke ,emoji.emojis('question'));
}
}