This repository has been archived by the owner on Dec 21, 2018. It is now read-only.
/
standup-irc.js
485 lines (414 loc) · 14.5 KB
/
standup-irc.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
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
476
477
478
479
480
481
482
483
484
485
var _ = require('underscore');
var fs = require('fs');
var irc = require('irc');
var path = require('path');
var pg = require('pg');
var winston = require('winston');
var api = require('./api');
var auth = require('./auth');
var utils = require('./utils');
// Default configs
var defaults = {
irc: {
nick: 'standup'
},
standup: {
port: 80
},
log: {
console: true,
file: null
},
pg: {
enabled: false
},
blacklist: []
};
var existsSync = fs.existsSync || path.existsSync;
// Global config.
if (existsSync('./config.json')) {
config = require('./config.json');
}
config = _.extend({}, defaults, config || {});
var transports = [];
if (config.log.file) {
transports.push(new (winston.transports.File)({
filename: config.log.file
}));
}
if (config.log.console) {
transports.push(new (winston.transports.Console)());
}
// Global logger.
logger = new (winston.Logger)({
transports: transports
});
/********** PG Client **********/
// Check if PG is enabled and if so connect
if (config.pg.enabled) {
var pg = require('pg');
// If no connection string is provided in config then check for an ENV
// variable with one.
if (!config.pg.connstring) {
config.pg.connstring = process.env.DATABASE_URL;
}
if (config.pg.connstring) {
var pg_client = new pg.Client(config.pg.connstring);
pg_client.connect();
}
if (pg_client) {
var query = pg_client.query("SELECT id FROM blacklist");
query.on('row', function(row) {
config.blacklist.push(row.id);
});
}
}
/********** IRC Client **********/
// Global client
irc_client = new irc.Client(config.irc.host, config.irc.nick, {
channels: config.irc.channels
});
// Global authentication manager
authman = new auth.AuthManager();
// Connected to IRC server
irc_client.on('registered', function(message) {
logger.info('Connected to IRC server.');
// Store the nickname assigned by the server
config.irc.realNick = message.args[0];
logger.info('Using nickname: ' + config.irc.realNick);
// Check for additional channels and join
if (pg_client) {
var query = pg_client.query("SELECT id FROM channels");
query.on('row', function(row) {
irc_client.join(row.id);
});
}
});
// Handle errors by dumping them to logging.
irc_client.on('error', function(error) {
// Error 421 comes up a lot on Mozilla servers, but isn't a problem.
if (error.rawCommand !== '421') {
return;
}
logger.error(error);
if (error.hasOwnProperty('stack')) {
logger.error(error.stack);
}
});
/* The bot gets invited to a channel by a user
* - `channel`: The channel the bot is invited to.
* - `from`: The nick of the user who invited the bot.
*/
irc_client.on('invite', function(channel, from) {
logger.info('Invited to ' + channel + ' by ' + from + '.');
commands.goto.func(from, channel, '', [channel]);
});
/* The bot gets kicked out of a channel
* - `channel`: The channel that the user is getting kicked from.
* - `user`: The nick of the user getting kicked from.
* - `by`: The nick of the kicker.
*/
irc_client.on('kick', function(channel, user, by) {
if (user === config.irc.realNick) {
logger.info('Kicked from ' + channel + ' by ' + by + '.');
commands['bye'](user, channel);
}
});
/* Receive, parse, and handle messages from IRC.
* - `user`: The nick of the user that send the message.
* - `channel`: The channel the message was received in. Note, this might not be
* a real channel, because it could be a PM. But this function ignores
* those messages anyways.
* - `message`: The text of the message sent.
*/
irc_client.on('message', function(user, channel, message) {
var match, nick, targetMessageRegex;
if (config.blacklist.indexOf(user) !== -1) {
return false;
}
nick = utils.escapeRegExp(config.irc.realNick);
targetMessageRegex = new RegExp('^' + nick + '[:,]\\s*?(.*)$');
match = targetMessageRegex.exec(message);
if (match) {
message = match[1].trim();
if (message[0] === '!') {
// message = "!cmd arg1 arg2 arg3"
var cmd_name = message.split(' ')[0].slice(1);
var args = message.split(' ').slice(1);
args = utils.parseArgs(args);
var cmd = commands[cmd_name] || commands['default'];
cmd.func(user, channel, message, args);
} else {
if (message.toLowerCase() === 'botsnack') {
// Special case for botsnack
commands.botsnack.func(user, channel, message, []);
} else {
// If they didn't ask for a specific command, post a status.
commands.status.func(user, channel, message, [channel, message]);
}
}
}
});
// Read server notices
irc_client.on('notice', function(from, to, text) {
if (from === undefined) {
logger.info('Service Notice: ' + text);
from = '';
}
from = from.toLowerCase();
if (from === 'nickserv') {
authman.notice(from, text);
}
});
var commands = {
/* Post a message in all channels */
'announce': {
help: "Broadcast a message in all other channels.",
usage: "<message>",
func: function(user, channel, message, args) {
_.each(irc_client.chans, function(data, chan) {
if (chan !== channel) {
irc_client.say(chan, args.join(' '));
}
});
}
},
/* Blacklist a user to ignore their messages */
'blacklist': {
help: "Blacklist a user or show a list of blacklisted users.",
usage: "[<user>]",
func: function(user, channel, message, args) {
utils.ifAuthorized(user, channel, function() {
var nick = args[0];
if (nick) {
if (config.blacklist.indexOf(nick) === -1) {
pg_client.query("INSERT INTO blacklist" +
"(id, blacklisted_by) values " +
"('" + nick + "', '" + user + "')");
config.blacklist.push(nick);
irc_client.action(channel, 'Ignores ' + nick);
}
} else {
if (config.blacklist.length > 0) {
irc_client.say(channel, 'Blacklisted users:');
irc_client.say(channel, config.blacklist.join(', '));
} else {
irc_client.say(channel, 'No blacklisted users.');
}
}
});
}
},
/* Every bot loves botsnacks. */
'botsnack': {
func: function(user, channel, message, args) {
var replies = [
'Yummy!',
'Thanks, ' + user + '!',
'My favorite!',
'Can I have another?',
'Tasty!'
];
irc_client.say(channel, _.shuffle(replies)[0]);
}
},
/* Leave the channel */
'bye': {
help: "Ask the bot to leave the channel.",
func: function(user, channel) {
irc_client.say(channel, 'Bye!');
irc_client.part(channel);
// Remove the channel from the db
if (pg_client) {
pg_client.query("DELETE FROM channels WHERE id=$1", [channel]);
}
}
},
/* List all channels */
'chanlist': {
help: "Get a list of channels that I am in.",
func: function(user, channel) {
irc_client.say(channel, "I'm currently in:");
irc_client.say(channel, _.keys(irc_client.chans).sort().join(', '));
}
},
/* Delete a status by id number. */
'delete': {
help: "Delete a status by id.",
usage: "<id>",
func: function(user, channel, message, args) {
utils.ifAuthorized(user, channel, function() {
var id = args[0];
if (id[0] === '#') {
id = id.slice(1);
}
id = parseInt(id, 10);
if (isNaN(id)) {
irc_client.say(channel, '"' + args[0] + '" ' +
'is not a valid status ID.');
return;
}
var response = api.status.delete(id, user);
response.once('ok', function(data) {
irc_client.say(channel, 'Ok, status #' + id + ' is no more!');
});
response.once('error', function(code, data) {
data = JSON.parse(data);
if (code === 403) {
irc_client.say(channel, "You don't have permission " +
" to do that. Did you post that status?");
} else {
var error = "I'm a failure, I couldn't do it.";
if (data.error) {
error += ' The server said: "' + data.error + '"';
}
irc_client.say(channel, error);
}
});
});
}
},
/* Tell the bot to join a channel */
'goto': {
help: 'Tell the bot to join a channel.reg ',
usage: '<channel>',
func: function(user, channel, message, args) {
var join = args[0];
if (join[0] !== '#') {
join = '#' + join;
}
if (join) {
irc_client.join(join);
}
// Add channel to the db
if (pg_client) {
pg_client.query({
text: 'INSERT INTO channels(id, invited_by) values($1, $2)',
values: [join, user]
});
}
}
},
/* Provide a help system.
*
* To give a command a help message, define a 'help' field in it's object.
* If the help field is not present, the command will not be listed.
* To give a comand an arguments list, define a 'usage' field in it's object.
* If the usage field is not present, the command will not list a usage it's help message.
*/
'help': {
help: "This help message.",
func: function(user, channel) {
var command, help, usage;
irc_client.say(channel, 'Available commands:');
_.each(_.keys(commands).sort(), function(command) {
help = commands[command].help;
usage = commands[command].usage;
if (help !== undefined) {
var message = ['!' + command];
if (usage !== undefined) {
message.push(usage)
}
message.push('- ' + help);
irc_client.say(channel, message.join(' '));
}
});
}
},
/* Simple presence check. */
'ping': {
help: "A simple presence check.",
usage: undefined,
func: function(user, channel, message, args) {
irc_client.say(channel, "Pong!");
}
},
/* Create a status. */
'status': {
usage: "<project> status message",
func: function(user, channel, message, args) {
utils.ifAuthorized(user, channel, function() {
var project = args[0];
if (project[0] === '#') {
project = project.slice(1);
}
var status = args.slice(1).join(' ');
var response = api.status.create(user, project, status);
response.once('ok', function(data) {
irc_client.say(channel, 'Ok, submitted status #' + data.id);
});
response.once('error', function(err, data) {
irc_client.say(channel, 'Uh oh, something went wrong.');
});
});
}
},
/* Check a user's authorization status. */
'trust': {
help: "Check a user's authorization status.",
usage: "<user>",
func: function(user, channel, message, args) {
var a = authman.checkUser(args);
a.once('authorization', function(trust) {
if (trust) {
irc_client.say(channel, 'I trust ' + args);
} else {
irc_client.say(channel, "I don't trust " + args);
}
});
}
},
/* Update a user's settings */
'update': {
help: "Update the user's settings.",
usage: "<name|email|github_handle> <value> [<user>]",
func: function(user, channel, message, args) {
utils.ifAuthorized(user, channel, function() {
var what = args[0];
var value = args[1];
var who = args[2];
if (!who) {
who = user;
}
if (what && value) {
var response = api.user.update(user, what, value, who);
response.once('ok', function(data) {
irc_client.action(channel, "updates some stuff!");
});
response.once('error', function(code, data) {
if (code === 403) {
irc_client.say(channel, "You don't have " +
"permission to do that.");
} else {
var error = "I'm a failure, I couldn't do it.";
if (data.error) {
error += ' The server said: "' + data.error + '"';
}
irc_client.say(channel, error);
}
});
}
});
}
},
'whitelist': {
help: "Whitelist a user.",
usage: "<user>",
func: function(user, channel, message, args) {
utils.ifAuthorized(user, channel, function() {
var nick = args[0];
if (nick) {
config.blacklist = _.without(config.blacklist, nick);
pg_client.query("DELETE FROM blacklist WHERE id='" + nick + "'");
irc_client.say('Will do!');
}
});
}
},
/* The default action. Return an error. */
'default': {
func: function(user, channel, message) {
irc_client.say(channel, user + ': Huh? Try !help.');
}
}
};