Emilio Garcia Emilio Garcia - 18 days ago 8
Python Question

Schema validation warning from forwarding SMS with Twilio/Flask

My code takes an incoming SMS text message, extracts the body, and forwards the body to another number. (tPhone is the Twilio number and ePhone is the number I want messages forwarded to)

import twilio.twiml
from flask import Flask, request, redirect
from twilio.rest import TwilioRestClient
from passwords import *

client = TwilioRestClient(account_sid, auth_token)

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def AlertService():
TheMessage=request.form.get("Body")
if (TheMessage != None):
print(TheMessage)
client.messages.create(to=ePhone, from_=tPhone, body=TheMessage)
return str(TheMessage)

if __name__ == "__main__":
app.run(debug=True,host="0.0.0.0")


The code works (message gets forwarded) but the Twilio debugger tells me


Content is not allowed in prolog.

Warning - 12200

Schema validation warning

The provided XML does not conform to the Twilio Markup XML schema.


How can I fix the XML being sent to Twilio?




Edit: Some things I've found. Even if I set 'TheMessage' to a predefined string (ex.
TheMessage="hello"
) I receive the same error from Twilio.

Additionally, if I try to generate and send the XML, I still get the same error.

resp = twiml.Response()
XML = resp.message(TheMessage)
print(XML)
client.messages.create(body=str(XML),to=ePhone,from_=tPhone)


The code fails to send if I try
body=XML
and if I try
body=str(XML)
it just sends the XML as plaintext.

Answer

Twilio developer evangelist here.

At the moment it looks as though you are using the REST API to forward the SMS message. While you can do it this way, it's easier to use TwiML to do it within the request using the <Message> verb. In your second example you appear to be trying to use TwiML and the REST API together and that's not going to work.

So, you just want to build up a TwiML response, add the message to it if there is an incoming message and then use the <Message> attributes to and from to forward it on to your phone number. Like this:

import twilio.twiml
from flask import Flask, request, redirect
from passwords import *

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def AlertService():
    TheMessage=request.form.get("Body")
    resp = twiml.Response()
    if (TheMessage != None):
        resp.message(TheMessage, to=ePhone)
    return str(resp)

if __name__ == "__main__":
    app.run(debug=True,host="0.0.0.0")

Let me know if that helps at all.