/
app.js
358 lines (318 loc) · 11.7 KB
/
app.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
// App.js
// Server route setup
var express = require('express');
var bodyParser = require('body-parser');
var Sequalize = require('sequelize');
var mongoose = require('mongoose');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
const SlackBot = require('slackbots');
var BracketBuilder = require('./bracketBuilder');
var makeAppointment = require('./calendarHelper');
// Google OAuth instantiation
// var OAuth2 = google.auth.OAuth2;
const bb = new BracketBuilder();
const db = new Sequalize({
dialect: 'sqlite',
storage: './services/test.sqlite'
})
const User = db.define('user', {
name: {
type: Sequalize.STRING,
primaryKey: true
},
real_name: {
type: Sequalize.STRING,
primaryKey: true
},
display_name: {
type: Sequalize.STRING,
primaryKey: true
},
email: {
type: Sequalize.STRING,
primaryKey: true
},
pid: Sequalize.STRING,
slack_id: {
type: Sequalize.STRING,
primaryKey: true
}
})
// express server setup
var app = express();
var port = process.env.PORT || 3000;
// bot
const bot = new SlackBot({
token: process.env.BOT_TOKEN,
name: 'Lil BB'
})
// Object that stores mapping of uesrs
var all_users = {};
var all_tourns = {};
bot.on('start', () => {
const params = {
icon_emoji: ''
}
// user storage
var users = bot.getUsers()._value.members;
users.forEach(u => {
all_users[u.id] = {
name: u.name || '',
real_name: u.real_name || '',
display_name: u.display_name || '',
email: u.profile.email || '',
pid: ''
}
});
bot.postMessageToChannel(
'general',
":wave: Hello, is it _*Lil BB*_ you are looking for? :gentlyplz:",
params);
})
// Error handler
bot.on('error', (err) => console.log(err))
// Message handler
bot.on('message', (data) => {
if (data.type !== 'message') {
return;
}
// Create tournament
var msgArray = data.text.split(" ");
var senderId = data.user;
if (!msgArray[0].includes("UBXBUSPJ9")) {
return;
};
if (msgArray[1].toLowerCase() === "create") {
var bracketName = "";
for (i = 2; i < msgArray.indexOf("bracket"); i++) {
bracketName += (msgArray[i] + " ");
}
var cap = msgArray[msgArray.indexOf("bracket") + 2];
createTournament(bracketName, cap, senderId);
}
// Add players
else if (msgArray[1].toLowerCase() === "add") {
var slackId = msgArray[2].substring(2, msgArray[2].indexOf(">"));
var bracketId = msgArray[4];
addSingleUser(slackId, all_users[slackId].real_name, bracketId);
}
// CAL TESTER
else if (msgArray[1].toLowerCase() === "cal") {
var u1id = msgArray[2].substring(2, msgArray[2].indexOf(">"));
var u2id = msgArray[3].substring(2, msgArray[3].indexOf(">"));
var startdate = new Date("2018-07-28T09:00:00");
var name = "HARD CODED EVENT NAME"
startdate.setDate(startdate.getDate() + 1);
console.log(all_users[u1id].email, all_users[u2id].email, startdate)
appointmentHelper(all_users[u1id].email, all_users[u2id].email, name);
}
// List brackets
else if (msgArray[1].toLowerCase() === "list") {
var bracketId = msgArray[2];
bb.fetchAllBracketInfo().then(g => {
var tournamentsString = "";
g.forEach(t => {
tournamentsString += (":trophy: *" + t.name + " (ID: " + t.id + "):* see bracket here :eyes: " + t.url + "\n")
})
bot.postMessageToChannel(
'general',
tournamentsString
);
});
}
// Update match
else if (msgArray[1].toLowerCase() === "update") {
console.log(msgArray);
var bracketId = msgArray[2];
var slackId = msgArray[5].substring(2, msgArray[5].indexOf(">"));
// var winner = all_users[slackId].pid;
User.findOne({where: {slack_id: slackId}})
.then(user => {
updateTournament(bracketId, user.pid);
})
.catch(err => console.log(err));
}
// Update match
// else if (msgArray[1].toLowerCase() === "cock") {
// sendInvites()
// }
// List participants in tournament
else if (msgArray[1].toLowerCase() === "players") {
var bracketId = msgArray[2];
all_tourns[bracketId] = {};
bb.indexParticipants({id: bracketId}).then( players => {
var playerString = "";
for (i = 0; i < players.length; i++) {
all_tourns[bracketId][players[i].name] = players[i].id;
if (i !== players.length - 1) {
playerString += (players[i].name + " (" + players[i].id + "), ");
} else if (players.length === 1) {
playerString = players[i].name + " (" + players[i].id + ")"
} else {
playerString += "and " + players[i].name + " (" + players[i].id + ")";
}
}
console.log(all_tourns[bracketId]);
bb.fetchBracketInfo({ id:bracketId }).then(data => {
console.log("DATA: ", data)
bot.postMessageToChannel(
'general',
":busts_in_silhouette: Players in *" + data.name + "* are: " + playerString
)
})
});
}
// Knife surya
else if (msgArray[1] === "knife") {
bot.postMessageToChannel(
'general',
"I'd sleep with my eyes open if I were you....:knife: <@UBXDQTU9J>"
)
}
else {
bot.postMessageToChannel(
'general',
":surreal_think: Sorry, I'm not sure if I know what you mean. Try again. :surreal_think:"
)
}
})
// Non-channel messaging capabilities
// Notify user of match
function matchNotification(name, oAuthURL, opponent, date) {
bot.postMessageToUser(
name,
":alerto: You have a new match! against" + opponent + " on " + date +
". Check your Google Calendar for more information :alerto:"
)
}
// Message helper functions
function createTournament(name, cap, slackId) {
if (cap < 4) {
bot.postMessageToChannel(
'general',
"Sorry! you need at least 4 people in a bracket!"
)
return;
}
bb.createBracket({ name, cap }).then(res => {
// console.log("RESERVE: ", res);
if (res.length !== 0) {
bot.postMessageToChannel(
'general',
":trophy: :sparkles: Created the *" + name + "* bracket with ID *" + res +
"* for *" + cap + "* contenders." +
":heavy_exclamation_mark: If you'd like to join " +
"this bracket, please write <@UBXBUSPJ9> _add @friend to *" + res + "*_ :heavy_exclamation_mark:");
} else {
bot.postMessageToChannel(
'general',
"Oops! Something went wrong here. Try again!"
)
}
// Name here needs to be display name or something
addSingleUser(slackId, all_users[slackId].real_name, res);
})
}
// Congratulatory end of tournament message
function endTournament(id) {
// TODO: function to get winner
bot.postMessageToChannel(
'general',
":trophy: :first_place_medal: Congratulations to " + winner + " on DEFEATING _EVERYONE_ in " + bracketName + " :first_place_medal: :trophy:"
)
}
// Add single user (also used in the create stage)
function addSingleUser(slackId, name, tournamentId) {
bb.addSingleParticipant({ tournamentId, name })
.then( ({ id }) => {
console.log("ID COMIN THRUUUU: ", id);
bb.fetchBracketInfo({id: tournamentId}).then(resp => {
if (resp.cap <= resp.count) {
bot.postMessage('general', ":heavy_plus_sign: :gentlyplz: <@" + slackId + "> has been successfully added to " + tournamentId + " bracket. The cap has been reached and the games will now begin!");
bb.startTournament({tournamentId});
sendInvites();
} else {
bot.postMessage('general', ":heavy_plus_sign: :gentlyplz: <@" + slackId + "> has been successfully added to " + tournamentId + " bracket.");
}
})
User.insertOrUpdate({name, real_name: all_users[slackId].real_name, display_name: all_users[slackId].display_name, email: all_users[slackId].email, pid: id, slack_id: slackId})
.then(res => console.log(res))
.catch(err => console.log(err));
})
.catch(_ => {
bot.postMessage('general', 'Oops! Something went wrong here. Try again!');
})
}
// Sends cal invites
function sendInvites({tournamentId}) {
let myUsers = new Set();
bb.getMatches(tournamentId)
.then(matches => {
console.log("Cal matches for a tournament: ", matches);
matches.forEach(m => {
});
});
}
// CLEAR
// User.destroy({where: {}, truncate: true});
// Updating match when user inputs score and winner
function updateTournament(tournamentId, winnerId) {
bb.getMatch({tournamentId, winnerId})
.then(matches => {
let match;
// console.log("MATCH: ", matches);
matches.forEach(m => {
// console.log(m, winnerId, m.player1)
if (winnerId === `${m.player1}` || winnerId === `${m.player2}`) {
// console.log("I FOUND A MATCH.", m)
match = m;
return;
}
})
// console.log("match2: ", match);
let whichPlayerWon;
if (winnerId === match.player1) {
whichPlayerWon = "player1";
User.findOne({where: {pid: winnerId}}).then(user => {
console.log("RESSSS: ", res)
bb.updateMatch({ matchId: match.matchId, tournamentId: tournamentId, winnerId, loserId:match.player2, whichPlayerWon })
.then(res => {
bot.postMessageToChannel(
'general',
":aw_yeah: :banana_dance: Congratulations on the win <@" + user.slack_id + ">! :banana_dance: :aw_yeah: Stay tuned for the next contender."
)
})
.catch(err => console.log(err));
}).catch(err => console.log(err));
} else {
whichPlayerWon = "player2";
User.findOne({where: {pid: winnerId}}).then(user => {
bb.updateMatch({ matchId: match.matchId, tournamentId: tournamentId, winnerId, loserId:match.player1, whichPlayerWon })
.then(res => {
bot.postMessageToChannel(
'general',
":aw_yeah: :banana_dance: Congratulations on the win <@" + user.slack_id + ">! :banana_dance: :aw_yeah: Stay tuned for the next contender."
)
})
.catch(err => console.log(err));
})
.catch(err => console.log(err));
}
})
}
// Use body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
app.get('/hello', function (req, res) {
const code = req.query.code;
res.send('Hello world!');
});
// connection success route
app.get('/connect/success', function (req, res) {
res.send('Connect success.')
});
// TODO: google authorization endpoint
app.listen(port, function () {
console.log('⚡️ Listening on port ' + port + ' ⚡️');
})