astroworld85
astroworld85

Reputation: 47

Node js twillio webhook - outgoing call not working

My goal here is for twillio to call a webhook, and then to have a few node js functions record what the user says, and then make an outgoing call to another phone number and play that recording.

However, I can't seem to get an outgoing call set up. The code works in a regular node js file, but as soon as it is called as a part of the webhook, it won't work:

const accountSid = 
const authToken = 
const client = require('twilio')(accountSid, authToken);

exports.handler = function(context, event, callback) {


  console.log(event.CallSid, event.RecordingUrl);
  console.log()
  console.log("RECORDING URL: " + event.RecordingUrl + ".mp3");

  let audioURL = event.RecordingUrl
  audioURL+=".mp3";

  const response = new Twilio.twiml.VoiceResponse();



  response.say({ voice: 'woman', language: 'en-US' }, 'Thank you.');

  client.calls
      .create({
         from: '+14********',
         to: '+14***********',
         url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3'
       })



  callback(null, response);
};

Upvotes: 1

Views: 245

Answers (1)

philnash
philnash

Reputation: 73100

Twilio developer evangelist here.

The issue here is that you are making the asynchronous request to make the call and then calling the callback immediately. That terminates the execution of the Twilio Function, and because it is immediate cancels that outbound API request. See the documentation on Twilio Function execution for more details.

To fix this you should only call the callback once the create function has completed.

As an extra tip, you can also get an authenticated client from the context object without having to load your accountSid or authToken yourself.

Also, in your example the URL you are providing for the outbound call appears to be an mp3. Your URL should return TwiML, or you can send TwiML as part of the API request.

I would update your function like so:

exports.handler = function(context, event, callback) {
  console.log(event.CallSid, event.RecordingUrl);
  console.log()
  console.log("RECORDING URL: " + event.RecordingUrl + ".mp3");

  let audioURL = event.RecordingUrl
  audioURL+=".mp3";

  const client = context.getTwilioClient();

  const response = new Twilio.twiml.VoiceResponse();

  response.say({ voice: 'woman', language: 'en-US' }, 'Thank you.');

  client.calls
      .create({
         from: '+14********',
         to: '+14***********',
         twiml: `<Response><Play>${audioUrl}</Play></Response>`
       })
       .then(() => {
         callback(null, response);
       })
       .catch(error => {
         callback(error);
       });
};

Upvotes: 1

Related Questions