© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
R. StringerReal-Time Twilio and Flybasehttps://doi.org/10.1007/978-1-4842-7074-5_6

6. Sending Daily SMS Reminders

Roger Stringer1  
(1)
Penticton, BC, Canada
 

In this chapter, I’ll show you how you can use Node.js, Flybase, and Twilio to write your very own daily SMS reminder app.

Necessary Tools

  • Twilio to send and receive SMS messages

  • Flybase to store the users who have subscribed to our service

  • Node.js to build on Chrome’s JavaScript runtime for easily building fast, scalable network applications

Scheduling SMS Messages with Cron

To get started, we’ll need to install a couple npm packages. We’ll be using the twilio package (https://github.com/twilio/twilio-node) to send text messages, and we’ll be using the cron package (https://github.com/ncb000gt/node-cron) to schedule the time we want to send the text messages. You can install them by running the following commands:
npm install twilio
npm install cron
Create a new file called app.js and require the twilio and cron packages:
var twilio = require('twilio'),
client = twilio('ACCOUNTSID', 'AUTHTOKEN'),
cronJob = require('cron').CronJob;
Let’s write some code that sends a text message at 6 PM every day:
var textJob = new cronJob( '0 18 * * *', function(){
  client.sendMessage( { to:'YOURPHONENUMBER', from:'YOURTWILIONUMBER', body:'Hello! Hope you're having a good day!' }, function( err, data ) {});
}, null, true);

You’re probably wondering what the string we’re passing as the first argument to our cronJob is. That is a format specific to Cron that lets us define the time and frequency of when we want this job to fire.

In this case, at 0 minutes 18 hours every day. This article (www.nncron.ru/help/EN/working/cron-format.htm) does a nice job of breaking down the Cron format.

In the callback to our cronJob, we use the Twilio Client library to send a message. We pass the to and from numbers and the body of the message we want to send.

Run this code and wait in anticipation for your text message. If it’s 10 AM, you probably don’t want to have to wait 8 hours to see if your code works. Just update the Cron format to send at an earlier time. Here’s a hint. To send at 10:13 AM, you’d use this format: “13 10 * * *”.

You now have a basic version of this app, but you most likely don’t want to just send a message to yourself every day. If you do, then congrats! You’re all done! For the rest of us, we can make a couple small code changes to have this send to multiple phone numbers.

First, let’s add a new variable called numbers that contains the phone numbers we want to send messages to:
var numbers = ['YOURPHONENUMBER', 'YOURFRIENDSPHONENUMBER'];
Then let’s update the code in our textJob to loop over these phone numbers and send a message to them:
for( var i = 0; i < numbers.length; i++ ) {
  client.sendMessage( { to:numbers[i], from:'YOURTWILIONUMBER', body:'Hello! Hope you’re having a good day.'}, function( err, data ) {
    console.log( data.body );
  });
}

Receiving SMS Messages

Now that we’re sending an SMS message to different numbers at our desired time, let’s update this code to know when a user sends a text message to our app. Twilio uses webhooks (https://en.wikipedia.org/wiki/Webhook) to let your server know when an incoming message or phone call comes into our app. We need to set up an endpoint that we can tell Twilio to use for the messaging webhook.

We’ll be using the Express framework (http://expressjs.com/) to set up our node web server to receive the POST request from Twilio, so we’ll need to install the express package. We’ll also be using the body-parser module, so we’re going to install that as well:
npm install express
npm install body-parser
At the beginning of our app.js file, we’ll need to require express and initialize it into a variable called app. We’re also going to use the bodyParser middleware (https://github.com/expressjs/body-parser) to make it easy to use the data we’ll get in our POST request:
var express = require('express'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
We’re going to add a route for /message that responds with some TwiML (www.twilio.com/docs/api/twiml). TwiML is a basic set of instructions you can use to tell Twilio what to do when you receive an incoming call or SMS message. Our code will look like this:
app.post('/message', function (req, res) {
  var resp = new twilio.TwimlResponse();
  resp.message('Thanks for subscribing!');
  res.writeHead(200, {
    'Content-Type':'text/xml'
  });
  res.end(resp.toString());
});

We use the Twilio node library to initialize a new TwimlResponse. We then use the Message verb (www.twilio.com/docs/api/twiml/sms/message) to set what we want to respond to the message with. In this case, we’ll just say “Thanks for subscribing!” Then we’ll set the content-type of our response to text/xml and send the string representation of the TwimlResponse we built.

Finally, let’s set our server to listen on port 3000:
var server = app.listen(3000, function() {
  console.log('Listening on port %d', server.address().port);
});
Now let’s fire up our app:
node app.js
Now that we have our server running, we need to tell Twilio to use this messaging URL as our Message Request URL:
![](https://lh6.googleusercontent.com/EDpe7a4_f17kekwXJmzaPj53kvW913UZHr-lEvlKP588mR5jHzIzUd7g48GSzkSzz5INNI9sh3Mygtmstiz4YmCuFznnTSlWpZV0bEFXjjnlU8mZzHR_SL-7nyEHWTmolw)

Send an SMS message to your Twilio number, and you should get a response back. If you don’t, take a look at the Twilio App Monitor (www.twilio.com/user/account/developer-tools/app-monitor) to help determine what went wrong.

Saving Users in Flybase

We’ve set up a script that sends out a text message at the same time every day, and we’ve given users the ability to send a text message into our app. There’s just one last thing left to do. We need to save our users’ information when they send a text to our app. We’ll be using Flybase (www.flybase.io/) as our datastore, so we need to install the Flybase node module:
npm install flybase
Now that we’ve installed the Flybase module, let’s require and initialize it at the top of our app.js file:
var api_key = "{YOUR-API-KEY}";
var db = "dailysms";
var collection = "users";
var usersRef = require('flybase').init(db, collection, api_key);

When you sign for a Flybase account, they provide an API Key for your account. Make sure you update this code to replace {YOUR-API-KEY} with this key.

From inside Flybase, create a new app called dailysms.

Since we’ll be pulling the phone numbers from Flybase, we’ll want to update our numbers variable to be an empty array and then fill it with info from the database.

Flybase is a real-time database and built around the premise of subscribing to events as opposed to reading on demand. We’re going to subscribe to two events: first, we want to retrieve a list of all existing phone numbers, and then we want to get notified whenever a new user is added:
var numbers = [];
usersRef.on('value', function(snapshot) {
      snapshot.forEach( function( rec ){
           numbers.push( rec.value().phonenumber );
           console.log( 'Added number ' + rec.value().phonenumber );
      });
});
usersRef.on('added', function(snapshot) {
     numbers.push( snapshot.value().phonenumber );
     console.log( 'Added number ' + snapshot.value().phonenumber );
});
Now we need to add users to our database when they text in subscribe. Let’s revisit our message route to make this update:
```javascript
app.post('/message', function (req, res) {
     var resp = new twilio.TwimlResponse();
     if( req.body.Body.trim().toLowerCase() === 'subscribe' ) {
          var fromNum = req.body.From;
          if(numbers.indexOf(fromNum) !== -1) {
               resp.message('You already subscribed!');
          } else {
               resp.message('Thank you, you are now subscribed. Reply "STOP" to stop receiving updates.');
               usersRef.push({phonenumber:fromNum});
          }
     } else {
          resp.message('Welcome to Daily Updates. Text "Subscribe" receive updates.');
     }
     res.writeHead(200, {
          'Content-Type':'text/xml'
     });
     res.end(resp.toString());
});

When the Twilio message webhook triggers a new POST request to your server, we include request parameters (www.twilio.com/docs/api/twiml/sms/twilio_request#request-parameters) with information about the message.

We’ll be using the Body parameter to examine the content the user texted in and the From parameter to determine the number they texted from. If they’ve texted in the word “subscribe” and they’re not already in our database, we’ll use the push function on our Flybase reference to add them.

Our app is now ready to go. Let’s run it and give it a try:
node app.js

Summary

We did it! Now that you’ve built a simple daily SMS reminder app, it’s your chance to customize the daily message to whatever you want.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.253.93