Search code examples
pythonsmstwiliomessaginghttp-status-code-400

Twilio SMS Repsonse


I'm playing around with Python and Twilio, attempting to setup an automated response to an SMS. The response comes through when I send a text but none of the other details. My test server also gives a 400 bad request, so it's not understanding what's being requested. I may just be using incorrect syntax since I compiled this code from different examples and text. If anyone know what I'm doing incorrectly or knows the correct syntax I would appreciate the help.

from flask import Flask, request
from twilio.twiml.messaging_response import *

#initialize Flask application
app = Flask(__name__)

#route for handling request on endpoint
@app.route("/sms", methods=['POST', 'GET'])

def inbound_sms():
    #gets number that text is sent from
    inbound_num = request.form['From']
    #gets message that was sent
    message_body = request.form['Body']

    reply = MessagingResponse()
    #Sends reply with attached details
    reply.message("Thank you!".format(inbound_num, message_body))
    return str(reply)

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

Solution

  • Twilio developer evangelist here.

    You are not receiving the number and body in the message because you are missing something in your string formatting. You need to add placeholders for where the number and body will slot into the string using {}. Like this:

    reply.message("Thank you! Number: {}. Body: {}".format(inbound_num, message_body))
    

    I don't know why your application would be responding with a 400 response though. It looks correct to me and if Twilio is sending the response then it should be working.