Twilio - 2 Ways of Sending Text Message
Twilio allows software developers to programmatically make and receive phone calls and send and receive text messages using its web service APIs.
Twilio's web service API gives developers the ablity to make and receive phone calls and text messages. Below are two ways that you can use the text message feature:
- Sending Messages Only: A script that runs on the terminal that takes in a phone number and sends a single text message to that phone number
- Sending & Receiving Messages: A server that processes text messages to a Twilio number and responses back with a text depending on the senders message
Sending messages only
This code is a single function that takes in a phone number and uses Twilio's api to create an instance. The instance needs your Twilio account SID, token and Twilio phone number which you get from Twilio.This code is in python and you'll need to create a virtual env and install Twilio.[code language="text"]$ virtualenv envNew python executable in env/bin/pythonInstalling setuptools, pip, wheel...done.$ source env/bin/activate(env)$ pip install twilio...lots of statements...[/code]In a python file, you'll also need to source your Twilio token, sid and phone number (there is a guide where to get your Twilio token and sid):[code language="python"]TWILIO_ACCOUNT_SID=os.environ.get("TWILIO_ACCOUNT_SID")TWILITO_AUTH_TOKEN=os.environ.get("TWILIO_AUTH_TOKEN")TWILIO_NUMBER=os.environ.get("TWILIO_NUMBER")[/code]The script uses raw_input to get the phone number; to make sure the phone number is formatted the way Twilio is expecting we are passing the phone number into the convert_to_e164 function. Now that the phone number is formatted corrected, it can be passed it into the function send_text_message. This function creates an instant of the Twilio Rest API and passes in a default message, the phone number and your Twilio phone number.[code language="python"]raw_phone_number = raw_input("Enter a phone number that you would like to send a text message to: ")phone_number = convert_to_e164(raw_phone_number)send_text_message(phone_number)[/code]
send_text_message function:
[code language="python"]client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKENmessage = client.message.create(body= "Your a kickass programmer",to = phone,from_ = TWILIO_NUMBER,)[/code]
To pull it all together, you can run that script on the terminal and input a phone number and it'll send the text "Your a kickass programmer" to that number!
Check out the code here
Sending & Receiving Message
Using Flask as the framework
For this capability, you'll need to have a server and a way to protect your server. In this example, I am using flask as our server and ngrok to transmit the local server's protocol. You'll need to add flask to you virtual environment.[code language="text"](env)$ pip install flask...lots of statements...[/code]Once that's done, you'll need to set up a route that Twilio will send request to. You can get the message that was texted by getting the values of the 'Body' of the request.[code language="python"]@app.route("/", methods=["GET","POST"])def hello():"""Sends text messages"""message = request.values["Body"].lower()[/code]The request also has other meta data that you can obtain and use (i.e. datetime, user's phone number). At this point, you can add any logic you want in regards to how you want to handle different users, this example I have a dictionary with keys of possible responses from the user and the value is the response I want to send to them. I add my message to a Twilio response instant and return the instant.[code language="python"]resp = twilio.twiml.Response()resp.message(responses.get(message, "boo"))return str(resp)[/code]Now that you have the logic of how you want to handle the text messages, you'll need to connect your server to Twilio's webhook. But you won't want to expose your server, so we'll use ngrok to tunnel between your local server we just created and Twilio. You'll need to download ngrok and run it:[code language="text"]$ ./ngrok http 5000[/code]So now, your ngrok server is running and it'll forward any request to your local server. You'll connect your ngrok to Twilio by going into your Twilio account and then into your phone number account under Messaging and add the ngrok http: At this point, your ngrok is running and connected to Twilio, you can start your flask server and its all ready. Text your Twilio number and your route will text you back based on what you wrote.
Check out the full code here
note: if you stop your ngrok and restart it, the http will changed and you'll need to update your phone number webhook.
Twilio Access Tokens
Go to your Twilio console dashboard or account settings and you'll find your account sid and click on the auth token to reveal your token hash.You'll want to create a secret.sh file that contains your access tokens:[code language="python"]export TWILIO_ACCOUNT_SID="##########"export TWILIO_AUTH_TOKEN="###########"export TWILIO_NUMBER="+##########"[/code]To give your terminal access to these variables, you just need to source them:[code language="text"](env)$ source secret.sh[/code]
Enjoy texting everyone you know!