This content originally appeared on Bits and Pieces - Medium and was authored by Thomas Sentre
Does your business rely on appointments? Whether you’re a beauty salon, restaurant, personal trainer, or handyman, no-shows can impact revenue significantly. Text reminders can reduce no-shows by up to 50%, but if you’re just starting your business or trying to keep costs down, you may think this is impossible to implement without a CRM ( Customer Relationship Management ) or other expensive systems.
Good news! It’s actually easy to create an automated text reminder system from scratch. Let’s make one using Node.js, Twilio, and Flybase.
The topics covered in this post include the following:
- Using Cron package to schedule SMS messages.
- Setting up a free account on Twilio and Flybase.
- Generating an API key in the Twilio and Flybase web portal.
- Saving users in Flybase database.
- And much more.
Setup
We’ll be using a few tools to build this app. You’ll want to have these set up before you continue on:
- Twilio: To send and receive SMS messages. Don’t have a Twilio account? Sign up for free
- Flybase: A real-time database API. We’ll be using it to store the users who have subscribed to our services
- Node.js: A platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications.
If you haven’t already, sign up for a free Flybase account now and then create a new app.
When you sign up for Twilio and Flybase accounts, they provide an API Key for your accounts. We will use these API Key to build our app.
How to Schedule SMS Messages with Cron
To get started, create a new folder called auto-sender and initialize our app by running the following command
npm init --yes
Next, we’ll need to install a couple of npm packages.
We’ll be using the twilio package to send text messages, the cron package to schedule the time we want to send the text messages and dotenv package that loads environment variables from a .env file into process.env.
Let’s install these packages by running the following commands:
npm install twilio
npm install cron
npm install dotenv –save-dev
Now, create a new file called app.js and import the Twilio and Cron packages:
import twilio from ‘twilio’;
import cronJob from ‘cron’.CronJob;
import dotenv from 'dotenv';
dotenv.config();
const client= twilio(process.env.ACCOUNTSID,process.env.AUTHTOKEN);
Let’s write some code that sends a text message at 6 PM every day:
const textJob=new cronJob(‘0 18 * * *’, function(){ client.messages.create ({
to: process.env.YOURPHONENUMBER,
from: process.env.YOURTWILIOPHONENUMBER,
body: ‘ Hello, Hope you are having a good day’
}) .then(message => console.log(message.body));
}, 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 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 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 of small code changes to have this sent 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',’YOURBOYFRIENDPHONENUMBER’];
Then let’s update the code in our textJob to loop over these phone numbers and send a message to them:
const textJob = new cron.CronJob(
"0 18 * * *",
function () {
for (var i = 0; i < numbers.length; i++) {
client.messages.create({
body: `Hello! Hope you’re having a good day.`,
from: process.env.YOURPHONENUMBER,
to: numbers[i]
})
.then(message => console.log(message.body));
}
},
null,
true
);
How to Receive 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 to let our 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 to set up our node web server to receive the POST request from Twilio, so we’ll need to install the express package. So we’re going to install that as well:
npm install express
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 express middleware to make it easy to use the data we’ll get in our POST request:
import express from 'express';
app = express();
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
We’re going to add a route for /message that responds with some 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:
const MessagingResponse= twilio.twiml.MessagingResponse;
app.post('/message', function (req, res) {
const twiml = new MessagingResponse();
twiml.message('Thanks for subscribing!');
res.writeHead(200, {
'Content-Type':'text/xml'
});
res.end(twiml.toString());
});
We use the Twilio node library to initialize a new TwimlResponse. We then use the Message verb 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:
const 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 to help determine what went wrong.
That is it! Our daily SMS reminder app is ready. At 6 PM every day the following SMS will be sent to all phone numbers added to our app:
How to Save 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 as our data store, 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:
Import flybase from ‘flybase’
const flybase_api_key = process.env.FLYBASEAPIKEY;
const db = "dailysms";
const collection = "users";
const usersRef = flybase.init(db, collection, flybase_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 alist of all existing phone numbers, and then we want to get notified whenever a new user is added:
const 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:
const MessagingResponse= twilio.twiml.MessagingResponse;
app.post('/message', function (req, res) {
const twiml = new MessagingResponse();
console.log(req.body)
if( req.body.Body.trim().toLowerCase() === 'subscribe' ) {
var fromNum = req.body.From;
if(numbers.indexOf(fromNum) !== -1) {
twiml.message('You already subscribed!');
} else {
twiml.message('Thank you, you are now subscribed. Reply "STOP" to stop receiving updates.');
usersRef.push({phonenumber:fromNum});
}
} else {
twiml.message('Welcome to Daily Updates. Text "Subscribe" receive updates.');
}
res.writeHead(200, {
'Content-Type':'text/xml'
});
res.end(twiml.toString());
});
When the Twilio message webhook triggers a new POST request to your server, we include 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
Conclusion
In this post, we have created a simple but functional daily SMS reminder App using Node.js, Flybase, and Twilio. You can find the complete source code for this application in this repository. I hope you have found this useful for getting up and running. Now you can decide to add more features as you see fit.
Build composable web applications
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favourite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components.
Learn more
- Building a Composable UI Component Library
- How We Build Micro Frontends
- How we Build a Component Design System
- How to build a composable blog
- The Composable Enterprise: A Guide
- Meet Component-Driven Content: Applicable, Composable
Build an SMS Reminder App using Nodejs, Twilio, and Flybase was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Thomas Sentre
Thomas Sentre | Sciencx (2022-05-29T15:35:29+00:00) Build an SMS Reminder App using Nodejs, Twilio, and Flybase. Retrieved from https://www.scien.cx/2022/05/29/build-an-sms-reminder-app-using-nodejs-twilio-and-flybase/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.