Python 007: SMS Integration

This will help you:

Learn how to send and receive texts in Python programs

In this activity, you'll learn how to use Twilio, a text messaging API, to send and recieve texts in a Python program. You could use this to send yourself reminders, have conversations with a chatbot on your phone, or send alerts to the users of a program.

Time: 1-3 hours / Level: B2

You should already:

  • Have a basic understanding of Python

  • Download the Twilio API and create a free account (see directions in Step 1)

Get the code and resources for this activity by clicking below. It will allow you to download the files from a Google Drive folder. Unzip the folder and save it in a sensible location.

Glossary

  • API - Application Programming Interface, a way of interacting with an application (usually one hosted online) through a written program.

  • Auth token - Authorization token, a secret code programmers get in order to use an API.

  • Virtual Environment - An isolated version of your programming environment, so that installed packages and changes to environment variables don't mess with your computer's operating environment.

  • Server - a computer where a program connected to the internet is running. If the server stops running the program, it will not be usable.

  • Localhost - 127.0.0.1, the local IP address of your computer for when it's just talking to itself.

  • Port - essentially, a channel for communicating over the internet with a certain IP address. Each address has many ports.

  • IP Address - Internet Protocol address. It's like the phone number for computers (personal/client computers or websites/servers.) However, sometimes the IP address for a computer can change.

Step 1: Warm-up - Register with & download Twilio

Click on this link and register for a free Twilio account. This will allow you to get an active phone number to use in programs, and send a limited number of texts. The free trial account includes a limited amount of credit you can use to send messages. It requires payment to continue using after your credit has run out, but you do not need to add any payment information to use your free trial.

Read the instructions here for setting up your account.

Install Twilio by typing pip install Twilio in the terminal.

Here is a quickstart guide for using Twilio with Python. It's very helpful, but you do about the same things in the following steps.

Step 2: Warm-up - Sending a text

Open the file send_text.py and read the comments to understand what is happening. Add your credentials from your Twilio account, and your own phone number as the recipient. You may notice that you must use a Twilio-provided number for the sender, and a number you have validated for the receiver. Then, run it by typing python send_text.py in the terminal.

Your account SID and auth token are like a secret username and password that you, and only you, use in your own programs to show Twilio's services who you are and prove you can use their services. In general, web APIs (Application Programming Interfaces) use an auth token for each user, so that they can control who is making requests to the application, and how many requests they are making. It takes resources to make the API available and handle requests, and someone making many, many requests in a short period of time could make the service unavailable for other users.

It's not a good idea to post your account SID or auth token anywhere else. If you're using an API in a project you are sharing, here are tips for storing your credentials so that you don't have to frequently add and remove them in your code.

Step 3: Activity - Preparing to receive messages

To receive and handle messages with Twilio, you will need to run a very minimal web app. We're going to use Flask for this, and you can learn more about Flask in the Flask web app activity.

To start, go to this tutorial and follow the steps to set up Flask. It starts by helping you set up a virtual environment, which keeps your environment for a project from changing how your computer's normal operating environment is set up. You can read more about virtual environments here if you are curious.

To activate the virtual environment, source is not a command in Windows. Instead, after running virtualenv --no-site-packages . (yes, include the '.') you should run scripts/activate. If you ever want to deactivate, run:

cd scripts
deactivate
cd ..

When installing requirements, just type pip install -r requirements.txtrequirements.txt is included with this activity, but you can update it if you need to.

Read run_flask.py and then type python run_flask.py to run your web app. Here is the link to your web app.

If that works, move on to the next part of the tutorial to direct incoming messages to your program.

Follow the directions here to download ngrok. You'll need to create a count to get an auth token, but it's very simple. You'll need to extract/unzip the files, then open a new terminal window, and go to the folder containing ngrok.exe, something like this:

cd /users/{USERNAME}/{DOWNLOAD_FOLDER}/{NGROK_FOLDER} ./ngrok authtoken YOUR_AUTH_TOKEN

That will save your auth token to ngrok's configuration file.

Then, in a separate terminal window with this activity folder open, run python run_flask.py. Back in the terminal window with ngrok, run ./ngrok http 5000 (or a different port number than 5000. run_flask.py should print Running on http://127.0.0.1:PORT_NUMBER/.)

If ngrok starts correctly, copy the Forwarding https... URL into your browser, and add '/sms' or whatever address you gave to @app.route().

What's happening?

You're running a program that posts some text on your home IP address (127.0.0.1) on a port (probably 5000). Your home IP address is local to your computer, so anyone else trying to connect to it would just be connecting to their own computer. ngrok talks to your local connection on the given port, and posts the data it gets online at a unique, temporary URL. If you end the program running, the data will no longer be available. If you end ngrok, the connection between your local host address and the internet will end, and the URL ngrok gave you will become meaningless.

Step 4: Activity - Receiving messages

Go to this part of the tutorial to learn how to receive messages when your program is running. The code for run.py in their tutorial is in recv_text.py in this activity folder.

Remember that when you quit/end ngrok, the URL will become useless, and when you restart it you need to update the URL in your Twilio settings as the tutorial describes. If it's not working, the most likely problem is that you forgot to add '/sms' or whatever routing address you used to the URL in Twilio's settings.

Step 5: Make it your own

Write a program that sends a text to the number +1XXXXXXXXXX. It's the number of a phone hidden in the Foundry, and it will buzz when you text it. Try and find the hidden phone by sending repeated messages to it.

Step 6: Going further

The 'Where To Next?' section of the tutorial has suggestions for next steps once you have done this. The API documentation shows how to build a lot of different things, but the Twilio Quest page is a pretty cool way to keep learning: it makes a game out of learning to build different programs.