imubot
Version:
A simple helpful bot.
86 lines (77 loc) • 2.54 kB
JavaScript
(function() {
const { EventEmitter } = require('events');
const User = require('./user');
function Brain(bot) {
// Inherit properties.
EventEmitter.call(this);
this.data = { users: {} };
bot.on("running", () => this.emit('connected'));
return this;
}
// Inherit prototype object.
Brain.prototype = Object.create(EventEmitter.prototype)
// Assign self.
Brain.prototype.constructor = Brain
Brain.prototype.close = function() {
clearInterval(this.saveInterval);
this.save();
return this.emit('close');
};
Brain.prototype.save = function() {
return this.emit('save', this.data);
};
Brain.prototype.mergeData = function(data) {
this.data = Object.assign(this.data, data)
return this.emit('loaded', this.data);
};
Brain.prototype.users = function() {
return this.data.users;
};
Brain.prototype.userForId = function(id, options) {
var user = this.data.users[id];
if (!user && options) {
user = new User(id, options);
this.data.users[id] = user;
}
if (options && options.room && (!user.room || user.room !== options.room)) {
user = new User(id, options);
this.data.users[id] = user;
}
return user || {};
};
Brain.prototype.userForName = function(name) {
var k, lowerName, result, userName;
result = null;
lowerName = name.toLowerCase();
for (k in this.data.users || {}) {
userName = this.data.users[k].name;
if (userName && userName.toString().toLowerCase() === lowerName) {
result = this.data.users[k];
}
}
return result || {};
};
Brain.prototype.usersForRawFuzzyName = function(fuzzyName) {
var key, lowerFuzzyName, ref, results, user;
var re = new RegExp(fuzzyName, 'i')
ref = this.data.users || {};
results = []
for (key in ref) {
re.test(fuzzyName) && results.push(ref[key]);
}
return results;
};
Brain.prototype.usersForFuzzyName = function(fuzzyName) {
var i, len, lowerFuzzyName, matchedUsers, user;
matchedUsers = this.usersForRawFuzzyName(fuzzyName);
lowerFuzzyName = fuzzyName.toLowerCase();
for (i = 0, len = matchedUsers.length; i < len; i++) {
user = matchedUsers[i];
if (user.name.toLowerCase() === lowerFuzzyName) {
return [user];
}
}
return matchedUsers;
};
module.exports = Brain;
}).call(this);