| Send SMS through Twilio from Node.js |
| Node.js |
| Wednesday, 29 September 2010 12:43 |
|
There are two Twilio client libraries available for Node.js (that I could find). The first is aaronblohowiak's Twilio-Node and the second is guille's node.twilio.js. What I needed to do was to send an SMS message and neither library provided an example of how to do this. I'm not sure if they just neglected it or if they figured that a library wasn't necessary for accessing a simple REST interface. So here is my implementation of a simple module for sending SMS messages through Twilio from a Node.js application. I would have just used the http module except that the Twilio API leverages HTTP Basic Authentication which you can manually do using the http module, but it is a pain. restler makes it must easier. var rest = require('./vend/restler/lib/restler'), sys = require('sys'), config = require('../config'); var sendSMS = function(opt, callback) { var accountSid = config.twilio.accountSid, authToken = config.twilio.authToken, apiVersion = '2010-04-01', uri = '/'+apiVersion+'/Accounts/'+accountSid+'/SMS/Messages', host = 'api.twilio.com', fullURL = 'https://'+accountSid+':'+authToken+'@'+host+uri, from = opt.from || config.twilio.fromPhoneNumber, to = opt.to, body = opt.body; rest.post(fullURL, { data: { From:from, To:to, Body:body } }).addListener('complete', function(data, response) { callback(); }); }; exports.sendSMS = sendSMS; |