MonkeyBonkey
MonkeyBonkey

Reputation: 47901

how to receive and process a photo mms using twilio

Looking for an example, of how to receive and process images via mms to my app using Twilio.

Looking at the number configuration screen in the twilio dashboard, I assume that I set up an incoming phone number and a HTTP POST url to send incoming mms to. However, I'm not sure what gets posted to that url and don't know the structure of that data.

Does someone have an example of what data gets POSTed to the url and in what format? Any javascript examples of what data the server would process would be great.

Upvotes: 0

Views: 629

Answers (1)

tsturzl
tsturzl

Reputation: 3137

Firstly use the twilio-node module(npm install twilio). Once you have that in place, you can just access the webhook request body like you would any request body req.body.

As depicted in twilio's docs, the structure is like so:

{
   MessageSid: String, //ID pertaining to this message
   AccountSid: String, //ID pertaining to your twilio account
   From: String, //phone number of sender
   To: String, //recipients phone number, you in this case
   Body: String, //Message body
   NumMedia: Number, //number of attached media
   //these values only appear when media is present(NumMedia.length > 0)
   MediaContentType: [String] //type of content in SMS
   MediaUrl: [String] //URL to download the media
}

You can then do something like this using the twilio modules, caolan/async module, and the popular request/request module:

var twilio  = require('twilio'),
    fs      = require('fs'),
    async   = require('async'),
    request = require('request');

app.post('/mms', function(req, res) {
    var options = { url: 'https://subtle-gradient-188.herokuapp.com/twiml' };
    if (!twilio.validateExpressrequire(req, 'YOUR_TWILIO_AUTH_TOKEN', options)) return res.status(401).send("Bad key!");

    if(!req.body.hasOwnProperty('MediaUrl')) return res.send("Missing media...");

    var media = req.body.MediaUrl;

    //download all media
    async.map(media, download, function(err, filenames) {

        var resp = new twilio.TwimlResponse();
        if(err) {
            resp.say("Problem occured");
            console.log(err);
        }
        else resp.say('Files recieved: ' + filenames.join(', '));
        res.type('text/xml');
        res.send(resp.toString());
    });
});

//download a single url to a unique filename
function download(url, cb) {
    var name = Date.now() + url.split('/').pop();

    request
        .get(url)
        .on('error', cb)
        .on('end', function() {
            cb(null, name);
        })
        .pipe(fs.createWriteStream(name));
}

Upvotes: 2

Related Questions