summaryrefslogtreecommitdiff
path: root/irc-client.js
diff options
context:
space:
mode:
Diffstat (limited to 'irc-client.js')
-rw-r--r--irc-client.js103
1 files changed, 103 insertions, 0 deletions
diff --git a/irc-client.js b/irc-client.js
new file mode 100644
index 0000000..bd8edb8
--- /dev/null
+++ b/irc-client.js
@@ -0,0 +1,103 @@
+var IRC = require('./node_modules/node-irc/irc').IRC;
+var util = require('util');
+var events = require('events');
+var _ = require('underscore');
+
+function info() {
+ var copy = [].slice.apply(arguments)
+ console.log('IrcClient: ' + copy.join(' '));
+}
+
+function Channel(name) {
+ this.name = name;
+ this.listeners = [];
+}
+
+Channel.prototype.addListener = function(f) {
+ this.listeners.push(f);
+};
+
+Channel.prototype.fire = function(event) {
+ _.each(this.listeners, function(f) {
+ f(event);
+ });
+};
+
+function IrcClient(nick, realName, ident, server, port, password) {
+ this.nick = nick;
+ this.realName = realName;
+ this.ident = ident;
+ this.server = server;
+ this.port = port;
+ this.password = password;
+
+ this.channels = {};
+ this.connected = false;
+ this.debugLevel = undefined;
+ this.irc = undefined;
+}
+util.inherits(IrcClient, events.EventEmitter);
+
+IrcClient.prototype.init = function(irc) {
+ // TODO: hmm..
+ var client = this;
+ this.debugLevel && irc.setDebugLevel(this.debugLevel);
+ irc.on('connected', function() {
+ info('Connected, channels: ' + _.size(client.channels));
+ _.each(client.channels, function(channel) {
+ info('JOINing ' + channel.name);
+ irc.join(channel.name);
+ });
+ });
+ irc.on('disconnected', function() {
+ info('Disconnected, reconnecting...');
+ client.connect();
+ });
+ irc.on('join', function(nick, channelName) {
+ _.each(client.channels, function(channel) {
+ info('JOINed ' + channel.name);
+ channel.fire(channelName);
+ });
+ });
+ irc.on('privmsg', function(nick, channel, message) {
+ client.emit('privmsg', nick, channel, message);
+ });
+ return irc;
+}
+
+IrcClient.prototype.getChannel = function(name) {
+ var c = this.channels[name];
+
+ if(typeof c == "undefined") {
+ c = new Channel(name);
+ this.channels[name] = c;
+ }
+
+ return c;
+}
+
+IrcClient.prototype.setDebugLevel = function(level) {
+ this.debugLevel = level;
+ this.irc && this.irc.setDebugLevel(level);
+}
+
+IrcClient.prototype.connect = function() {
+ this.irc = this.init(new IRC(this.server, this.port, this.password));
+ this.irc.connect(this.nick, this.realName, this.ident);
+}
+
+IrcClient.prototype.join = function(name, cb) {
+ var c = this.getChannel(name);
+ if(typeof cb != "undefined") {
+ c.addListener(cb);
+ }
+ if(this.connected) {
+ c.fire(name);
+ }
+}
+
+IrcClient.prototype.notice = function(to, message) {
+ this.irc.notice(to, message);
+}
+
+module.exports.IrcClient = IrcClient;