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.

$ virtualenv env
New python executable in env/bin/python
Installing setuptools, pip, wheel...done.
$ source env/bin/activate
(env)$ pip install twilio
...lots of statements...

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):

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")

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.

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)

send_text_message function:

client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN

message = client.message.create(
    body= "Your a kickass programmer",
    to = phone,
    from_ = TWILIO_NUMBER,
)

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!

twiliosmmexample.png

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.

(env)$ pip install flask
...lots of statements...

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.

@app.route("/", methods=["GET","POST"])
def hello():
  """Sends text messages"""

  message = request.values["Body"].lower()

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.

resp = twilio.twiml.Response()
resp.message(responses.get(message, "boo"))

return str(resp)

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:

$ ./ngrok http 5000

ngrok.png

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:

Screen Shot 2016-12-18 at 10.42.37 AM.png

 

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.

accountkeysapicreditation

You’ll want to create a secret.sh file that contains your access tokens:

export TWILIO_ACCOUNT_SID="##########"
export TWILIO_AUTH_TOKEN="###########"
export TWILIO_NUMBER="+##########"

To give your terminal access to these variables, you just need to source them:

(env)$ source secret.sh

Enjoy texting everyone you know!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s