Campion
Campion
Feb 2, 2018 · 4 min read
Google Cloud Platform

Just a little bit of experience needed!

Learn how to build a Cat Fact text service using GCP and Twilio.

If you haven’t used GCP before, you may want to follow my previous tutorial Hosting your website on Google Cloud Platform for beginners


Before We Begin

Set Up Twilio

First, go ahead and sign up for a Free Trial on Twilio. You can get free credits from GCP if you sign up here: http://ahoy.twilio.com/googlecloudplatform

Fill out your info and verify your account with SMS. You should see this next, where you can name your project:

On the next page hit Get Started and then Get a number

Finally click Choose this Number and Done.

Set Up GCP

Finally, you’ll also want to make sure you have a GCP project setup with billing enabled.

Getting Started

Now that we’ve set everything up, let’s start coding. Open up the Cloud Shell Editor and clone the sample repository from Github:

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/appengine/twilio

Now, go back to Twilio so we can configure the URL endpoint for your app. On your Twilio dashboard click Manage Numbers

And then click on the number in red to edit its configuration.

Scroll down to the Messaging section and replace the Webhook URL highlighted below with https://<your-app-id>.appspot.com/sms/receive

And hit Save at the bottom of the page.

Now, go back to the main Twilio dashboard, and note the Project Info:

We need to put these settings in the app.yaml file as shown below:

env_variables:
TWILIO_ACCOUNT_SID: <your-account-sid>
TWILIO_AUTH_TOKEN: <your-auth-token>
TWILIO_NUMBER: <your-twilio-number>

PS: You can open up files quickly by typing edit app.js

and finally, we’ll need to install a couple of libraries to help us:

npm install --save twilio requests express body-parser

Fetching 🐈 Facts

We’ll start by writing the code that gets a cat fact and sends it to the user. We’ll be using the Node.JS Request library, so open up the app.js file and put this line near the top (I did it in line 24):

const request = require('request');

Now look for the /sms/send endpoint, which starts like:

// [START send_sms]
app.get('/sms/send', (req, res, next) => {

We’ll change the main logic at this endpoint to get our cat facts. Look for this part:

twilio.sendMessage({
to: to,
from: TWILIO_NUMBER,
body: 'Hello from Google App Engine'
}, (err) => {
if (err) {
next(err);
return;
}
res.status(200).send('Message sent.');
});

and replace it with:

var theFact = '';
request.get('https://catfact.ninja/fact?max_length=160',
function(error, response, body) {
var info = JSON.parse(body);
console.log(info.fact);
theFact = info.fact;
twilio.sendMessage({
to: to,
from: TWILIO_NUMBER,
body: theFact
}, (err) => {
if (err) {
console.log(err);
next(err);
return;
}
res.status(200).send('Message sent.');
});
});

What this does here is get a Cat Fact from catfact.ninja and uses that as the body of the text message it sends the user.

Receiving User Messages

Now, scroll down to the sms/receive endpoint. We’ll change this so the user can ask for a fact.

Find the part that has:

const resp = new TwimlResponse();
resp.message(format('Hello, %s, you said: %s', sender, body)); res.status(200)
.contentType('text/xml')
.send(resp.toString());

and replace it with:

if (body === 'FACT') {
request.get("https://<your-app-id>.appspot.com/sms/send?to=" + sender);
res.status(200).contentType('text/xml').send("Fact sent.");
} else {
const resp = new TwimlResponse();
resp.message(format('Sorry, I didn\'t get that, please say FACT to get a cat fact.'));
res.status(200).contentType('text/xml').send(resp.toString());
}

TIP: Don’t forget to replace <your-app-id> with your App ID.

This makes it so your app will send a fact back if it receives the word ‘FACT’.

Deploy and We’re Done!

Finally, deploy your app with gcloud app deploy and text “FACT” to your Twilio number.

In The Future

If you want to make your Cat Fact bot available to the public, go back to Twilio and upgrade your account.

If you have any questions, comment below!

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Campion

Written by

Campion

Student at the University of Washington

Google Cloud Platform - Community

A collection of technical articles published or curated by Google Cloud Platform Developer Advocates. The views expressed are those of the authors and don't necessarily reflect those of Google.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade