Monday, January 7, 2019

Using Twilio with Python to send SMS

Twilio is a web API which can be used to add communications such as phone calling, messaging, video and two-factor authentication in Python applications.

Twilio's API abstracts the telecommunications pieces so as a developer you can simply use your favorite programming languages and frameworks in your application and use Twilio to embed voice, VoIP, and messaging into applications. To use Twilio service we need to install the twilio module and then sign up for the free Twilio service. The free trial is indefinite; so we won’t have to upgrade to a paid plan later. To install the twilio module use pip install twilio command as shown below:


Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Python>pip install twilio
Collecting twilio
  Downloading https://files.pythonhosted.org/packages/21/2e/91af5c8e20400792e62c
19bacc197c4b7b8a7fbef1cac5ec9c73944facff/twilio-6.22.1-py2.py3-none-any.whl (986
kB)
    100% |████████████████████████████████| 993kB 1.3MB/s
Collecting PyJWT>=1.4.2 (from twilio)
  Downloading https://files.pythonhosted.org/packages/87/8b/6a9f14b5f781697e5125
9d81657e6048fd31a113229cf346880bb7545565/PyJWT-1.7.1-py2.py3-none-any.whl
Requirement already satisfied: pytz in c:\users\python\appdata\roaming\python\py
thon36\site-packages (from twilio) (2018.5)
Collecting pysocks; python_version >= "3.0" (from twilio)
  Downloading https://files.pythonhosted.org/packages/53/12/6bf1d764f128636cef74
08e8156b7235b150ea31650d0260969215bb8e7d/PySocks-1.6.8.tar.gz (283kB)
    100% |████████████████████████████████| 286kB 898kB/s
Requirement already satisfied: six in c:\users\python\appdata\roaming\python\pyt
hon36\site-packages (from twilio) (1.11.0)
Requirement already satisfied: requests>=2.0.0; python_version >= "3.0" in c:\us
ers\python\appdata\local\programs\python\python36\lib\site-packages (from twilio
) (2.21.0)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\python\appdata\
local\programs\python\python36\lib\site-packages (from requests>=2.0.0; python_v
ersion >= "3.0"->twilio) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\python\appdata\loc
al\programs\python\python36\lib\site-packages (from requests>=2.0.0; python_vers
ion >= "3.0"->twilio) (2018.11.29)
Requirement already satisfied: idna<2.9,>=2.5 in c:\users\python\appdata\local\p
rograms\python\python36\lib\site-packages (from requests>=2.0.0; python_version
>= "3.0"->twilio) (2.8)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in c:\users\python\appdata\
local\programs\python\python36\lib\site-packages (from requests>=2.0.0; python_v
ersion >= "3.0"->twilio) (1.24.1)
Installing collected packages: PyJWT, pysocks, twilio
  Running setup.py install for pysocks ... done
Successfully installed PyJWT-1.7.1 pysocks-1.6.8 twilio-6.22.1

C:\Users\Python>


After installing twilio Sign up for Twilio and get your first SMS-enabled Twilio phone number. Go to http://twilio.com/ and fill out the sign-up form. Once you’ve signed up for a new account, you’ll need to verify a mobile phone number that you want to send texts to.

Twilio provides your trial account with a phone number to use as the sender of text messages. You will need two more pieces of information: your account SID and the auth (authentication) token. You can find this information on the Dashboard page when you are logged in to your Twilio account. These values act as your Twilio username and password when logging in from a Python program.

Now that we are ready with our twilio account we'll make a program to send text message using twilio. See the program below:

# import the Twilio helper library (installed with pip install twilio)
from twilio.rest import Client

accountSID = 'AC89892hkkjkiuiui12344'
authToken = '1234556778hghgfjgjjkkkkkl'

twilioclient = Client(accountSID, authToken)
myTwilioNumber = '+191234456777'
myCellPhone = '+9123345451'

smsText = twilioclient.messages.create(body='Mr. Satya - Howdy! - Awaiting project status.', from_=myTwilioNumber, to=myCellPhone)


After a short duration a text message will be received that reads Sent from your Twilio trial account - Mr. Satya - Howdy! - Awaiting project status. 

We first import twilio module using from twilio.rest import Client. This depends on the version of twilio we are using. I am using twilio 6.22.1 if you are using twilio 5.x then you need to use from twilio.rest import TwilioRestClient.

Next I've stored my account SID in accountSID and my auth token in authToken and then call Client() or TwilioRestClient() and pass it accountSID and authToken. The call to Client() or TwilioRestClient() returns a  Client or TwilioRestClient object.

This object has a messages attribute, which in turn has a create() method we use to send text
messages. This is the method that will instruct Twilio’s servers to send your text message. After storing myTwilio number and cell phone number in myTwilioNumber and myCellPhone, respectively, call create() and pass it keyword arguments specifying the body of the text message, the sender’s number (myTwilioNumber), and the recipient’s number (myCellPhone)

The Message object returned from the create() method is stored in smsText and this will have information about the text message that was sent. We can use the smsText variable as shown in the below program:


# import the Twilio helper library (installed with pip install twilio)
from twilio.rest import Client

accountSID = 'AC89892hkkjkiuiui12344'
authToken = '1234556778hghgfjgjjkkkkkl'

twilioclient = Client(accountSID, authToken)
myTwilioNumber = '+191234456777'
myCellPhone = '+9123345451'

smsText = twilioclient.messages.create(body='Mr. Satya - Howdy! - Awaiting project status.', from_=myTwilioNumber, to=myCellPhone)

print(smsText.to)
print(smsText.from_)
print(smsText.body)
print(smsText.status)
print(smsText.date_created)
print(smsText.date_sent)
print(smsText.sid)

The output of the program is shown below:

+918639664301
+19382222190
Sent from your Twilio trial account - Mr. Satya - Howdy! - Awaiting project stat
us.
queued
2019-01-07 07:48:44+00:00
None
SM8aaed0faf80a46648e4eb7c270fe2ed9
------------------
(program exited with code: 0)

Press any key to continue . . .

The to, from_, and body attributes hold the cell phone number, Twilio number, and message, respectively. The status attribute give you a string. The date_created and date_sent attributes give you a datetime object if the message has been created and sent. It may seem odd that the status attribute is set to 'queued' and the date_sent attribute is set to None when you’ve already received the text message. This is because you captured the Message object in the smsText variable before the text was actually sent. You will need to refetch the Message object in order to see its most up-to-date status and date_sent.



Share:

0 comments:

Post a Comment