Install Python, Sanic, and the Plivo Python SDK
You must set up and install Python, Sanic, and Plivo’s Python SDK before you send your first SMS message.Install Python
Download and install Python from its official site.Install Sanic and the Plivo Python SDK
Create a project directory and change into it.$ mkdir mypythonapp
$ cd mypythonapp
Install Sanic and the Plivo Python SDK using pip.$ pip install sanic plivo
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/MMS message
You must have a Plivo phone number to send messages to the US or Canada; you can rent a Plivo number from Phone Numbers > Buy Numbers on the Plivo console or via the Numbers API.Set up a Sanic server
Create a file called SendSMS.py and paste into it this code.import plivo
client = plivo.RestClient('<auth_id>','<auth_token>')
message_created = client.messages.create(
src='<sender_id>',
dst='<destination_number>',
text='Hello, from Sanic!')
print(message_created)
import plivo
client = plivo.RestClient('<auth_id>','<auth_token>')
message_created = client.messages.create(
src='<sender_id>',
dst='<destination_number>',
media_ids=['801c2056-33ab-499c-80ef-58b574a462a2'],
text='Hello, MMS from Sanic!',
media_urls=['https://media.giphy.com/media/26gscSULUcfKU7dHq/source.gif'],
type_='mms')
print(message_created)
Replace the auth placeholders with your authentication credentials from the Plivo console. Replace the phone number placeholders with actual phone numbers in E.164 format (for example, +12025551234). In countries other than the US and Canada you can use a sender ID for the message source.Note: We recommend that you store your credentials in the auth_id and auth_token environment variables to avoid the possibility of accidentally committing them to source control. If you do this, you can initialize the client with no arguments and Plivo will automatically fetch the values from the environment variables. You can use os.environ to store environment variables and fetch them when initializing the client.
Test
Save the file and run it.Receive your first inbound SMS/MMS message
To receive incoming messages, you must have a Plivo phone number that supports SMS; you can rent numbers from the Numbers page of the Plivo console or by using the Numbers API.Set up a Sanic server
Create a file called receive_sms.py and paste into it this code.import plivo
from plivo import plivoxml
from sanic import Sanic
from sanic.response import text
app = Sanic("Plivo SMS App")
@app.route("/receive_sms/", methods=["POST", "GET"])
async def receive_sms(request):
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 Received"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
import plivo
from plivo import plivoxml
from sanic import Sanic
from sanic.response import text
app = Sanic("Plivo SMS App")
@app.route("/receive_sms/", methods=["POST", "GET"])
async def receive_sms(request):
from_number = request.values.get("From")
to_number = request.values.get("To")
text = request.values.get("Text")
media_url = request.values.get("Media0")
print("Message received - From: %s, To: %s, Text: %s, Media: %s" % (from_number, to_number, text, media_url))
return "Message Received"
Save the file and run it.You should see your basic server application in action at http://localhost:8000/receive_sms/.Expose your local server to the internet
To receive incoming messages, your local server must connect with Plivo API services. For that, we recommend using ngrok, which exposes local servers running behind NATs and firewalls to the public internet over secure tunnels. Using ngrok, you can set webhooks that can talk to the Plivo server.Note: Before starting the service, add ngrok in the allowed hosts list in the settings.py file in your project.
ALLOWED_HOSTS = ['.ngrok.io']
Run ngrok on the command line, specifying the port that hosts the application on which you want to receive messages (80 in this case):This starts the ngrok server on your local server. Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.Now people can send messages to your Plivo number.Create a Plivo application to receive messages
Associate the controller you created with Plivo by creating a Plivo application. Visiting Messaging > Applications and click Add New Application. You can also use Plivo’s Application API.Give your application a name — we called ours Receive SMS. Enter the server URL you want to use (for example https://<yourdomain>.com/receive_sms/) in the Message URL field and set the method to POST. Click Create Application to save your application.Assign a Plivo number to your application
Navigate to the Numbers page and select the phone number you want to use for this application.From the Application Type drop-down, select XML Application.From the Plivo Application drop-down, select Receive SMS (the name we gave the application).Click Update Number to save.Test
Send a text message to the Plivo number you specified using any phone.Reply to an incoming SMS/MMS message
To receive incoming messages, you must have a Plivo phone number that supports SMS; you can rent numbers from the Numbers page of the Plivo console or by using the Numbers API.Set up a Sanic server
Create a file called reply_to_sms.py and paste into it this code.import plivo
from plivo import plivoxml
from sanic import Sanic
from sanic.response import text
app = Sanic("Plivo SMS App")
@app.route("/reply_to_sms", methods=["POST", "GET"])
async def reply_to_sms(request):
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(
"This is an automatic response", 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", port=8000)
If you haven’t done so already, expose your local server to the internet.Create a Plivo application to reply to messages
Associate the controller you created with Plivo by creating a Plivo application. Visiting Messaging > Applications and click Add New Application. You can also use Plivo’s Application API.Give your application a name — we called ours Reply Incoming SMS. Enter the server URL you want to use (for example http://<yourdomain>.com/replysms/) in the Message URL field and set the method to POST. Click Create Application to save your application.Assign a Plivo number to your application
Navigate to the Numbers page and select the phone number you want to use for this application.From the Application Type drop-down, select XML Application.From the Plivo Application drop-down, select Reply Incoming SMS (the name we gave the application).Click Update Number to save.Test
Send a text message to the Plivo number you specified using any phone. You should receive a reply.More use cases
We illustrate more than a dozen use cases with code for both API/XML and PHLO on our documentation pages.