All files / lib TwilioSMSBot.js

4.6% Statements 4/87
0% Branches 0/44
0% Functions 0/15
4.65% Lines 4/86
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 2001x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                       1x  
var os = require('os');
var Botkit = require('./CoreBot');
var Twilio = require('twilio');
 
function TwilioSMS(configuration) {
 
    var twilioSMS = Botkit(configuration || {});
 
    if (!configuration) {
        throw Error('Specify your \'account_sid\', \'auth_token\', and ' +
            '\'twilio_number\' as properties of the \'configuration\' object');
    }
 
    if (configuration && !configuration.account_sid) {
        throw Error('Specify an \'account_sid\' in your configuration object');
    }
 
    if (configuration && !configuration.auth_token) {
        throw Error('Specify an \'auth_token\'');
    }
 
    if (configuration && !configuration.twilio_number) {
        throw Error('Specify a \'twilio_number\'');
    }
 
    twilioSMS.defineBot(function(botkit, config) {
 
        var bot = {
            type: 'twiliosms',
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances
        };
 
        bot.startConversation = function(message, cb) {
            botkit.startConversation(bot, message, cb);
        };
 
        bot.createConversation = function(message, cb) {
            botkit.createConversation(bot, message, cb);
        };
 
 
        bot.send = function(sms, cb) {
 
            var client = new Twilio(configuration.account_sid,
                configuration.auth_token);
 
 
            client.messages.create(sms, function(err, message) {
 
                if (err) {
                    cb(err);
                } else {
                    cb(null, message);
                }
 
            });
 
        };
 
        bot.reply = function(src, resp, cb) {
            var msg = {};
 
            if (typeof resp === 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }
 
            msg.channel = src.channel;
 
            if (typeof cb === 'function') {
                bot.say(msg, cb);
            } else {
                bot.say(msg, function() {});
            }
 
        };
 
        bot.findConversation = function(message, cb) {
 
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
 
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
 
                    var convo = botkit.tasks[t].convos[c];
                    var matchesConvo = (
                        convo.source_message.channel === message.channel ||
                        convo.source_message.user === message.user
                    );
 
                    if (convo.isActive() && matchesConvo) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
 
                }
            }
 
            cb();
        };
 
        return bot;
    });
 
    twilioSMS.handleWebhookPayload = function(req, res, bot) {
 
        twilioSMS.log('=> Got a message hook');
 
        var payload = req.body;
        twilioSMS.ingest(bot, payload, res);
 
    };
 
    twilioSMS.middleware.normalize.use(function(bot, message, next) {
 
        message.text = message.Body;
        message.user = message.From;
        message.channel = message.From;
 
 
        message.from = message.From;
        message.to = message.To;
 
        message.timestamp = Date.now();
        message.sid = message.MessageSid;
 
        next();
 
    });
 
    twilioSMS.middleware.format.use(function(bot, message, platform_message, next) {
 
        platform_message.body = message.text;
        platform_message.from = configuration.twilio_number;
        platform_message.to = message.channel;
 
        if (message.hasOwnProperty('mediaUrl')) {
            platform_message.mediaUrl = message.mediaUrl;
        }
 
        next();
 
    });
 
 
 
    // set up a web route for receiving outgoing webhooks
    twilioSMS.createWebhookEndpoints = function(webserver, bot, cb) {
 
        twilioSMS.log('** Serving webhook endpoints for Twilio Programmable SMS' +
            ' at: ' + os.hostname() + ':' + twilioSMS.config.port + '/sms/receive');
 
        var endpoint = twilioSMS.config.endpoint || '/sms/receive';
 
        if (twilioSMS.config.validate_requests === true) {
            webserver.post(endpoint, verifyRequest);
        }
 
        webserver.post(endpoint, function(req, res) {
            twilioSMS.handleWebhookPayload(req, res, bot);
 
            // Send empty TwiML response to Twilio
            var twiml = new Twilio.twiml.MessagingResponse();
            res.type('text/xml');
            res.send(twiml.toString());
        });
 
        if (cb) cb();
 
        return twilioSMS;
    };
 
    // validate that requests are coming from twilio
    function verifyRequest(req, res, next) {
        var twilioSignature = req.headers['x-twilio-signature'];
 
        var validation_url = twilioSMS.config.validation_url ||
            ((req.headers['x-forwarded-proto'] || req.protocol) + '://' + req.hostname + req.originalUrl);
 
        if (Twilio.validateRequest(twilioSMS.config.auth_token, twilioSignature, validation_url, req.body)) {
            next();
        } else {
            twilioSMS.log('** Invalid twilio signature on incoming request!');
            res.status(400).send({
                error: 'Invalid signature.'
            });
        }
    }
 
    twilioSMS.startTicking();
 
    return twilioSMS;
}
 
module.exports = TwilioSMS;