Instantly share code, notes, and snippets.

Embed
What would you like to do?
irc bot written in javascript for nodejs
{
"nickname": "xnodeuser",
"username": "xnodeuser",
"hostname": "myhost",
"servername": "myserver",
"realname": "xnodeuser",
"channel": "#xnodeuser"
}
const net = require('net');
const config = require('./config.json');
const protocol = require('./protocol.js');
const [host, port] = process.argv.slice(2);
const user = [
config.username,
config.hostname,
config.servername,
config.realname
].join(' ');
const client = net.createConnection({host, port}, () => {
client.write(`USER ${user}\r\n`);
client.write(`NICK ${config.nickname}\r\n`);
client.write(`JOIN ${config.channel}\r\n`);
});
const send = text => client.write(`${text}\r\n`);
const handle = function handle (message) {
protocol
.filter((handler) => message.match(handler.pattern))
.forEach((handler) => {
console.log(`==> Found: ${handler.pattern}`);
const groups = message.match(handler.pattern);
for (let text of handler.action(...groups)) {
send(text);
}
});
};
client.on('data', (data) => {
const message = data.toString();
console.log(message);
handle(message);
});
function* ping (raw, target) {
yield `PONG ${target}`;
}
function* greet (raw, user, target) {
yield `PRIVMSG ${target} :hello ${user}!`;
yield `PRIVMSG ${target} :I've missed you!`;
}
module.exports = [
{ pattern: /^PING :(.+)/, action: ping},
{ pattern: /^:(.+)!.+@.+ PRIVMSG (.+) :hello/, action: greet},
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment