Skip to content
This repository has been archived by the owner on Nov 14, 2017. It is now read-only.

Command event #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions lib/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,52 @@ module.exports.Bot = (function() {
this.password = options.password;
this.debug = options.debug;
this.name = options.name;

// Emit a `command` event.
//
// A command is either a private message or a message on a channel directed
// to the bot starting with '@bot' or 'bot:' (but not just 'bot').
//
// Listeners are passed:
//
// - `message`: the message
// - `reply`: a function to call to reply, passing it a message
//
// If the command was received on a channel, the bot's name is stripped from
// the message and the user's name is added to the response.
//
// (Not sure what the right place for this would be)
this.on('message', function(channel, from, message) {
function firstName(name) {
return name.split(' ')[0];
}

var botNick = preg_quote(this.name)+'|'+preg_quote(firstName(this.name));
if (m = message.match(new RegExp('^\\s*(@?)('+botNick+')(:?)\\s*(.*)$', 'i'))) {
var at = m[1], colon = m[3], message = m[4];

if (!at && !colon)
return; // maybe just talking about the bot (not aimed at it)

var bot = this;
this.emit('command', message, function(reply) {
// Only use first name for response, so HipChat colors it nicely.
bot.message(channel, '@' + firstName(from) + ' ' + reply);
});
}

// Not sure if a native JS function exists somewhere?
function preg_quote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
});

this.on('privateMessage', function(from, message) {
var bot = this;
this.emit('command', message, function(reply) {
bot.message(from, reply);
});
});
};

util.inherits(Bot, events.EventEmitter);
Expand Down