Created
September 26, 2012 10:01
-
-
Save riston/3787123 to your computer and use it in GitHub Desktop.
IRC bot in Node.js
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
var net = require('net') | |
, util = require('util') | |
, exec = require('child_process').exec; | |
var options = { | |
PORT: 6667 | |
, HOST: 'irc.freenode.net' | |
, NICK: 'Miska' | |
, CHANNELS: [ '#node.js', '#javascript', '#randomChan' ] | |
, USER: { | |
ALLOWED: [ 'risto_' ] | |
} | |
}; | |
var command = [ | |
{ match: /^PING/, emit: 'pong' } | |
, { match: '@uptime', emit: 'uptime' } | |
]; | |
var socket = net.connect(options.PORT, options.HOST, function() { | |
console.log('Connection up to irc server'); | |
}); | |
socket.setEncoding('ascii'); | |
socket.setNoDelay(); | |
socket.on('connect', function() { | |
setTimeout(function() { | |
socket.write(util.format('NICK %s\n', options.NICK)); | |
socket.write(util.format('USER %s 8 *: %s\n', options.NICK, 'Full Name')); | |
socket.write(util.format('JOIN %s\n', options.CHANNELS.join(','))); | |
}, 10000); | |
}); | |
socket.on('timeout', function() { | |
console.log('TIMEOUT for connection'); | |
console.log('Total of bytes written: ' + socket.bytesWritten); | |
}); | |
/** | |
* Custom command for bot send the uptime | |
*/ | |
socket.on('uptime', function() { | |
var child = exec('uptime', function(err, stdout, stderr) { | |
if (err) throw err; | |
else { | |
options.CHANNELS.forEach(function(elem) { | |
var response = util.format('PRIVMSG %s :%s\n', elem, stdout); | |
console.log(response); | |
socket.write(response); | |
}); | |
} | |
}); | |
}); | |
socket.on('pong', function() { | |
console.log('PONG message back'); | |
socket.write('PONG\n'); | |
}); | |
socket.on('data', function(data) { | |
var cleanedData = data.toString().trim(); | |
console.log(cleanedData); | |
command.forEach(function(command) { | |
if (cleanedData.match(command.match)) { | |
socket.emit(command.emit); | |
} | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment