1

I have a twilio phone # that receives an SMS, which calls a Twilio protected function, which calls an external (Hologram.io) API. The call to the Twilio function succeeds, the call to Hologram.io succeeds, everything is working, but I always get this error and it's just really annoying. I do not get what is wrong.

enter image description here

Part of the body of the Twilio function:

enter image description here

jwallis
  • 75
  • 1
  • 9

2 Answers2

3

Twilio developer evangelist here.

Your Function is called by Twilio when you receive an SMS, so the response of the Function is going back to Twilio to tell it what to do. You do so by returning TwiML. This means that if you return TwiML like this, you will get a message sent back from the Twilio number:

const twiml = new Twilio.twiml.MessagingResponse();
twiml.message("Hello from your function");
callback(null, twiml);

In your code, you are returning the result of your API call to Hologram straight to Twilio. Since that result is JSON instead of TwiML, Twilio doesn't know what to do with it and you get an error.

If you don't want to respond to the incoming text message, you can return empty TwiML, like this:

instance.post('/api/1/sms/incoming', {
  // hologram data
})
.then((response) => {
  const twiml = new Twilio.twiml.MessagingResponse();
  callback(null, twiml);
});

Let me know if this helps.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • Brilliant, this is exactly what I needed! I had no idea that functions were supposed to return TwiML. Maybe I'm wrong, but this example doesn't seem to imply returning XML https://www.twilio.com/docs/runtime/quickstart/serverless-functions-make-a-write-request-to-an-external-api-json – jwallis Feb 12 '21 at 02:06
  • 1
    Functions can return whatever you want. But your Function is being called by a Twilio webhook, and the webhook expects the response to be TwiML. – philnash Feb 12 '21 at 02:09
  • Just want to say I think it's great that Twilio has a developer evangelist engaging with us in the social sphere. SO and other "social" platforms can make or break a company, and SO is a good knowledge bank, better than many home grown solutions. – jwallis Feb 13 '21 at 03:40
0

You need to return TwiML to Twilio rather then JSON, reference:

TwiML™ for Programmable SMS

Alan
  • 10,465
  • 2
  • 8
  • 9
  • My function is calling an External API at Hologram.io, which I have no control over. So it sounds like you're saying I'm going to have to live with the error...? – jwallis Feb 10 '21 at 21:13
  • 1
    You can just return empty TwiML to Twilio as @philnash suggested, instead of returning the 3rd party API response (JSON) back to Twilio, do don't return `response.data` in your callback. – Alan Feb 10 '21 at 23:59