Twilio - Get request for call recording not working

56 views Asked by At

I am trying to attach an audio file containing the call recording to an E-Mail.

My code works with audio files from public urls, but not with the Twilio call recordings. I am sure the issue is with the authentication, so I tried to add it to my code, but now it is not working anymore.

What my code looks like right now:

const request = require('request');

// configure authentication
var auth = "Basic " + Buffer.from(context.accountSid + ":" + context.authToken).toString("base64");

// recording url
url = 'https://api.twilio.com/2010-04-01/Accounts/AC..../Recordings/' + event.recordingSid + '.mp3';

// request with authentication
const options = {
    url: url,
    headers: {
      'Authorization': auth,
    },
    encoding: null
};

// get audio file and attach to mail
request.get(options, (error, response, body) => {
    if (error) {
        console.error(error);
        return;
    };

    if (response.statusCode !== 200) {
        console.error("Failed to fetch Twilio recording:", response.statusCode, response.statusMessage);
        return;
    };

    const msg = {
        // some configuration for message
        attachments: [
          {
              content: body.toString('base64'),
              filename: 'Call.mp3',
              encoding: 'base64',
              type: "audio/mpeg"
          }
        ]
    };

    // send mail 
  });
};

The current error code I am getting is "REDACTED - may contain security sensitive information", but also "message":"self.uri.auth.split is not a function".

1

There are 1 answers

4
Ricardo Gellman On BEST ANSWER

I would first change your handling error and use request lib to handle it, and than invoke

const request = require('request');

const auth = "Basic " + Buffer.from(context.accountSid + ":" + context.authToken).toString("base64");
const headers = {'Authorization': auth};

const url = 'https://api.twilio.com/2010-04-01/Accounts/AC..../Recordings/' + event.recordingSid + '.mp3';

request.get({
    url: url,
    headers: headers,
    encoding: null  // Important to get binary data
}, (error, response, body) => {
    if (error) {
        console.error(error);
        return;
    }

    if (response.statusCode !== 200) {
        console.error("Failed to fetch Twilio recording:", response.statusCode, response.statusMessage);
        return;
    }


    const msg = {
        attachments: [
            {
                content: body.toString('base64'),
                filename: 'Call.mp3',
                encoding: 'base64',
                type: "audio/mpeg"
            }
        ]
    };

    // send mail using your sendMail function or library
    // sendMail(msg);
});