Contents

  1. Introduction
  2. Theory and tools
  3. Send a test message with Postman
  4. Send a message with code
  5. Connect a Workplace integration to our code
  6. Receive a message from Workplace
  7. Getting your bot online

Getting your bot online

In the last part of our bot-building tutorial, we learned how to start a real conversation with your bot: receiving data from Workplace and sending a reply back to the user.

Today, we’re at the final step – bringing your bot onto the web and letting it do its thing.

Ready? Let’s start:

 

1. Making your bot cloud-ready

So far, we’ve only been working with an application that lives on our local machine. That’s great for development and testing – but it’s not so hot for production.

Why? Because the moment you finish working on it and switch off your laptop, your bot stops working.

We need to get our application up into the cloud if we want it to work without us. So first, let’s see a quick recap of what our code should look like at this point:

const express = require('express')
const bodyParser = require('body-parser')
let app = express()
let port = 3000
const axios = require('axios');
app.use(bodyParser.json());

const workplaceAPI = axios.create({
    method: 'POST',
    baseURL: 'https://graph.facebook.com/me/messages',
    headers: {
        Authorization: 'Bearer <Your Integration Token>
    }
});

const sendMessage = (id, message) => {
    workplaceAPI({
        data: {
            recipient: {
                id: id
            },
            message: {
                text: message
            }
        }
    })
}

app.get('/webhook', (req, res) => {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === 'ThisIsARandomStringThatIJustMadeUpOnTheSpot') {
        console.log('Validated webhook');
        res.status(200).send(req.query['hub.challenge']);
    } else {
        console.error('Failed validation. Make sure the validation tokens match.');
        res.sendStatus(403);
    }
});

app.post('/webhook', (req, res) => {
    let uuid = req.body.entry[0].messaging[0].sender.id
    let message = req.body.entry[0].messaging[0].message.text
    console.log('Received a message from', uuid, 'now replying')
    sendMessage(uuid, message)
    res.sendStatus(200)
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

We’ll need to make two small changes to our application before it can run in the cloud. So let’s make those changes:

Open up package.json, and look at the ‘scripts’ section:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
},

We need to define a new script called ‘start’. This script will tell the host to use NodeJS to load our index.js.

Here’s the code you’ll need:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "node index.js"
},

That’s the first change we needed to make. Now we can move on to the second change:

In your index.js file, find the ‘port=3000’ line – and replace it with this:

let port = (process.env.PORT || 3000)

Most hosts will dynamically assign a port internally – and then map it to port 80 externally.

The line above that we just wrote says this:

‘If a dynamic port has been assigned, use it. Otherwise, use port 3000’.

So with those two changes made, save your work and check your code into source control:

Checkin the final code changes into GIT

Fantastic! With that out of the way, we’re ready to move on to our cloud host.

 

2. Setting up a cloud host

For this tutorial, we’re going to use a service called Heroku to host our application in the cloud.

Heroku is an extra layer on top of Amazon’s AWS platform. AWS is an incredible system, and it powers huge chunks of the internet. But it is complicated – and that’s where Heroku can help us by simplifying many of the set-up steps.

(A quick note: Heroku is more expensive than AWS. So if you’re planning to productionise your work, you should try to learn AWS itself. But for development work, Heroku’s free tier is perfect.)

Let’s get Heroku set up:

Switch over to the terminal in VS Code. If you click on the plus symbol, you can create a new Bash or Powershell instance. (Or you can hit ctrl-C to end the Ngrok session – since we’re finished with that now.)

Once you’re in the terminal, type the following:

Heroku create
heroku ps:scale web=1

Heroku commands in the terminal

Remember when I said that Heroku would simplify things?

Don’t let the modest output above fool you: Heroku has done loads of things behind the scenes.

Without bombarding you with too much information, Heroku has just:

  • Created an AWS instance
  • Created a new URL, and then mapped it to the AWS instance
  • Created a GIT repository
  • Added a reference to the Heroku GIT repository to local GIT setup
  • Setup SSL
  • Deployed a default, placeholder application
  • And created a process that will deploy our application to AWS whenever code is uploaded to the Heroku GIT repository.

And if you’re anything like me, you’ll be relieved that you didn’t have to do all of that yourself.

Now all you have to do is type the following:

Heroku open

And your browser will load up your new, publicly available application:

Heroku default application

Now that we have Heroku up and running, we just need to make a few adjustments.

When we used the ‘Heroku create’ command earlier, it made some assumptions. It hosted the application in the USA, and it gave us a default application name and URL. (You can read more about the Heroku Command Line Tool here.)

We need to replace the placeholder application with our own. We want to trigger an application deployment to AWS, and we’ll do that by uploading our code to the Heroku GIT repository. So let’s do that now.

In the terminal, type the following:

git push heroku master

(Alternatively, you can use VS Code’s visual method):

Checking into GIT using the VS Code UI

Now if you refresh your browser, after a few seconds you should see an error:

An error in the browser

That’s because we’ve previously only defined a route for ‘/webhook’. Let’s add that to the end of our URL and try again:

Forbidden error in browser

If you remember, that’s the same ‘forbidden’ message we were getting when we tested locally, and through Ngrok.

Don’t worry: it’s a good sign. It’s because we haven’t given our application the verification token that Workplace sends over.

So to fix this, we now need to repoint our Workplace integration away from our Ngrok URL and over to our Heroku URL.

 

3. Pointing Workplace to Heroku

Head back into Workplace, and navigate to the Integrations section of the Admin Panel.

Click on your ‘Coolr-Bot-Tutorial’ integration, and then scroll down to the webhook section and change it so that it points to Heroku. (You’ll need to add your verification token again.)

Once you’ve got your integration pointing at the Heroku URL, save your changes – and pray that you get sent back to the Admin Panel without an error.

Changing the settings of the integration in the admin panel

So now we’ve got Workplace pointing at our cloud-hosted application.

There’s only one thing left to do. Let’s test it!

 

Awesome! Your bot is now live on the cloud and connected to Workplace – which means it should keep running even when you switch off your local machine.

 

So what’s next?

Sadly, this is the end of our bot-building tutorial series.

But you should be proud of yourself – you’ve come a long way!

How far, you ask? Through this series, you’ve managed to:

  • Build an application that can receive messages and reply to users in Workplace
  • Connect Workplace and your app together through a webhook subscription and the Graph API
  • And create your own cloud application and connect Workplace to it.

You’ve learned all sorts of bot theory (and plenty of new terms) – and you’ve started to get to grips with a whole host of developer tools and shortcuts that can help you on your bot-building journey.

But while you should be proud – and I hate to tell you this – you shouldn’t get ahead of yourself.

This is just the beginning. You’ve got a lot of learning and practice ahead of you, and what we’ve covered in this seven-part series is just the bare minimum to get you started.

We haven’t really touched on security, we’ve taken a lot of shortcuts, and we haven’t even begun to think about performance or sustainability. What you have here is not suitable for production! And I plan to follow up with another series of tutorials which cover those extra security requirements.

But luckily, there’s plenty of help out there for you. Now that you have an understanding of the nuances of building a bot for Workplace, there should be loads of other bot tutorials which will now work for you – so don’t stop now!

If you want to play it safe (and I strongly recommend it), you can get a separate instance of Workplace to do your experimentation and learning without affecting any of your colleagues. It’s only $3 a month for a new Workplace instance – and with the huge potential you’ll have with your bots as you learn, that’s a small price to pay. If that’s not an option, another little tip is to create a group which only contains yourself (and any willing guinea pigs) and then scope the integration to that group.

Scoping the integration to a single group

And while we’re talking about security, make sure you whitelist your cloud host’s IPs (here’s a handy link for Heroku).

There’s an argument that I should have put these security pointers at the start of the tutorial, but please remember that this is an absolute beginner’s’ guide. If we’d turned on lots of security features at the start, the chances are that things wouldn’t have worked and you’d have never made it to the end of the tutorial. You’re now a fledgling bot developer and part of that means understanding the security risks associated with your application, so get out there and do some reading.

Building your own bots is rewarding. And it’s always going to be the option that gives you the most freedom and flexibility.

But on the other hand, it’s possible that this beginner’s guide has seriously tested your limits – and your patience.

If that’s the case, you might want to look into some off-the-shelf bots that can do exactly what you need. If you need an easy, point-and-click interface, you can check out some of the options from our friends over at The Bot Platform and Prepp.

(And if you do, don’t forget to speak to me first so I can introduce you!)

These platforms are incredible for anyone who doesn’t want to dig into the nitty gritty of coding themselves – but you may find there are limits in how you can use them, or in how they integrate with your other systems. And of course, you’ll end up paying more when compared to building a bot yourself.

But if you’re looking for a third way – a way to get the specific, tailor-made bots you need without sacrificing on flexibility or integration – you can always come and speak to us at Coolr.

We’re experts when it comes to building bespoke bots. We can create a tailor-made, customised, secure bot that’s built specifically for your business – and connect it to any of your internal systems as you need it.

So if you want the perfect balance between power and flexibility – and you don’t want to melt your brain in a coding environment – send me a direct message on Workplace or drop me an email (if you’re feeling a bit old school).

And no matter what you do, good luck with your journey – and never stop learning!

Enjoyed this case study? Share!

Coolr thinking

Check out our latest news, blogs, cases studies and rants below.

more

Coolr story

We're doing things a little different at Coolr. We're part agency, part tech start-up, part consultancy - and we have big plans.

Learn more