Bulk Messaging with NodeJS on Glitch

In this guide we’ll build a small example application for sending the same message to multiple recipients at once. This has many practical applications, from bulk messaging your customers to inviting a group of friends over for a party. Our application will be very minimal, just a form with two text areas. The first one will be used to enter the list of numbers, one number per line, and the second one will be used to enter the message. Once the user submits the form we’ll convert this input into the format required for the MessageMedia API and send the messages.

The backend part of this application will be written in Javascript for the Node environment using the Express framework. The messagemedia-messages-sdk library will be included for easily making an API request to the MessageMedia API. For the purpose of following this guide you can use a nifty free service called Glitch which provides a Node environment and a code editor directly in your browser so you don’t have to set anything up.

Get started with Glitch

Go get started, go to Glitch, click on the Sign in button and authenticate with either your GitHub or Facebook account. Once signed in, choose New Project. Glitch creates a basic Node project for you with a random funny name such as accidental-tomato. You can rename it to anything you like, provided the desired name is still available. Names must be globally unique because this name followed by .glitch.me will be the URL through which you and everybody else can access your application in the browser.

Message Form

Let’s start with the static HTML part. Glitch has already created the file views/index.html for you. Remove all code from this file and replace it with the following:

<!doctype html>
<html>
    <head>
        <title>Send bulk message</title>
    </head>
    <body>
        <h1>Send bulk message</h1>
        <form action="/sendMessages" method="post">
            <label>Recipients (one number per line):</label>
            <div><textarea name="numbers" cols="50" rows="5"></textarea></div>
            <label>Message content:</label>
            <div><textarea name="message" cols="50" rows="5"></textarea></div>
            <button type="submit">Send</button>
        </form>
    </body>
</html>

As you can see, we have a basic HTML form which makes an HTTP POST request to the path /sendMessages, text areas called numbers and message, and a submit button.

Setting up Dependencies

As part of its project template, Glitch creates the package.json file that every Node project uses to describe itself and declare its dependencies. When you open this file and look at the dependencies section you’ll notice that the Express framework is already there. We need to add two more libraries here; one is the request library mentioned in the introduction which we’ll use for API access, and the other is body-parser, which will greatly simplify reading the form in the backend.

Now go ahead and specify the dependencies like this, keeping the other segments of the file as they are:

{
    "dependencies": {
        "express": "^4.15.3",
        "messagemedia-messages-sdk": "^1.0.0",
        "body-parser" : "^1.17.2"
    }
}

In your local environment you’d have to run npm install on the command line now, but on Glitch you can skip this step as their service watches your files in the background and installs the dependencies automatically.

Adding Credentials to the Environment

Glitch creates a .env file. This is a special file because its contents always remain private even if you let others “remix” your source code on Glitch. Therefore your MessageMedia API credentials should go here. We’ll use HTTP Basic authentication for accessing the API, therefore please create two variables in the .env file like this:

API_KEY=YourRESTAPIKeyHere
API_SECRET=YourRESTAPISecretHere

Implementing the Backend

Your backend code needs to go into the server.js file that Glitch has created. Remove all content from this file and start creating it step by step as outlined below.

First we’ll use require() to load all dependencies:

var express = require('express');
var bodyParser = require('body-parser');

Next, we create the app object and tell Express to use body-parser:

var app = express();
app.use(bodyParser.urlencoded({ extended : true }));

We also need to create one route in Express to serve our static views/index.html file using sendFile():

app.get("/", function (req, res) {
  res.sendFile(__dirname + '/views/index.html');
});

Next, we include the MessageMedia NodeJS SDK and define a variable for our MessagesController. This allows us to send messages later:


const sdk = require('messagemedia-messages-sdk');
const controller = sdk.MessagesController;

Now that we have the MessageMedia API defined, we need to authenticate using our REST API Credentials. If you do not have credentials already, you can obtain them from here. By using process.env for these variables, we can read the authentication information from the .env file as mentioned above.

// Configuration parameters and credentials
sdk.Configuration.basicAuthUserName = process.env.API_KEY; // Your API Key
sdk.Configuration.basicAuthPassword = process.env.API_SECRET; // Your Secret Key

 

Now we’re slowly getting to the most interesting part, the /sendMessages route in which the form is processed and the API request is made. First we’ll read the input and split the list of numbers into lines using the split() function with a regular expression:

app.post("/sendMessages", function (req, res) {
  var numbers = req.body.numbers.split(/[\r\n]+/g);
  var message = req.body.message;

The API takes a messages array and each entry in this array can have a variety of attributes describing the message. At bare minimum we need a value for the keys content and destination_number. In our example, the message is the same for all recipients, thus we iterate through the numbers and create a new message object for each of them, with a different destination_number value but the same content. Here’s how to do that:

  var messages = [];
  for (var n in numbers) {
    messages.push({
      content : message,
      destination_number : numbers[n]
    });
  }

At last it’s time for the API call: We use the ‘createSendMessages’ function on the controller we defined earlier with a body that contains our messages array inside ‘messages’. This will use the authentication we set earlier to generate and send a request to the MessageMedia API. We then set a callback function that gets called once the API call returns. Here we send a message to the user if the sending was successful.

controller.createSendMessages({ messages : messages }, function(error, response, context) {
   if (error == null){
     res.send("OK");
   } else {
     res.send("Error from API: " + error.errorResponse);
   }
 });

Almost done! As the last step, the server needs to be started:

app.listen(process.env.PORT);

In a local environment you’d have to call node server.js now but, once again, Glitch does this automatically in the background. Go to https://your-project-name.glitch.me (or simply click the Show button in Glitch) and try it out! Remember that numbers have to be entered one by line and in international format.

Final remarks

You’ve learned how to create a basic Node application that calls the MessageMedia API to send text messages to more than one recipient. Go ahead and play a bit with this application! You could also try to export it from Glitch and run it with Node on your local computer.