Created
July 4, 2012 22:37
-
-
Save niwinz/3049898 to your computer and use it in GitHub Desktop.
Evented Irc Client/lib on NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Irc(host, port, nick){ | |
this._host = host; | |
this._port = port; | |
this._nick = nick; | |
} | |
Irc.prototype.setChannels = function(channels) { | |
this._chans = channels; | |
} | |
Irc.prototype.log = function(msg){ | |
if (this._debug) console.log(msg); | |
} | |
Irc.prototype.connect = function(handlers){ | |
var _sock = new net.Socket(); | |
var _chans = this._chans; | |
var _nick = this._nick; | |
_sock.setEncoding('utf-8'); | |
/* Regex */ | |
_rx_privmsg = /:([\w\d\-\_]+).*@([\d\.\w]+)\s+PRIVMSG\s+([\#\w\-\_]+)\s+:(.*)/; | |
_rx_ping = /PING\s+:(.*)/; | |
_rx_notice = /:([\d\.\w]+)+\s+NOTICE\s+\*\s+:(.*)/; | |
_sock.connect(this._port, this._host, function() { | |
//Irc.log("Connected to " + this._host + ":"+ this._port); | |
console.log("Connected"); | |
// Send identify data; | |
_sock.write("NICK " + _nick + "\n\r"); | |
_sock.write("USER " + _nick + " nodejs nodejsbot :" + _nick + "\n\r") | |
// Connect to channels if exists; | |
if (_chans.length > 0){ | |
_chans.forEach( function(chan){ | |
_sock.write("JOIN " + chan + "\n\r"); | |
}); | |
} | |
// Init eventloop; | |
this.on('data', function(data){ | |
var matches = null | |
if (matches = data.match(_rx_ping)){ | |
this.write("PONG " + matches[1] + "\n\r"); | |
} | |
else if (matches = data.match(_rx_privmsg)){ | |
if (handlers.on_privmsg){ | |
// args: nick, chan, msg | |
handlers.on_privmsg(matches[1], matches[3], matches[4]); | |
} | |
} | |
else if (matches = data.match(_rx_notice)){ | |
if (handlers.on_notice){ | |
// args: server, msg | |
handlers.on_notice(matches[1], matches[2]); | |
} | |
} | |
}); | |
}); | |
// Error handling; | |
if (handlers.on_error){ | |
_sock.on('error', handlers.on_error); | |
} | |
else { | |
_sock.on('error', function(exception) { | |
console.log("Internal error: " + exception); | |
}); | |
} | |
} | |
var handlers = { | |
on_error: function(exception){ | |
console.log("Error: " + exception); | |
}, | |
on_privmsg: function(nick, chan, msg){ | |
console.log("Nick:" + nick + " Chan:" + chan + " Msg:" + msg); | |
}, | |
on_notice: function(server, msg){ | |
console.log("Notice [" + server + "]: " + msg); | |
} | |
} | |
var irc = new Irc('irc.freenode.net', 6667, 'niwibot'); | |
irc.setChannels(['#archlinux-co']); | |
irc.connect(handlers); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment