Lead Alerts Application Migration from Twilio to CarrierX

If you have read the Migrating from Twilio to CarrierX Quick Start, you could see that both Twilio and CarrierX provide similar means, which allow their users to send voice calls and text messages, and all you need is to change the representation of these instructions in your code.

But when it comes to a real-case migration from Twilio to CarrierX, users might meet some difficulties.

Let’s see such a migration in details and learn how to solve the issues that arise so that your migrated application worked with CarrierX flawlessly.

Getting Application Source Code

We take the Lead Alerts application from Twilio as an example. This sample application accepts some values in the inputs of the home webpate and then sends a text message to the administrator with these entered details. You can download the application source code at GitHub.

Once you download the application, you can see that it has the following structure:

[lead_alerts]
[tests]
.dockerignore
.env.example
.gitignore
.mergify.yml
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
LICENSE
Makefile
README.md
docker-compose.yml
manage.py
requirements.txt

The lead_alerts folder holds the files we are going to modify. Here is its structure:

[services]
[static]
[templates]
__init__.py
config.py
views.py

First, we need to modify the views.py file. All the routes used to send requests and responses for our application are here.

Modifying Files

The views.py file contains two routes:

We are going to edit the notifications route. Let’s see what, where, and how should be modified.

I. notifications Route

We modify the notifications route like this:

  1. The notifications route uses the TwilioService() class to send a text message. We do not need it, so we can remove this line.

  2. The next code portion to change is the way that the message is sent. We completely remove the Twilio message sending methods and add the CarrierX Core API Send Message method.

Twilio Python Code
@app.route('/notifications', methods=['POST'])
def create():
    house_title = request.form["house_title"]
    name = request.form["name"]
    phone = request.form["phone"]
    message = request.form["message"]

    twilio_service = TwilioService()

    formatted_message = build_message(house_title, name, phone, message)
    try:
        twilio_service.send_message(formatted_message)
        flash('Thanks! An agent will be contacting you shortly', 'success')
    except TwilioRestException as e:
        print(e)
        flash('Oops! There was an error. Please try again.', 'danger')

    return redirect('/')

Corresponding CarrierX Python Syntax
@app.route('/notifications', methods=['POST'])
def create():
    house_title = request.form["house_title"]
    name = request.form["name"]
    phone = request.form["phone"]
    message = request.form["message"]

    formatted_message = build_message(house_title, name, phone, message)
    auth_token = app.config['CARRIERX_TOKEN']
    agent_phone_number = app.config['AGENT_PHONE_NUMBER']
    carrierx_phone_number = app.config['CARRIERX_PHONE_NUMBER']
    url = "https://api.carrierx.com/core/v2/sms/messages"
    headers = {'Authorization': f'Bearer {auth_token}', 'Content-Type':'application/json'}
    payload = {"from_did": carrierx_phone_number, "to_did": agent_phone_number, "message": formatted_message}
    request_details = requests.post(url, data=json.dumps(payload), headers=headers)

    flash('Thanks! An agent will be contacting you shortly', 'success')

    return redirect('/')

For the POST request correct work, we need to import the requests and json Python modules. We add this to the beginning of the views.py file:

import requests, json

II. Configuration Files

As you could notice, we used the AGENT_PHONE_NUMBER variable in our migrated code. It is stored in the .env file in the application route. Change this phone number to the number where you want to send your notification to:

AGENT_PHONE_NUMBER=15162065516

There are two more variables in our code: CARRIERX_TOKEN and CARRIERX_PHONE_NUMBER. These values can be taken in your portal account profile. Refer to the Security Token and Rent Phone Number Quick Starts for more information on where to get the token and the phone number.

Add these variables with their values to the .env file:

CARRIERX_TOKEN=5ebc03d6-8b2b-44ad-bf65-72d4f1491dda
CARRIERX_PHONE_NUMBER=15162065515

After that, add the following lines to the config.py file in the lead_alerts folder so that they become accessible for the application:

CARRIERX_TOKEN = os.environ.get('CARRIERX_TOKEN', None)
CARRIERX_PHONE_NUMBER = os.environ.get('CARRIERX_PHONE_NUMBER', None)

Finishing Migration

Now that we modified the routes, we can safely remove the Twilio libraries import declaration from the beginning of the views.py file:

from twilio.base.exceptions import TwilioRestException
from .services.twilio_service import TwilioService
from lead_alerts import app
from flask import flash, redirect, render_template, request
import requests, json

@app.route('/')
def index():
    house = {
                'title': '555 Sunnybrook Lane',
                'price': '$349,999',
                'description':
                    'You and your family will love this charming home. ' +
                    'Featuring granite appliances, stainless steel windows, and ' +
                    'high efficiency dual mud rooms, this joint is loaded to the max. ' +
                    'Motivated sellers have priced for a quick sale, act now!'
            }
    return render_template('index.html', house=house)

@app.route('/notifications', methods=['POST'])
def create():
    house_title = request.form["house_title"]
    name = request.form["name"]
    phone = request.form["phone"]
    message = request.form["message"]

    formatted_message = build_message(house_title, name, phone, message)
    auth_token = app.config['CARRIERX_TOKEN']
    agent_phone_number = app.config['AGENT_PHONE_NUMBER']
    carrierx_phone_number = app.config['CARRIERX_PHONE_NUMBER']
    url = "https://api.carrierx.com/core/v2/sms/messages"
    headers = {'Authorization': f'Bearer {auth_token}', 'Content-Type':'application/json'}
    payload = {"from_did": carrierx_phone_number, "to_did": agent_phone_number, "message": formatted_message}
    request_details = requests.post(url, data=json.dumps(payload), headers=headers)

    flash('Thanks! An agent will be contacting you shortly', 'success')

    return redirect('/')

def build_message(house_title, name, phone, message):
    template = 'New lead received for {}. Call {} at {}. Message: {}'
    return template.format(house_title, name, phone, message)

You can also remove the importing of Twilio modules from the requirements.txt file.

Follow the instructions from the application GitHub page to run the application. Then open the application home page in your browser and send a request to test it.

Further Reading

You have successfully migrated the Lead Alerts application from Twilio to CarrierX!

Refer to the following page to learn more about CarrierX API:

Use our Migrating from Twilio to CarrierX Quick Start to learn more about other difficulties you can meet while migrating from Twilio to CarrierX and the ways to solve these issues.

Read other instructions on real-case migrations from Twilio to CarrierX here:

Refer to our other quick start guides for instructions on how to work with CarrierX: