Building Communications Applications Using Avaya OneCloud CPaaS

“No one learns as much about a subject as one who is forced to teach it.”

Peter Drucker

This morning, I will be presenting an IAUG webinar on developing Avaya CPaaS applications. Rather than present an hour of PowerPoint slides, I will live-walk viewers through the steps to build an outbound SMS text campaign application that can be run on your Windows PC or Mac (no server required).  Essentially, the steps I go through when I sit down and write code

Actually, I plan on presenting three different ways using two different languages — node.js and Python.  I will also address how to invoke Avaya CPaaS APIs via REST and the language-specific helper libraries.

This blog article provides the source code for those three applications.  

Notes: 

In these examples, I use the CPaaS api-us.cpaas platform.  If you use another platform (api.zang.io or api-eu.cpaas), adjust CPAAS_URL accordingly.

For simplicity’s sake, I do little to no error checking in any of the applications.

This is the format of the Excel spreadsheet I use as a campaign “database” — Name, Number, Message.

Using the above Excel file, a received message will look similar to this:

Got it? Let’s take a look at the three applications.


smsCampaign.js:  This node.js application directly invokes the CPaaS REST Send SMS API to send SMS text messages.

/*

This program reads in a list of names, text numbers, and messages from an Excel file.  It then loops through the list to:
 - Send campaign message to text number.
 - After sending text, pause for one second.  This avoids hitting CPaaS SMS rate limit

*/

const xlsx = require('node-xlsx'); // https://www.npmjs.com/package/node-xlsx
const request = require('request-promise');

// Set the following to match your environment
const EXCEL_FILE = "Excel File";
const CPAAS_USER = "CPAAS Account SID";
const CPAAS_TOKEN = "CPaaS Auth Token";
const CPAAS_FROM = "CPaaS Telephone Number in E.164 Format";
const CPAAS_URL = "https://api-us.cpaas.avayacloud.com/v2/Accounts/";

const CPAAS_SEND_SMS = "/SMS/Messages.json";

// Parse the Excel file
const workSheetsFromFile = xlsx.parse(EXCEL_FILE);

/*

Excel file must be in form of: 

Name | 10-digit Number | Message
Name | 10-digit Number | Message
Name | 10-digit Number | Message
.
.
.

xlsx.parse will create a JSON object that looks like this:

[ { name: 'Sheet1', data: [ [name, number, message], [name, number, message], [name, number, message] ] } ]

*/

sendTextMessages(workSheetsFromFile[0].data);

async function sendTextMessages(data) {
	const auth = "Basic " + Buffer.from(`${CPAAS_USER }:${CPAAS_TOKEN}`, "utf-8").toString("base64");
	for (let i in data) {
		toName = data[i][0];
		toNumber = `+1${data[i][1].toString()}`; // +1 for E.164 format
		campaignMessage = data[i][2];
		message = `Hello, ${toName}. ${campaignMessage}`;
		options = {
			url: `${CPAAS_URL}${CPAAS_USER}${CPAAS_SEND_SMS}`,
			body: `From=${CPAAS_FROM}&To=${toNumber}&Body=${message}`,
			headers: {
				'Content-Type': 'text/plain',
				'Accept': 'application/json',
				'Authorization': auth
			},
			method: 'POST'
		}
		var response = await request.post(options, function(e, r, body) {});
		// To avoid hitting CPaaS rate limit, pause for one second (the default minimum for SMS transmission) between new messages
		await new Promise(resolve => setTimeout(resolve, 1000));
	}
}

librarySMSCampaign.js:  This node.js application uses the CPaaS node.js helper library to send SMS text messages

/*

This program reads in a list of names, text numbers, and messages from an Excel file.  It then loops through the list to:
 - Send campaign message to text number.
 - After sending text, pause for one second.  This avoids hitting CPaaS SMS rate limit

*/

const xlsx = require('node-xlsx'); // https://www.npmjs.com/package/node-xlsx
var cpaas = require('@avaya/cpaas');  // npm install @avaya/cpaas

// Set the following to match your environment
const EXCEL_FILE = "Excel File";
const CPAAS_USER = "CPAAS Account SID";
const CPAAS_TOKEN = "CPaaS Auth Token";
const CPAAS_FROM = "CPaaS Telephone Number in E.164 Format";
const CPAAS_URL = "https://api-us.cpaas.avayacloud.com/v2";

// Parse the Excel file
const workSheetsFromFile = xlsx.parse(EXCEL_FILE);

/*

Excel file must be in form of: 

Name | 10-digit Number | Message
Name | 10-digit Number | Message
Name | 10-digit Number | Message
.
.
.

xlsx.parse will create a JSON object that looks like this:

[ { name: 'Sheet1', data: [ [name, number, message], [name, number, message], [name, number, message] ] } ]

*/

var connector = new cpaas.SmsConnector({
    accountSid: CPAAS_USER,
    authToken: CPAAS_TOKEN,
	baseUrl: CPAAS_URL
});

sendTextMessages(workSheetsFromFile[0].data);

async function sendTextMessages(data) {
	for (let i in data) {			
		toName = data[i][0];
		toNumber = "+1" + data[i][1].toString(); // +1 for E.164 format
		campaignMessage = data[i][2];
		message = `Hello, ${toName}. ${campaignMessage}`;
		//send SMS message
		connector.sendSmsMessage({
			to: toNumber,
			from: CPAAS_FROM,
			body: message
		}).then(function (data) {

		}); 	
		// To avoid hitting CPaaS rate limit, pause for one second (the default minimum for SMS transmission) between new messages
		await new Promise(resolve => setTimeout(resolve, 1000));			
	}
}

smsCampaign.py:  This Python application uses the CPaaS Python helper library to send SMS text messages

from zang import ZangException, Configuration, ConnectorFactory
import openpyxl # https://openpyxl.readthedocs.io/en/stable/
import time

# Set the following to match your environment
CPAAS_USER = 'CPAAS Account SID'
CPAAS_TOKEN = 'CPaaS Auth Token'
CPAAS_FROM = 'CPaaS Telephone Number in E.164 Format'
EXCEL_FILE = 'Excel File'
CPAAS_URL = 'https://api-us.cpaas.avayacloud.com/v2'

configuration = Configuration(CPAAS_USER, CPAAS_TOKEN, url = CPAAS_URL)
smsMessagesConnector = ConnectorFactory(configuration).smsMessagesConnector

# Load spreadsheet and obtain active sheet
wb = openpyxl.load_workbook(EXCEL_FILE)
sheet_obj = wb.active
 
# Obtain the number of rows in the spreadsheet
m_row = sheet_obj.max_row

# Loop through the spreadsheet
for i in range(1, m_row + 1):
    # Retrieve cells for row i
    name_cell = sheet_obj.cell(row = i, column = 1)
    phone_cell = sheet_obj.cell(row = i, column = 2)
    message_cell = sheet_obj.cell(row = i, column = 3)
    
    # Retrieve the values of each cell
    name = name_cell.value
    number = "+1" + str(phone_cell.value) # +1 for E.164 format
    message = 'Hello, ' + name + '. ' +  message_cell.value

    # Send sms message
    try:
        smsMessage = smsMessagesConnector.sendSmsMessage(
            to = number,
            body = message,
            from_ = CPAAS_FROM)
    except ZangException as ze:
        print(ze)
        
    # To avoid hitting CPaaS rate limit, pause for one second (the default minimum for SMS transmission) between new messages 
    time.sleep(1)

Mischief Managed

I hope that my webinar and these sample applications are enough to get you started in the fabulous world of Avaya CPaaS programming. Sending SMS messages is only the beginning. There are so many other things you can do with CPaaS APIs and inboundXML (a webinar and a blog for another day).

Feel free to reach out to me with any questions you might have. I am here to help.

Happy programming!

Advertisement

2 comments

  1. Ramesh Babar · · Reply

    this is a fantastic way to engage others in learning

    1. Thanks, Ramesh! Engaging and teaching are my intentions.!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: