-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.js
348 lines (323 loc) · 12.3 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
var fs = require('fs');
var SlackAPI = require('slackbotapi');
var Quiz = require('./quiz.js');
function QuizBot(slackToken, locale) {
if (typeof locale === 'undefined') { locale = 'en'; }
this.slack = new SlackAPI({
'token': slackToken,
'logging': false
});
this.slack.on('hello', this.onConnectToSlack.bind(this));
this.slack.on('message', this.onSlackMessage.bind(this));
this.slack.on('file_shared', this.onFileShared.bind(this));
this.quizzes = [];
this.locale = locale;
}
QuizBot.prototype.loadLocale = function(lang) {
var isLocalSuccess = this.tryLoadLocale('locale/' + lang + '.json');
if(!isLocalSuccess) {
var isBuiltInSuccess = this.tryLoadLocale(__dirname + '/locale/' + lang + '.json');
if(!isBuiltInSuccess) {
this.onLocaleLoadFailed(lang);
return false;
}
}
return true;
};
QuizBot.prototype.tryLoadLocale = function(filePath) {
try {
var data = fs.readFileSync(filePath, 'utf8');
this.locale = JSON.parse(data);
return true;
}catch (e) {
return false;
}
}
QuizBot.prototype.getLocale = function(quiz, id) {
if(quiz != null) {
var customQuizLocale = quiz.getCustomLocale(id);
if(customQuizLocale) {
return customQuizLocale;
}
}
if(this.locale[id] && this.locale[id].length > 0) {
var rnd = Math.floor(Math.random() * this.locale[id].length);
return this.locale[id][rnd];
}else{
return "Oops, I don't have locale for " + id;
}
};
QuizBot.prototype.onLocaleLoadFailed = function(lang) {
this.slack.sendMsg(slackChannel, this.getLocale(null, quizId.length == 0 ? 'quizLoadFailedEmpty' : 'quizLoadFailed').replace("<quizId>", quizId));// + " [" + err + "]");
};
QuizBot.prototype.saveQuizToDisk = function(name, url, slackChannel) {
var quizId = name.replace(/\.[^/.]+$/, "");
var http = require('https');
var content = '';
var request = http.request(url, function (res) {
res.on('data', function (chunk) {
content += chunk;
}.bind(this));
res.on('end', function () {
try {
fs.mkdirSync('data');
}catch(e) {}
fs.writeFile('data/' + quizId + '.json', content, function(err) {
if (err) {
this.slack.sendMsg(slackChannel, "Couldn't save file. Error: " + err);
return;
}
this.slack.sendMsg(slackChannel, "Quiz successfully saved as " + quizId + '!');
}.bind(this));
}.bind(this));
}.bind(this));
request.on('error', function (e) {
this.slack.sendMsg(slackChannel, "There was an error: " + e.message);
}.bind(this));
request.end();
};
QuizBot.prototype.listQuizzes = function(slackChannel) {
this.quizList = [];
fs.readdir(__dirname + '/data', function(err, files) {
if (err) {
//this.slack.sendMsg(slackChannel, "Couldn't find directory. Error: " + err);
//return;
}else{
for(var i=0; i<files.length; i++) {
this.quizList.push(files[i].replace(/\.[^/.]+$/, ""));
}
}
fs.readdir('data', function(err, files) {
if (err) {
//this.slack.sendMsg(slackChannel, "Couldn't find directory. Error: " + err);
//return;
}else{
for(var i=0; i<files.length; i++) {
this.quizList.push(files[i].replace(/\.[^/.]+$/, ""));
}
}
var output = "";
for(var i=0; i<this.quizList.length; i++) {
if(i != 0) output += ", ";
output += this.quizList[i];
}
this.slack.sendMsg(slackChannel, "Here are the quizzes I've got: " + output);
}.bind(this));
}.bind(this));
};
QuizBot.prototype.loadQuiz = function(slackChannel, quizId) {
var isLocalSuccess = this.tryLoadQuiz('data/' + quizId + '.json', slackChannel, quizId);
if(!isLocalSuccess) {
var isBuiltInSuccess = this.tryLoadQuiz(__dirname + '/data/' + quizId + '.json', slackChannel, quizId);
if(!isBuiltInSuccess) {
this.onQuizLoadFailed(slackChannel, quizId);
}
}
};
QuizBot.prototype.tryLoadQuiz = function(filePath, slackChannel, quizId) {
try {
var data = fs.readFileSync(filePath, 'utf8');
this.onQuizLoadSuccess(data, slackChannel);
return true;
}catch (e) {
return false;
}
}
QuizBot.prototype.onQuizLoadSuccess = function(data, slackChannel) {
var quiz = new Quiz();
quiz.on('questionPrep', this.onQuestionPrepped.bind(this));
quiz.on('question', this.onQuestionStarted.bind(this));
quiz.on('correctAnswer', this.onCorrectAnswer.bind(this));
quiz.on('incorrectAnswer', this.onIncorrectAnswer.bind(this));
quiz.on('questionTimeout', this.onQuestionTimeout.bind(this));
quiz.on('otherPossibleAnswers', this.onOtherPossibleAnswers.bind(this));
quiz.on('answerPrompt10SecondsLeft', this.onAnswerPrompt10SecondsLeft.bind(this));
quiz.on('showScores', this.onShowScores.bind(this));
quiz.on('quizComplete', this.onQuizComplete.bind(this));
quiz.init(JSON.parse(data), slackChannel);
this.quizzes[slackChannel] = quiz;
quiz.start();
};
QuizBot.prototype.onQuizLoadFailed = function(slackChannel, quizId) {
this.slack.sendMsg(slackChannel, this.getLocale(null, quizId.length == 0 ? 'quizLoadFailedEmpty' : 'quizLoadFailed').replace("<quizId>", quizId));// + " [" + err + "]");
};
QuizBot.prototype.startQuiz = function(quiz, slackChannel, quizId) {
var isValid = true;
if(quiz != null && quiz.state > 0) {
isValid = false;
}
if(isValid) {
this.loadQuiz(slackChannel, quizId);
}else{
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizAlreadyRunning'));
}
};
QuizBot.prototype.pauseQuiz = function(quiz, slackChannel) {
if(quiz == null) {
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizNotLoadedYet'));
}else{
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizPaused'));
quiz.pause();
}
};
QuizBot.prototype.resumeQuiz = function(quiz, slackChannel) {
if(quiz == null) {
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizNotLoadedYet'));
}else{
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizResumed'));
quiz.resume();
}
};
QuizBot.prototype.stopQuiz = function(quiz, slackChannel) {
if(quiz == null) {
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizNotLoadedYet'));
}else{
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizStopped'));
quiz.stop();
this.quizzes[slackChannel] = null;
}
};
QuizBot.prototype.onQuestionPrepped = function(quiz, questionIndex) {
var text = "";
if(questionIndex == 0) {
text = this.getLocale(quiz, 'questionPrepFirst');
}else if(questionIndex == quiz.questions.length-1) {
text = this.getLocale(quiz, 'questionPrepLast');
}else{
text = this.getLocale(quiz, 'questionPrep');
}
text = text.replace("<number>", questionIndex+1);
this.slack.sendMsg(quiz.slackChannel, text);
};
QuizBot.prototype.onQuestionStarted = function(quiz, question) {
var pointsPrefix = "";
var text;
if(question.points > 1 || question.answerCount > 1) {
pointsPrefix = "For " + question.points + " point" + (question.points != 1 ? "s" : "") + (question.answerCount > 1 ? " each" : "") + ", ";
text = pointsPrefix + "*" + question.text.substring(0, 1).toLowerCase() + question.text.substring(1) + "* " + (question.image != null ? question.image : "");
}
else{
text = "*" + question.text + "* " + (question.image != null ? question.image : "");
}
this.slack.sendMsg(quiz.slackChannel, text);
};
QuizBot.prototype.onQuestionTimeout = function(quiz, question) {
var correctAnswerText = question.answerCount == 1 ? this.getLocale(quiz, 'correctAnswerSingle') : this.getLocale(quiz, 'correctAnswerMultiple');
correctAnswerText = correctAnswerText.replace("<data>", quiz.getCorrectAnswers());
this.slack.sendMsg(quiz.slackChannel, this.getLocale(quiz, 'questionTimeout') + ' ' + correctAnswerText);
};
QuizBot.prototype.onOtherPossibleAnswers = function(quiz, otherAnswers) {
var text = otherAnswers.length == 1 ? this.getLocale(quiz, 'otherPossibleAnswer') : this.getLocale(quiz, 'otherPossibleAnswers');
var answersText = "";
for(var i=0; i<otherAnswers.length; i++) {
if(i != 0) {
if(i == otherAnswers.length-1) {
answersText += " and ";
}else{
answersText += ", ";
}
}
answersText += "_*" + otherAnswers[i].text[0] + "*_";
}
text = text.replace("<answer>", answersText);
this.slack.sendMsg(quiz.slackChannel, text);
};
QuizBot.prototype.onCorrectAnswer = function(quiz, user, answers, points, answersLeft) {
var correctMsg = "";
if(answers.length == 1) {
correctMsg = this.getLocale(quiz, 'correctAnswer');
}else if(answers.length == 2) {
correctMsg = this.getLocale(quiz, 'correctAnswers2');
}else{
correctMsg = this.getLocale(quiz, 'correctAnswers');
}
correctMsg = correctMsg.replace('<user>', "<@" + user.name + ">");
var answersText = "";
for(var i=0; i<answers.length; i++) {
if(i != 0) {
if(i == answers.length-1) {
answersText += " and ";
}else{
answersText += ", ";
}
}
answersText += "_*" + answers[i] + "*_";
}
correctMsg = correctMsg.replace('<answer>', answersText);
var answersRemainingText = "";
if(answersLeft > 0) answersRemainingText = " *" + answersLeft + "* answer" + (answersLeft != 1 ? "s" : "") + " left...";
var pointsText = points + " point" + (points != 1 ? "s" : "");
correctMsg = correctMsg.replace('<points>', pointsText);
this.slack.sendMsg(quiz.slackChannel, "" + correctMsg + " " + answersRemainingText);
};
QuizBot.prototype.onShowScores = function(quiz, slackChannel) {
if(quiz == null) {
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'quizNotLoadedYet'));
}else{
this.slack.sendMsg(slackChannel, this.getLocale(quiz, 'latestScores') + quiz.getScores(this.getLocale(quiz, 'leads')));
}
};
QuizBot.prototype.onIncorrectAnswer = function(quiz, user) {
this.slack.sendMsg(quiz.slackChannel, this.getLocale(quiz, 'incorrectAnswer'));
};
QuizBot.prototype.onAnswerPrompt10SecondsLeft = function(quiz, secondsLeft) {
this.slack.sendMsg(quiz.slackChannel, "Anyone? Only " + secondsLeft + " seconds left!");
};
QuizBot.prototype.onQuizComplete = function(quiz) {
delete this.quizzes[quiz.slackChannel];
this.slack.sendMsg(quiz.slackChannel, this.getLocale(quiz, 'finalScores') + quiz.getScores(this.getLocale(quiz, 'wins')));
this.slack.sendMsg(quiz.slackChannel, this.getLocale(quiz, 'closer'));
};
QuizBot.prototype.getQuizByChannel = function(slackChannel) {
return this.quizzes[slackChannel];
};
//************************
// Slack handlers
//************************
QuizBot.prototype.onConnectToSlack = function(data) {
this.name = this.slack.slackData.self.name;
this.id = this.slack.slackData.self.id;
if(this.loadLocale(this.locale)) {
console.log("Quizbot [" + this.name + "] is up and running!");
}else{
console.log("Quizbot [" + this.name + "] could not load '" + this.locale + "' locale file");
}
};
QuizBot.prototype.onSlackMessage = function(slackMsgData) {
if(typeof slackMsgData.text == 'undefined') return;
var quiz = this.getQuizByChannel(slackMsgData.channel);
var user = this.slack.getUser(slackMsgData.user);
//check for mention
if(slackMsgData.text.indexOf('<@' + this.id + '>') > -1) {
var startQuizIndex = slackMsgData.text.indexOf('start quiz');
if(startQuizIndex > -1) {
var rest = slackMsgData.text.substring(startQuizIndex + 11);
var nextSpace = rest.indexOf(" ");
var quizId = rest.substring(0, nextSpace > -1 ? nextSpace : rest.length);
this.startQuiz(quiz, slackMsgData.channel, quizId);
}else if(slackMsgData.text.match(/(pause quiz)\b/ig)) {
this.pauseQuiz(quiz, slackMsgData.channel);
}else if(slackMsgData.text.match(/(resume quiz)\b/ig)) {
this.resumeQuiz(quiz, slackMsgData.channel);
}else if(slackMsgData.text.match(/(stop quiz)\b/ig)) {
this.stopQuiz(quiz, slackMsgData.channel);
}else if(slackMsgData.text.match(/(quiz status)\b/ig)) {
this.getQuizStatus(quiz, slackMsgData.channel);
}else if(slackMsgData.text.match(/(show scores)\b/ig)) {
this.onShowScores(quiz, slackMsgData.channel);
}else if(slackMsgData.text.match(/(list quizzes)\b/ig)) {
this.listQuizzes(slackMsgData.channel);
}
}else{
//listen for normal text
if(quiz != null) {
if(quiz.isQuestionActive()) {
quiz.checkAnswer(slackMsgData.text, user);
}
}
}
};
QuizBot.prototype.onFileShared = function(data) {
this.saveQuizToDisk(data.file.title, data.file.url, data.file.ims[0]);
};
module.exports = QuizBot;