Skip to content

Instantly share code, notes, and snippets.

@CBenni
Created Jan 22, 2016
Embed
What would you like to do?
var net = require('net');
var events = require('events');
var rx = /^(?:@([^ ]+) )?(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$/;
var rx2 = /([^=;]+)=([^;]*)/g;
var rx3 = /\r\n|\r|\n/;
var STATE_V3 = 1
var STATE_PREFIX = 2
var STATE_COMMAND = 3
var STATE_PARAM = 4
var STATE_TRAILING = 5
function parseIRCMessage(message) {
var data = rx.exec(message);
var tagdata = data[STATE_V3];
if (tagdata) {
var tags = {};
do {
m = rx2.exec(tagdata);
if (m) {
tags[m[1]] = m[2];
}
} while (m);
data[STATE_V3] = tags;
}
return data;
}
function IRCBot(host, port, onconnect) {
var self = this;
self.client = new net.Socket();
self.send = function(data) {
self.client.write(data+'\n');
}
self._buffer = "";
self.connect = function() {
self.client.connect(port, host, function() {
self.emit('connect');
});
}
var buffer = new Buffer('');
self.client.on('data', function(chunk) {
if (typeof (chunk) === 'string') {
buffer += chunk;
} else {
buffer = Buffer.concat([buffer, chunk]);
}
var lines = buffer.toString().split(rx3);
if (lines.pop()) {
return;
} else {
buffer = new Buffer('');
}
lines.forEach(function(line) {
var parsed = parseIRCMessage(line);
parsed[STATE_COMMAND] == "PING" && self.send("PONG");
self.emit('raw', parsed);
self.emit(parsed[STATE_COMMAND], parsed);
});
});
self.client.on('close', function() {
self.emit('disconnect');
});
// client.destroy();
}
IRCBot.prototype = new events.EventEmitter;
exports = module.exports = IRCBot;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment