Search code examples
twiliotwilio-twiml

How do I make the endpoint hit from a TwiML redirect in a VoiceResponse return a MessagingResponse?


I have a situation where I want a TwiML VoiceResponse to call another endpoint which returns a MessagingResponse. However, I am getting an XML Validation warning for the MessagingResponse because of what I suspect is a mismatch in the inbound type (a call) and the outbound type (an SMS).

Please note that there is a requirement that I cannot use the Twilio client as suggested here https://support.twilio.com/hc/en-us/articles/360017437774-Combining-Voice-SMS-and-Fax-TwiML-in-the-Same-Response. I would like to achieve this with pure TwiML.

I have a call webhook set up on my Twilio phone number which hits a POST /call endpoint on my NodeJS server. The endpoint responds with TwiML which plays a tone and calls a redirect to another endpoint on my server.

TwiML returned:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Play digits="www9"/>
    <Redirect method="POST">[url-omitted]/notify</Redirect>
</Response>

Then, on the same server I have a second POST /notify endpoint which let's say, for simplicity, sends an SMS to a specific number.

TwiML returned from redirect endpoint:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message to="+11234567890">Hello world!</Message>
</Response>

Expected Result

The expected result is that when I call the Twilio number from my cellphone, I hear the "9" tone and then receive a text message with "Hello world!".

Actual Result

I only hear the "9" tone and never receive a text message.

When I look in the Twilio console, I can see that a call was made to the POST /notify endpoint, and it responded with the expected TwiML, but it has a 12200 - Schema validation warning.

Msg "XML Validation warning"
line    "2"
parserMessage   " Invalid content was found starting with element 'Message'. One of '{Play"
ErrorCode   "12200"
cols    "32"
LogLevel    "WARN"
url "https://handler.twilio.com/twiml/[id-omitted]"

As noted, I suspect the above error message is because this all originated from a call and not an SMS.


Solution

  • Twilio developer evangelist here.

    The <Message> TwiML verb is only usable during messaging flows, which is why you got the schema validation warning.

    You can use the deprecated <Sms> verb to send messages during voice calls, however I don't recommend this as it uses the old messaging API and doesn't handle things like unicode or messages longer than 160 characters.

    Instead, I recommend you use the Messages REST API to send messages during the call.