-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
311 lines (280 loc) · 8.63 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
global.base_path = `${__dirname}/`;
/*--------
Init
--------*/
var util = require('./util'),
logger = require('./logger')('index'),
Botkit = require('botkit'),
cron = require('node-cron'),
https = require('https'),
http = require('http'),
db = require('./db'),
config = require('./config'),
controller = Botkit.slackbot({
clientSigningSecret: config.get('slack').slackbot.clientSecret,
debug: false
}),
express = require('express'),
session = require('express-session'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
MemoryStore = require('session-memory-store')(session),
uuid = require('uuid'),
passport = require('passport'),
SlackStrategy = require('passport-slack-oauth2').Strategy;
/*--------
Params
--------*/
const ENVIRONMENT = config.get('ENVIRONMENT', 'local'),
PORT = config.get('PORT', '3000'),
PING = config.get('PING', false);
var bot = controller.spawn({token: config.get('slack').bot.token});
const invalidUsers = ['test_user'];
/*--------
Passport
--------*/
passport.use(new SlackStrategy({
callbackURL: config.getCallbackURL(),
clientID: config.get('slack').client_id,
clientSecret: config.get('slack').client_secret
}, (accessToken, refreshToken, profile, done) => {
done(null, profile);
}));
const users = {};
passport.serializeUser((user, done) => {
const id = uuid.v4();
users[id] = user;
done(null, id);
});
passport.deserializeUser((id, done) => {
done(null, users[id]);
});
/*--------
Express
--------*/
const app = express();
app.set('port', PORT);
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
resave: false,
saveUninitialized: false,
secret: '12345QWERTY-SECRET',
store: new MemoryStore()
}));
app.use(express.static('public'));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
/*--------
Routes
--------*/
app.use('/auth', require('./routes/auth'));
app.use('/rewards', require('./routes/rewards'));
app.use('/leaderboard', require('./routes/leaderboard'));
app.use('/', require('./routes/views'));
var server = http.createServer(app);
server.listen(PORT);
server.on('error', (error) => {
logger.log(error);
});
server.on('listening', () => {
logger.info('Server started.');
});
/*--------
Token
--------*/
const { token, singular, plural } = config.get('keyword'),
regex_token = new RegExp(token, "g"),
regex_mention = /<@(\S+)>/g;
util.setKeyword(config.get('keyword'));
/*--------
Command list
--------*/
const commandList = [
{
message: `Displays the ${singular} leaderboard, it can be used on any channel where the bot is invited.`,
name: 'show leaderboard'
},
{
message: `Displays the actual quantity of ${plural} you have, this command need to be a direct message to the bot.`,
name: `my ${plural}`
}
];
/*--------
Reset Tokens
--------*/
controller.hears(`reset daily ${plural}`, 'direct_message', (bot, message) => {
if (config.get('admins').includes(message.user)) {
db.reset()
.then(() => {
bot.reply(message, `The ${plural} has been reset.`);
})
.catch((error) => {
bot.reply(error, `Error while reset the ${plural}.`);
});
} else {
bot.reply(message, `You don't have permission to do this command.`);
}
});
/*--------
Token Listener
--------*/
if (util.isProduction(ENVIRONMENT)) {
controller.hears(token, 'ambient', function(bot, message) {
var mentioned_users = message.text.match(regex_mention);
if (mentioned_users.length <= 0) {
return logger.warn('There are no users mentioned.');
}
var tokens = message.text.match(regex_token).length;
if (tokens <= 0) {
return logger.warn(`There are no ${plural} in the message.`);
}
mentioned_users = mentioned_users.map(function(mention_user) {
return mention_user.trim().replace(/<|@|>/g, '');
});
var giverId = message.user,
receiversIds = mentioned_users,
tokensToSend = (tokens * receiversIds.length),
messageLeft = '';
if (receiversIds.indexOf(giverId) < 0) {
db.getUser(giverId).then(function(user) {
var tokensLeft = (user.coins - tokensToSend);
if (tokensLeft < 0) {
messageLeft = (user.coins === 0) ? `, don't have *any* ${plural} at all. Tomorrow you will have more ${plural}.` : ', but you only have *' + user.coins + '*.';
bot.startPrivateConversation({ user: giverId },
function(response, convo) {
convo.say(`*You don't have enough ${plural}.* You're trying to send *` + tokensToSend + '* '+util.tokenHumanize(tokens)+messageLeft);
});
} else {
logger.info('tokens');
logger.info(tokens);
db.sendTokens(giverId, receiversIds, tokens, function(receiverId) {
bot.startPrivateConversation({ user: receiverId }, function(response, convo) {
convo.say(`You received *${tokens}* ${util.tokenHumanize(tokens)} from <@${giverId}>`);
});
})
.then(function() {
if (receiversIds.length == 1) {
logger.info('tokensLeft');
logger.info(tokensLeft);
messageLeft = (tokensLeft === 0) ? `, that was your last token. Don't worry tomorrow you will have more ${plural}.` : ', now you only have ' + tokensLeft + ' '+util.tokenHumanize(tokensLeft)+' left.';
bot.startPrivateConversation({ user: giverId }, function(response, convo) {
convo.say(`You sent *${tokens}* ${util.tokenHumanize(tokens)} to <@${receiversIds[0]}>${messageLeft}`);
});
} else {
messageLeft = (tokensLeft === 0) ? `, those were your last tokens. Don't worry tomorrow you will have more tokens.` : `, now you only have ${tokensLeft} ${util.tokenHumanize(tokensLeft)} left.` + (tokensLeft === 1) ? ' Choose wisely.' : '';
bot.startPrivateConversation({ user: giverId }, function(response, convo) {
convo.say(`You sent a total of *${tokensToSend}* tokens to ` + util.usersArray(receiversIds) + messageLeft);
});
}
});
}
});
} else {
bot.startPrivateConversation({ user: giverId },
function(response, convo) {
convo.say(`Very funny, but you can't send ${plural} to yourself.`);
});
}
});
}
/*--------
Dashboard Listener
--------*/
if (util.isProduction(ENVIRONMENT) || util.isTest(ENVIRONMENT)) {
controller.hears('show leaderboard', 'ambient', function(bot, message) {
let leaderboard = [];
db.getValidUsers()
.then(function(users) {
leaderboard = users.slice(0,10);
const result = leaderboard
.map((user, index) => `${index+1}. <@${user.id}> : ${user.total_coins} ${plural}`)
.join('\n');
bot.reply(message, `===== Top 10 ===== \n ${result}`);
});
});
}
/*--------
Display command list
--------*/
var CommandListAttach = require('./attachments/command_list.js');
controller.hears('help', 'direct_message', (bot, message) => {
var attach = new CommandListAttach();
Object.keys(commandList).forEach((index) => {
// console.log(commandList[index]);
attach.attachments[0].fields.push({
"title": commandList[index].name,
"value": commandList[index].message
});
});
bot.reply(message, attach);
});
/*--------
Personal tokens list
--------*/
if (util.isProduction(ENVIRONMENT) || util.isTest(ENVIRONMENT)) {
controller.hears(`my ${plural}`, 'direct_message', function(bot, message) {
db.getUser(message.user)
.then((user) => {
bot.reply(message, `You have ${user.total_coins} ${plural}`);
});
});
}
function cleanDeletedUsers() {
request(`https://slack.com/api/users.list?token=${config.get('token')}&include_locale=true&pretty=1`, (error, response, body) => {
if (error) {
// Print the error if one occurred
logger.error(error);
} else {
// Print the response status code if a response was received
logger.info(response);
JSON.parse(body).members.forEach(function(member) {
if (member.deleted) {
db.deleteUser(member.id, member.name);
}
});
}
});
}
/*--------
Bot starts
--------*/
function start_rtm() {
bot.startRTM(function(err) {
if (err) {
console.error('Failed to start RTM', err);
return setTimeout(start_rtm, 60000);
}
logger.info("RTM started!");
});
}
controller.on('rtm_close', function(bot, err) {
console.error('rtm_close event', bot, err);
start_rtm();
});
if (util.isProduction(ENVIRONMENT) || util.isTest(ENVIRONMENT)) {
start_rtm();
} else {
logger.info(`RTM hasn't started.`);
}
/*--------
Cron
--------*/
cron.schedule('59 23 * * ' + config.get('schedule').days, function() {
cleanDeletedUsers();
db.reset();
},{
scheduled: true,
timezone: config.get('timezone')
});
/*--------
Ping
--------*/
if (PING && util.isProduction(ENVIRONMENT)) {
setInterval(() => {
https.get("https://"+config.get('ping').app_name+".herokuapp.com");
}, config.get('ping').time);
}