Created
February 23, 2011 17:05
-
-
Save yeonwoonj/840728 to your computer and use it in GitHub Desktop.
super simple IRC bot (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 os = require('os'); | |
var net = require('net'); | |
// config | |
var con = net.createConnection(6667,'irc.freenode.net'); | |
var nick = '__YOURNICK__'; | |
var chan = '#__YOURCHANNEL__'; | |
var chatlogs = []; | |
var maxlines = 30; | |
// code | |
con.setEncoding('utf8'); | |
con.addListener('connect', function() { | |
// console.log('connected'); | |
con.write('NICK ' + nick + '\r\n'); | |
con.write('USER node node node NodeJS IRC BOT\r\n'); | |
con.write('JOIN ' + chan + '\r\n'); | |
}); | |
function sleep(secs) { | |
var last = os.uptime(); | |
while (true) { | |
var curr = os.uptime(); | |
var diff = curr - last; | |
if (diff < 0 || diff >= secs) { | |
return; | |
} | |
} | |
} | |
var stream = ''; | |
con.addListener('data', function(data) { | |
stream += data; | |
while (true) { | |
var pos = stream.indexOf('\r\n'); | |
if (pos == -1) { | |
return; | |
} | |
line = stream.substring(0, pos); | |
stream = stream.substr(pos+2); | |
if (line.indexOf('PING') != -1) { | |
con.write('PONG ' + line.split(/\s/)[1] + '\r\n'); | |
} | |
else if (line.indexOf('!nodebot quit') != -1) { | |
con.end('PRIVMSG ' + chan + ' :bye\r\n'); | |
} | |
else if (line.indexOf('PRIVMSG ' + chan + ' :') != -1) { | |
var who = line.substring(1, line.indexOf('!')); | |
var chat = line.substr(line.indexOf(':',1)); | |
//con.write('PRIVMSG ' + chan + ' :' + who + chat + '\r\n'); | |
chatlogs.push(who + chat); | |
if (chatlogs.length > maxlines) { | |
chatlogs.shift(); | |
} | |
} | |
else if (line.indexOf('JOIN :' + chan) != -1) { | |
var who = line.substring(1, line.indexOf('!')); | |
if (chatlogs.length > 0) { | |
for (var idx = 0; idx < chatlogs.length; idx++) { | |
con.write('PRIVMSG ' + who + ' :' + chatlogs[idx] + '\r\n'); | |
sleep(1); | |
} | |
con.write('PRIVMSG ' + who + ' :recent ' + chatlogs.length + ' chat log' + (chatlogs.length > 1 ? 's' : '') + '. ;-)\r\n'); | |
} | |
} | |
//console.log(line); | |
} | |
}); | |
con.addListener('close', function(had_error) { | |
console.log('connection closed: had_error=' + had_error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
does this work if run via google script app?