How to make phone calls and send SMS with Python

A complete guide to making phone calls and sending SMS via Python using Bandwidth APIs
Symbol for programming indicating how to make phone call and send SMS with Python

Bandwidth has a full suite of messaging API and voice API solutions to power your business needs. Whether you want to send MMS or SMS messages from toll-free numbers, local numbers, or short codes, Bandwidth’s APIs make it easy to enable in your software or platform, while Bandwidth’s relationships with the carriers give you reliable message delivery and insights. 

Introduction

In this article, you will see a quick overview of what sending your first message and creating your first call looks like when using Bandwidth’s Voice and Messaging APIs along with Bandwidth’s Python SDK. First, you will see some code examples and then at the end of this article is an explanation of the variables you would need to insert into the code to make the SDK work with your Bandwidth account.

Note: Python 2 was sunsetted on January 1, 2020, and is not supported by the Bandwidth SDK.

Additional resources:

Packages and client initialization

First, you need to install the packages needed for this example like this.

pip install bandwidth-sdk
pip install flask

You then need to require the SDK in your code and initialize the configuration for the SDK client.

from bandwidth.bandwidth_client import BandwidthClient

bandwidth_client = BandwidthClient(
    messaging_basic_auth_user_name="{username}",
    messaging_basic_auth_password="{password}",
    voice_basic_auth_user_name="{username}",
    voice_basic_auth_password="{password}"
)
voice_client = bandwidth_client.voice_client.client
messaging_client = bandwidth_client.messaging_client.client

How to send a text message with Python

Sending an SMS Message with Python from a Bandwidth number looks like this. This must be in the same file as your initiated client or the client must be imported here.

from bandwidth.messaging.models.message_request import MessageRequest

messagingBody = MessageRequest()
messagingBody.to = ["{to}"]
messagingBody.mfrom = "{from}"
messagingBody.text = "Hello, I am sending a message! How fun!"
messagingBody.application_id = "{app_id}"

messaging_client.create_message("{account_id}", body=messagingBody)

You will need to set up a server that can receive a callback/webhooks with a JSON body that will tell you if the message was successfully delivered or not. Some simple Python server code using sinatra that can process Bandwidth messaging callbacks could look like this.

from flask import Flask, request
import json

app = Flask(__name__)

@app.route("/messaging", methods=["POST"])
def messaging():
    data = json.loads(request.data)
    if (data[0].get("type") == "message-delivered"):
        //successful delivery action
        return ('', 200)
    if (data[0].get("type") == "message-failed"):
        failure_reason = data[0].get("description");
        //failed delivery action
        return ('', 200)
    return ('', 200)
app.run()

How to make a phone call with Python

Making a phone call with Python from a Bandwidth number looks like this. This must be in the same file as your initiated client or the client must be imported here.

from bandwidth.voice.models.api_create_call_request import ApiCreateCallRequest

voiceBody = ApiCreateCallRequest()
voiceBody.to = "{to}"
voiceBody.mfrom = "{from}"
voiceBody.answer_url = "{url}" 
voiceBody.application_id = "{app_id}"
voice_client.create_call("{account_id}", body=voiceBody)

When the call is answered by whoever you sent the call to, Bandwidth will send a callback/webhook with a JSON body to the URL you specified when you created the call. You can send BXML verbs back to Bandwidth in response to the callback/webhook to create new actions on the call. Some simple server code that would make the call play some text-to-speech audio and then hang up could look like this:

from bandwidth.voice.bxml.response import Response
from bandwidth.voice.bxml.verbs import *
from flask import Flask, request
import json

app = Flask(__name__)

@app.route("/voice", methods=["POST"])
def voice():
    data = json.loads(request.data)
    if (data.get("eventType") == "answer"):
        response = Response()
        speak_sentence = SpeakSentence(
            sentence="I am saying something and now will hang  up.",
            voice="julie"
        )
        hangup = Hangup()

        response.add_verb(speak_sentence)
        response.add_verb(hangup)

        return response.to_bxml()
     return ('', 200)

app.run()

And that’s it! That’s how simple it is to create your first message and call with a Bandwidth phone number, Bandwidth’s API, and Bandwidth’s Python SDK.

Variable Reference

Here is an explanation of the variables used in the above code that will be unique to your account and use case.

Variable Name Explanation
username your username for the Bandwidth App
password your password for the Bandwidth App
app_id the ID of your messaging or voice application; applications are set within the Bandwidth App and are used to associate your Bandwidth phone numbers with URLs for callback/webhooks
from_number when creating outgoing messages or calls, the number you are sending to; this can be your cell phone number for testing or the number of one of your customers
to_number when creating outgoing messages or calls, this is a number you have been assigned by Bandwidth that lives on your Bandwidth App account
account_id your Bandwidth App account ID
URL a URL you own that to which Bandwidth will send callbacks/webhooks related to call and messaging events; note that for messaging, this URL is not set at the time of message creation and is instead defined by the Bandwidth App application used to send the message

24/7 human support for Bandwidth’s APIs

Not just enterprise-grade APIs, get enterprise-scale support too, 24/7.