Get Started with Python

    Sign up for a Plivo Account

    Whenever a customer signs up with Plivo, they are provided with a free trial account to experiment with our services. This free trial account is given free credits for testing and using the same credits you can go ahead and purchase a number by navigating here. Once you have a number and credits in your account, you are all set to start testing our voice and SMS service.

    Register here to get your free Plivo account today.

    Below are the steps that are to be followed to successfully Sign up for a free trial account.

    1. Sign up with your corporate email address

    2. You will receive an activation email from Plivo. Click on the link mentioned in the email to activate your account.

    3. Enter an sms enabled, non-VOIP number to complete the phone verification.

    Sign up with your corporate email address

    Sign up with email addres

    If you are facing any issues while creating a Plivo account, you can reach out to our Support Team

    Install Python and the Plivo Python Server SDK

    To get started with Sending your First SMS, you have to set up Python and install Plivo Python SDK.

    Install Python

    Operating SystemInstructions
    OS X & LinuxYou would already have Python installed, you can check this by running the command python --version in the terminal
    WindowsTo install Python on Windows you can follow the instructions from here.

    Install Plivo Python Package

    Install the SDK using pip

    pip install plivo
    

    Alternatively, you can download the source code from this repo and run

    python setup.py install
    

    For features in beta, use the beta branch:

    pip install plivo==4.2.0b1
    

    Alternatively, you can download the source code from this repo(beta branch) and run

    python setup.py install
    

    We recommend that you use virtualenv to manage and segregate your Python environments, instead of using sudo with your commands and overwriting dependencies.

    Send your first Outbound SMS

    We’ll see how to use Plivo APIs to send SMS messages from your web application. Let’s have a look at some prerequisites before we dive into the code.

    • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo Console. Click here to sign-up for a Plivo account if you haven’t already!

    credentials

    • Plivo Phone Number: You must have a SMS-enabled Plivo phone number to send messages to the US and Canada. You can purchase numbers from the Numbers section of your Plivo Console. It is also possible to purchase numbers using the Numbers API.

    Buy New Number

    Create a file called SendSMS.py and paste the below code.

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    
    import plivo
    
    client = plivo.RestClient()
    message_created = client.messages.create(
        src='plivo_src_number',
        dst='the_destination_number',
        text='Hello, world!'
    )
    
    Note:
    • Replace the placeholders auth_id & auth_token with your credentials from Plivo Console
    • Replace the placeholder plivo_source_number with the Phone number which you have purchased and the_destination_number with the phone number you will be sending SMS text messages to.
    • Both plivo_source_number and the_destination_number should be in E.164 format, for example +15671234567.

    save the file and use the below command to run it.

    python SendSMS.py
    
    Note: If you are using a Plivo Trial account for this example, you can only send sms to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

    Set up a Flask server for Incoming Messages & Callbacks

    In this section, you will learn how to set up a Flask server in under 5 minutes and start handling Incoming Messages & Callbacks.

    Plivo supports receiving SMS text messages in 9 countries (see complete SMS API coverage). When an SMS is sent to a Plivo phone number, you can receive the text on your server by setting a Message URL in your Plivo app. Plivo will send the message along with other parameters to your Message URL.

    Setup a virtual env (optional)

    Go to the directory where you want to write the code for your server. We will first set up a virtual environment so that the packages installed won’t interfere with the system ones.

    To create a virtual environment with the name env_name use the following command.

    virtualenv env_name
    

    This creates a directory with the name env_name along with the required binaries inside it. The next step is to activate the virtual environment so you can start using it.

    source env_name/bin/activate
    

    You should now see that your CLI is in the env_name environment. The next time you do a pip install some_package it would installed in this environment and will not over-write the system versions.

    Once you are done with your development and want to return to the normal environment, you can deactivate this environment using

    deactivate
    

    Set up a Flask server

    Use the following code snippet to start a local server.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    from flask import Flask, request
    
    app = Flask(__name__)
    
    @app.route('/receive_sms/', methods=['GET', 'POST'])
    def inbound_sms():
    
        from_number = request.values.get('From')
        to_number = request.values.get('To')
        text = request.values.get('Text')
        print('Message received - From: %s, To: %s, Text: %s' %(from_number, to_number, text))
    
        return 'Message Recevived'
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    

    Save this code in any file (let’s say the file name is receive_sms.py). To run this file on the server, go to the folder where this file resides and use the following command:

      python receive_sms.py
    

    And you should see your basic server app in action on http://localhost:5000/receive_sms/

    Exposing your local server to the internet

    To receive Incoming Messages and to handle callbacks, your local server should be able to connect with Plivo API service, Ngrok is a tunneling software used to expose a web server running on your local machine to the internet. Using Ngrok you can set webhooks which can talk to Plivo server.

    ngrok block diagram

    You can download and install ngrok from here. Follow the detailed configuration instructions to get started.

    Run ngrok on the port which currently hosts your application. For example, if your port number is 80, run the following command:

    ./ngrok http <port_on_which_your_local_server_is_running>
    

    This will give you a UI with links that look like ngrok.io/* which you can use to access your local server using the public network.

    ngrok

    Create an Application

    1. Create an Application by visiting the Application Page and click on New Application or by using Plivo’s Application API.
    2. Give your application a name. Let’s call it Receive SMS. Enter your server URL (e.g. http://example.com/receive_sms/) in the Message URL field and set the method as POST. See our Application API docs to learn how to modify your application through our APIs.
    3. Click on Create to save your application.

    Create Application

    Assign a Plivo number to your app

    1. Navigate to the Numbers page and select the phone number you want to use for this app.
    2. Select Receive SMS (name of the app) from the Plivo App dropdown list.
    3. Click on Update to save.

    Assign Phone Number to Receive SMS App

    Test it out

    Send an SMS to your Plivo number using a regular mobile phone. Plivo will send a request to your Message URL with the parameters listed in the XML Request - Messages Documentation.

    Reply to an incoming SMS

    When an SMS is sent to an Plivo phone number, you can receive the text on your server by setting a Message URL in your Plivo app. Plivo will send the message along with other parameters to your Message URL. You can reply back using the Plivo Message XML.

    Note: In order to reply to a US or Canadian phone number, the `'src'` (source) phone number must be a Plivo US or Canadian phone number that is SMS-enabled. You can purchase a Plivo number from the Buy Numbers tab on your Plivo Console and filter the Phone Numbers by selecting SMS in the features option to buy SMS enabled numbers.

    Create a file called reply_to_sms.py and paste the below code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    from flask import Flask, request, make_response, Response
    from plivo import plivoxml
    
    app = Flask(__name__)
    
    @app.route('/reply_to_sms/', methods=['GET', 'POST'])
    def inbound_sms():
    
        from_number = request.values.get('From')
        to_number = request.values.get('To')
        text = request.values.get('Text')
        print('Message received - From: %s, To: %s, Text: %s' %
              (from_number, to_number, text))
    
        # send the details to generate an XML
        response = plivoxml.ResponseElement()
        response.add(
            plivoxml.MessageElement(
                'Thank you, we have received your request',
                src=to_number,  
                dst=from_number))
        print(response.to_string())  # Prints the XML
        # Returns the XML
        return Response(response.to_string(), mimetype='application/xml')
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
    
    Note: Create an application in the Plivo console with your Server URL in the message_URL field and assign the app to a Plivo number.

    Test it out

    Send an SMS to your Plivo number using a regular mobile phone and an automatic response will be sent from your Plivo number to your mobile phone. Also, Plivo will send a request to your Message URL with the parameters listed in the XML Request - Messages Documentation.