/
index.js
379 lines (313 loc) · 10.7 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
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
var util = require("util");
var events = require("events");
var Client = require("./client");
var utilities = {
escape_regex: (function() {
var cache = {};
return function(string) {
if (typeof cache[string] !== "undefined") return cache[string];
cache[string] = string.replace(/[.*+?|()\\[\\]{}\\\\]/g, "\\$&");
return cache[string];
}
})(),
merge: function(defaults, options) {
if (typeof options === "undefined") return defaults;
var o = {};
for (var i in defaults) {
if (defaults.hasOwnProperty(i)) {
o[i] = typeof options[i] === "undefined" ? defaults[i] : options[i];
}
}
return o;
}
};
/**
* events:
* 'command_not_found': function (channel, user, command);
**/
var Bot = module.exports = function(profile) {
// Confirm profile object is in correct form
if (!Array.isArray (profile))
profile = [profile];
for (var i = 0, len = profile.length; i < len; i++) {
if (!profile[i] || typeof profile[i] !== "object") {
throw new Error("Bot constructor: profile[" + i + "] is not an object.");
}
}
this.__profile = profile;
this.__listening = [];
// Used to identify message as command for bot
this.__trigger = '!';
this.__log_level = this.LOG_NONE;
this.__commands = {};
this.__commands_regex = null;
this.__trigger_changed = true;
process.on('uncaughtException', function(err) {
process.stderr.write("\n"+err.stack+"\n\n");
});
/*this.nickname_regex =
/^[A-Z\x5B-\x60\x7B-\x7D][-0-9A-Z\x5B-\x60\x7B-\x7D]{0,16}$/i;*/
};
util.inherits(Bot, events.EventEmitter);
Bot.prototype.init = function() {
// Connect to each IRC server
for (var i = 0, len = this.__profile.length; i < len; i++) {
var client = new Client(this.__profile[i]);
client.on("welcome", this.listeners.welcome.bind(this));
client.on("disconnect", this.listeners.disconnect.bind(this));
client.on("join", this.listeners.join.bind(this));
client.on("message", this.listeners.message.bind(this));
client.on("pm", this.listeners.pm.bind(this));
client.on("error", this.listeners.error.bind(this));
client.on("invite", this.listeners.invite.bind(this));
Bot.prototype.log.call(this, this.LOG_CONNECT, client.name, "Connecting...");
client.connect();
}
};
Bot.prototype.LOG_NONE = 0; // No logging
Bot.prototype.LOG_CONNECT = 1; // Log server connections
Bot.prototype.LOG_JOIN = 2; // Log channel joins/parts
Bot.prototype.LOG_COMMANDS = 4; // Log messages triggering commands
Bot.prototype.LOG_LISTENS = 8; // Log messages matching listeners
Bot.prototype.LOG_OUTGOING = 16; // Log anything the bot sends
Bot.prototype.LOG_INCOMING = 32; // Log anything the bot receives
Bot.prototype.LOG_UNKNOWN = 64; // Log unknown commands received from the server
Bot.prototype.LOG_ALL = -1; // Log everything
function pad2(n){ return ('0' + n).slice(-2); }
Bot.prototype.log = function(level, message) {
var d = new Date(),
D = d.getDate(),
M = d.getMonth() + 1,
Y = d.getFullYear(),
h = d.getHours(),
m = d.getMinutes(),
s = d.getSeconds(),
date = [Y, pad2(M), pad2(D)].join('-'),
time = [pad2(h), pad2(m), pad2(s)].join(':');
if (arguments.length > 2)
message = Array.prototype.slice.call(arguments, 1).join(" ");
if (this.__log_level == this.LOG_ALL || (level & this.__log_level))
util.puts("[" + date + " " + time + "] " + message);
};
Bot.prototype.set_log_level = function(level) {
this.__log_level = level;
};
/**
* Listens for message matching the specified regex and calls the callback
* function with:
*
* callback(context, text, 1st subpattern, 2nd subpattern, ...);
**/
Bot.prototype.register_listener = function(regex, callback, options) {
this.__listening.push({
regex: regex,
callback: callback,
options: utilities.merge({
allow_intentions: true // Parse `@ nick` after message
}, options)
});
};
/**
* Add a new command to listen for: callback is called with (context, result)
* - result: the text that comes after the command
**/
Bot.prototype.register_command = function(command, callback, options) {
command = command.toLowerCase();
switch (typeof callback) {
case "function":
this.__commands[command] =
{callback: callback,
options: utilities.merge({
allow_intentions: true, // Parse `@ nick` after message
hidden: false, // Show command in results from get_commands()
help: "No help for `"+command+"`"
}, options)};
break;
case "string":
callback = callback.toLowerCase();
if (this.__commands.hasOwnProperty(callback)) {
// The command is going to be an alias to `callback`
this.__commands[command] = this.__commands[callback];
} else {
throw new Error(
"Cannot alias `"+command+"` to non-existant command `"+callback+"`");
}
break;
default:
throw new Error(
"Must take a function or string as second argument to register_command");
}
};
/**
* compile_commands: Compiles a RegExp object
* ahead-of-time to listen for commands.
**/
Bot.prototype.compile_command_listener = function() {
if (this.__trigger_changed) {
var identifier = utilities.escape_regex(this.__trigger);
this.__commands_regex = new RegExp("^\\s*"+identifier+"\\s*((\\S+)\\s*(.*))$");
}
};
Bot.prototype.parse_intent = function(str) {
var parsed = str.match(/^(.*?)\s*@\s*([A-Z\x5B-\x60\x7B-\x7D][-0-9A-Z\x5B-\x60\x7B-\x7D]{0,16})$/i);
if (!parsed) return false;
return {
intent: parsed[2],
result: parsed[1]
};
};
Bot.prototype.get_commands = function() {
var array = [];
for (var i in this.__commands) {
if (this.__commands.hasOwnProperty(i)) {
if (!this.__commands[i].options.hidden) array.push(i);
}
}
return array.sort();
};
Bot.prototype.get_command_help = function(command) {
if (this.__commands.hasOwnProperty(command)) {
return this.__commands[command].options.help;
}
throw new Error("`"+command+"` is not a command.");
};
// Set the character that you use to signal a command to the bot
Bot.prototype.set_trigger = function(c) {
this.__trigger = c;
this.__trigger_changed = true;
};
Bot.prototype.quit = function() {
process.exit();
};
Bot.prototype.listeners = {
disconnect: function(client, why) {
Bot.prototype.log.call(this, this.LOG_CONNECT, client.name,
"Disconnected ("+why+"), reconnecting in 15s");
var bot = this;
setTimeout(function() {
Bot.prototype.log.call(bot, bot.LOG_CONNECT, client.name,
"Connecting...");
client.connect();
}, 15000);
},
welcome: function(client) {
if (client.timeout) {
clearTimeout(client.timeout);
client.timeout = null;
}
var channels = client.profile.channels;
for (var i = 0, len = channels.length; i < len; i++) {
Bot.prototype.log.call(this, this.LOG_JOIN, client.name, "Joining", channels[i]+"...");
client.get_channel(channels[i]).join();
}
this.emit("connect", client);
},
join: function(channel) {
this.emit("join", channel);
Bot.prototype.log.call(this, this.LOG_JOIN, channel.client.name, "Joined", channel.name);
},
pm: function(user, text) {
this.emit("pm", user, text);
var context = {
channel: user,
client: user.client,
sender: user,
intent: user,
priv: true
};
var trimmed = text.trim();
// Check if message matches listeners
for (var i = 0, len = this.__listening.length; i < len; i++ ) {
var result = trimmed.match(this.__listening[i].regex);
if (result) {
this.__listening[i].callback.apply(this,
[context, trimmed].concat(result.slice(1)));
Bot.prototype.log.call(this, this.LOG_LISTENS, user.client.name,
"PM "+user.name+":", trimmed);
return;
}
}
var command_matches;
if (command_matches = text.match(/^\s*((\S+)\s*(.*))$/)) {
var full = command_matches[1];
var command = command_matches[2].toLowerCase();
var parameters = command_matches[3];
Bot.prototype.log.call(this, this.LOG_LISTENS, user.client.name,
"PM "+user.name+":", text);
if (this.__commands.hasOwnProperty(command)) {
this.__commands[command].callback.call(this, context, parameters, command);
} else {
this.emit('command_not_found', context, full);
}
return;
}
},
message: function(channel, user, text) {
this.emit("message", channel, user, text);
var context = {
channel: channel,
client: channel.client,
sender: user,
intent: user,
priv: false
};
text = text.trim();
Bot.prototype.compile_command_listener.call(this);
var command_matches = text.match(this.__commands_regex);
if (command_matches) {
var full = command_matches[1];
var command = command_matches[2].toLowerCase();
var parameters = command_matches[3];
Bot.prototype.log.call(this, this.LOG_LISTENS, channel.client.name, channel.name+":",
"<"+user.name+">", text);
/**
* TODO: Great I spilled something.. somehow make this DRY..
**/
if (this.__commands.hasOwnProperty(command)) {
if (this.__commands[command].options.allow_intentions) {
var intent_obj = Bot.prototype.parse_intent.call(this, parameters);
if (intent_obj) {
parameters = intent_obj.result;
context.intent = channel.client.get_user(intent_obj.intent);
}
}
this.__commands[command].callback.call(this, context, parameters, command);
} else {
var intent_obj = Bot.prototype.parse_intent.call(this, full);
if (intent_obj) {
full = intent_obj.result;
context.intent = channel.client.get_user(intent_obj.intent);
}
this.emit('command_not_found', context, full);
}
return;
}
var trimmed = text.trim();
// Check if message matches listeners
for (var i = 0, len = this.__listening.length; i < len; i++ ) {
if (this.__listening[i].options.allow_intentions) {
var intent_obj = Bot.prototype.parse_intent.call(this, trimmed);
if (intent_obj) {
trimmed = intent_obj.result;
context.intent = channel.client.get_user(intent_obj.intent);
}
}
var result = trimmed.match(this.__listening[i].regex);
if (result) {
this.__listening[i].callback.apply(this,
[context, trimmed].concat(result.slice(1)));
Bot.prototype.log.call(this, this.LOG_LISTENS, channel.client.name, channel.name+":",
"<"+user.name+">", trimmed);
return;
}
}
},
error: function (client, command, message) {
Bot.prototype.log.call(this, this.LOG_UNKNOWN, client.name, command, message);
},
invite: function (client, user, channel) {
Bot.prototype.log.call(this, this.LOG_INVITE, client.name,
"Received invitation from " + user.name + " to " + channel.name);
this.emit("invite", user, channel);
}
};