0

I'm attempting to run code that responds to a text message sent through twilio and using ngrok. The code works to reply but since it halts the program, I am trying to have it run alongside other things in a loop. The current error is

"Traceback (most recent call last):
  File "/home/pi/JustTheMessagePost.py", line 32, in <module>
    sms()
  File "/home/pi/JustTheMessagePost.py", line 17, in sms
    number = request.form['From']
  File "/usr/lib/python3/dist-packages/werkzeug/datastructures.py", line 431, in __getitem__
    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand."

The code I have relating to this:

#Setup

import time
from twilio.rest import Client
from flask import Flask, request, current_app
from twilio.twiml.messaging_response import Message, MessagingResponse

# Example value given by sensors
temperature = 5


#def inbound_sms():
app = Flask(__name__)
@app.route("/twilio", methods=['POST'])
def sms():
    global CPUTemp
    number = request.form['From']
    message_body = request.form['Body']
    resp = MessagingResponse()
    response_message = 'This is the general Reply text'
    resp.message(response_message)
    if message_body == 'Tester':
        resp.message(temperature)
    else:
        print('No text')        
    return str(resp)

#Loop
while True:
    print("Test Text")
    with app.test_request_context():
        sms()
    time.sleep(5)
    

I'm very new to using flask and webhooks so any help is appreciated.

1 Answers1

0

Twilio developer evangelist here.

I don't think you need to run your app in a loop and that is likely causing the issues. Instead, you need to start the Flask server and let it wait for incoming connections.

There is a great post on the Twilio blog about how to run a Flask application which I recommend you read.

To start with, I think you should replace your while loop with the following:

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

That will run your Flask application and it will display the port number it is listening on. You can then use that port number with ngrok to create the tunnel through to your application and set the ngrok URL as your webhook URL. For more on receiving and responding to SMS message webhooks from Twilio with Flask, check out this blog post as well.

philnash
  • 70,667
  • 10
  • 60
  • 88
  • Thanks for your answer! This definitely lets it work but I want it to be part of a larger code that has sensors collecting data every several seconds. Is there any way I can have it run alongside without halting the program? Thanks! – Terminal Velocity Oct 20 '20 at 06:14
  • There are some good answers regarding [threading](https://stackoverflow.com/questions/50804420/run-code-alongside-a-flask-application) or [other methods](https://stackoverflow.com/questions/27465533/run-code-after-flask-application-has-started) for running a Flask app alongside other code. Do they help at all? – philnash Oct 20 '20 at 06:18
  • They did help! Thanks! – Terminal Velocity Oct 20 '20 at 12:33