Posted by: Eric Hansen
When I wrote the original code I made things way too complicated for it. So, I’ll steer you in the direction of NOT doing that, and we’ll make this simple!
After our import lines, add these:
TWILIO_SID = "xxx" TWILIO_AUTH = "yyy" TWILIO_NUMBER = "zzz"
The xxx and yyy will be replaced by whatever values you noted down/get from the Twilio dashboard. You also need to set your Twilio number as well so the service will know who to set the “From” field to.
Now we need to create a reference to Twilio’s API, which also requires us to send the SID and AUTH values:
client = TwilioRestClient(TWILIO_SID, TWILIO_AUTH)
We’ll work on SMS first since its cheaper and easier to work with. First what we need to do is create a route for SMS:
@app.route("/sms", methods=['GET', 'POST']) def sms(): try: client.sms.messages.create(body="Huzzah!", to="+1xxxyyyzzzz", from_=TWILIO_NUMBER) return "SMS sent." except TwilioRestException, e: return "Unable to send. Reason: %s" % (e.msg)
For sake of this project right now replace the hard-coded number “+1xxxyyyzzzz” with the number you signed up for with Twilio (demo accounts can’t send to just any number, paid accounts can) and visit /sms to receive a text message. Pretty cool, huh?! Lets change this a little bit and make it so when a GET request is made to the page it’s sent to a number specified. Here’s the new code block:
@app.route("/sms/") def sms(number): try: client.sms.messages.create(body="Huzzah!", to="+1%d" % number, from_=TWILIO_NUMBER) return "SMS sent." except TwilioRestException, e: return "Unable to send. Reason: %s" % (e.msg)
We made some changes here. First, we removed the ‘methods’ argument to app.route. This was done because we want to just focus on handling GET requests right now, which Flask defaults to when methods is not passed. Next is the route. Now we need to visit /sms/10-digit-number-here to make it work (replacing the “10-digit-number-here” part with the verified number). We still need to pass that info to the method itself so we can use it, and also modify the ‘to’ field so it still sends properly. Now, try again and it should still work!