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

Sending a message with NodeJS

In the last part of our bot-building tutorial, we sent ourselves a test message by setting up Postman and creating an integration inside Workplace.

Through that test message, we showed that we can send a message through the Graph API – and we proved that our integration is properly configured.

So today, we’re going to see if we can write some code to send that same message.

And for that, we’ll need to use Virtual Studio Code (remember that from our shopping list of tools?)

 

1. Setting up your environment

Once VS Code has started up, you’ll first need to open a terminal (this is a place where we can write one of commands).

Click on ‘View‘ in the top menu of VS Code, and then click on ‘Terminal‘. This opens up a new panel at the bottom of the main window in VS Code.

Opening the terminal

If things don’t look quite the same as this screenshot, don’t worry. It all depends on your operating system.

I’m running VS Code on an Apple computer (macOS) – so I get a BASH terminal running in my home directory. If you’re on Windows, you’ll probably get a Powershell terminal in your user directory.

So whichever type of terminal you see, that’s where we’ll type our commands.

First, we’re going to make a directory (mkdir) and change to that directory (cd). And we’ll do that by typing the following commands into the terminal:

mkdir coolr-bot-tutorial

cd coolr-bot-tutorial

Next, click the ‘Files‘ button on the main menu of VS Code, and click on ‘Open Folder‘. Find the ‘coolr-bot-tutorial‘ directory that we just created, and select it.

Open Folder

At this point, VS Code will reload, giving you a blank screen.

But if you look closely, you’ll see that the files panel is now based at our ‘COOLR-BOT-TUTORIAL’ folder.

Open Folder

The next thing we need to do is create a repository using GIT.

GIT? Repository? What’s that?

When you start writing code, you’ll make lots of changes – and it’s all too easy to lose track of where you are.

If you’re working with a team of developers, things get even worse. If one of your colleagues breaks your code, you need a way to go back to a time when it was working.

GIT is a source control tool that helps to avoid these problems. Each application will have its own repository (called ‘repo’ for short) – and this repository keeps track of all the changes and works out who updated what.

We’ll also want to create a package.json file using NPM.

Package.json? NPM? What’s that?

A package (or ‘module’, which means the same thing) is a way to parcel up useful pieces of code so you can use them again later.

For example: you might have a piece of code that calculates how many days are left until Christmas. Rather than type out that code every time, you can turn it into a package and call on it whenever you need it.

(You can even publish useful packages for other people to use – and use the packages that other people have published. There are currently almost a million public packages that you can use for free to save time and effort.)

NPM is short for Node Package Manager. It tracks key information about your application – such as which file NodeJS should load, and which extra packages your application needs to run properly. It does this using the package.json file.

So how do we do these two things?

Open up the terminal again (view – terminal), and type in the following commands:

git init

npm init -y

The first command instructs GIT to create a local repository for our application.

The second command tells NPM to create a package.json file – which NPM will use to track important information about our app and our environment.

If you click on package.json, you’ll see that it opens the file in the editor panel on the right-hand side of VS Code.

Package.json

For now, the only thing we need to look at is the “main”: “index.js” section.

This tells NodeJS to look for and load a file called index.js when it launches. So before it’s able to do that, we’ll need to create that file.

On the file panel, click the ‘New File‘ button, and then name the file ‘index.js‘. The new file will automatically be opened in the right hand editor window.

New File

Great! Let’s write some code!

In the right-hand editor window, add the following to your index.js file:

console.log('Hello World')

And now we can tell VS Code to launch our application. You can either press F5 on your keyboard, or click the debug button and then click the play icon.

Debug

At this point, VS Code might run your application straight away. But if you have multiple tools installed that could run .js files, you may need to tell VS Code which one to use.

If this happens to you, a quick way around it is to create a VS Code configuration.

Click the ‘Debug‘ button again. But this time, instead of clicking the play icon, click on the cog icon to the right-hand side of it.

Depending on what you have installed, you should be asked to select an application to launch your index.js file. If you do get a selection, choose ‘Node.JS‘.

A config file will load which you can immediately save. Now VS Code will know to always load your JS file with NodeJS.

Debug

With that extra step out of the way, you can now launch your application (either with F5 or with the play icon) – and you should see your ‘Hello World’ message appear in the Debug Console at the bottom of the screen.

Debug

Fantastic! We now have a working environment and a working application. It’s time to move on to the next step: recreating the Postman message from our last tutorial inside our application.

 

2. Recreating your message

For this step, we’re going to use a module (package) called Axios to send our message to the Graph API.

There are alternatives to Axios (Facebook’s example applications use a module called ‘request’) – but personally, I like Axios. It’s well-maintained, and it supports certain features that make JavaScript’s asynchronous behaviour easier to understand. On top of that, it works in both NodeJS and the browser.

So first, let’s install Axios:

In VS Code, click on the ‘terminal‘ tab, and then type the following command:

npm i axios

(In case you’re wondering, the ‘i’ is short for ‘install’.)

Once that’s finished installing, click on the ‘Files‘ button, and then click on ‘package.json‘.

At this point, a lot has happened. And you’ll be pleased to know that loads of complicated stuff has all been done for you:

Within package.json, you’ll see a new section called ‘dependencies’. And within that you’ll see “axios”: “^0.18.0”. (If you see different numbers, don’t worry.)

This tells NPM to always install the latest version of Axios in the v0.*.* branch. If you’re interested, you can read more about how NPM manages different versions here. But for this tutorial, we won’t need to worry about that.

Package.json

If you look at the command lines in the terminal, you’ll see that it says it’s installed 5 packages.

And if you look over at the files panel on the left, you’ll see a new folder called ‘node_modules‘. This is where NPM has stored Axios for us. If you expand that folder by clicking on the little arrow to the left of it, you’ll see Axios and four other packages.

This is because Axios has its own package.json – and that file has its own dependencies listed within it.

NPM has handled everything for us. It’s downloaded Axios, downloaded its dependencies, and then checked whether those dependencies have any dependencies of their own. And it’ll keep doing this until all of the required dependencies have been downloaded.

This is incredibly powerful stuff – and it’s all been taken care of for us in the background.

We’re going to take a bit of a jump with our code here. With the next bit of code, we’re going to:

  • Load the Axios module and store it in a variable
  • Create an instance of Axios and set some default values
  • And send the rest of the JSON we created in Postman in the last tutorial.

So open up your index.js, delete the ‘hello world’ code that we just created and paste in the following, changing <Your Integration Token> and <your UUID> to the values we used while working with Postman in the last blog post:

const axios = require('axios');

const workplaceAPI = axios.create({

    method: 'POST',

    baseURL: 'https://graph.facebook.com/me/messages',

    headers: {

        Authorization: 'Bearer <Your Integration Token>'

    }

});

workplaceAPI({

    data: {

        recipient: {

            id: '<Your UUID>'

        },

        message: {

            text: 'hello, world! From NodeJS'

        }

    }
})

The first line of code loads the Axios module and stores it in a variable called ‘axios’.

The next section creates an instance of Axios and sets some default values. We call this instance ‘workplaceAPI‘.

Since all we’re doing is sending messages, we know that the method will always be POST. We know that the URL will always be https://graph.facebook.com/me/messages – and we know that our access token will always be the same. (If you sent the message with a different token it would appear as a different bot to the user.)

So now we can now send the rest of the JSON we created in Postman in the previous step. It makes our code a lot cleaner.

Run the above code again with F5 or the play icon, and you should get a message from your bot in Workplace:

Message inside the bot

 

3. Tweaking your code

We’re going to make a few changes to our code (to make it easier to use later in the tutorial).

We’ll put the workplaceAPI instance inside a function called sendMessage(). That means we’ll be able to call it with just one line in the future.

const axios = require('axios');

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

            }

        }

    })

}

sendMessage('<Your UUID>', 'hello, world! From NodeJS refactored')

Refactored message in the bot

We’re making really great progress!

Our application is doing what we want it to, and there are no ugly errors in our code.

Now would be a good time to stop and check our code into GIT.

 

4. Checking your code into source control

At this point, we’re going to check our code into GIT.

(Remember: GIT is a source control tool that helps us keep track of our changes and updates – and it’s especially useful when other people will be working on your applications.)

We could do this from the command line. But since this is a guide for absolute beginners, we’re going to do it through VS Code itself.

First, click the ‘Source Control’ button:

Source Control

 

At the top of the panel you’ll see a number (mine says 69). This shows you the number of files which will get checked into GIT.

You’re probably wondering why that number is so high. We’ve only created a few files – right?

We’ve created package.json, package-lock.json (we haven’t discussed this but it was created when we installed Axios) and index.js.

So why are there so many files being checked in?

The answer is our node_modules folder. Remember that when we installed Axios, it automatically downloaded 4 other modules that it depended on.

But since those files are already declared in package.json, any new developer joining our team will be able to grab all of the modules just by referencing package.json – which means we don’t need to check these files into GIT.

So let’s tell GIT to ignore the node_modules directory.

Switch back to the ‘Files‘ panel and create a new file called .gitignore (make sure you include that full stop at the start!).

Inside that new file, you’ll need to add the following:

node_modules

.vscode

Once you’ve saved that, you should see that the number of files being checked into GIT has dropped down to just four:

  • .gitignore
  • js
  • json
  • And package-lock.json.

So let’s check those files in by switching back to the ‘Source Control‘ panel.

You’ll first you need to enter a commit message into the box at the top of that panel. This is what you’ll see when you’re looking through your GIT history – so make sure it’s short, but still descriptive. Once you’ve done that, you can click the tick above the message box:

Commit Message

And that’s it!

At this point in the tutorial, we’ve:

  • Set up our environment and created an application
  • Used a third-party module to send a message through a bot in Workplace
  • Tweaked our code to make it cleaner
  • And checked our code into source control.

You can now officially call yourself a bot developer!

 

A quick note about security

In this tutorial, I’ve placed the integration token in plain text in the JavaScript file. I’ve done this just to make things more clear for the tutorial.

In a production system, this would be a terrible idea.

Remember that your token is effectively a username and password – and that would mean that anyone with access to your GIT repository would also have access to your password.

So if you’re going to try anything more advanced than what we’ve covered here today, I’d strongly encourage you to look into something called ‘environment variables‘.

Every operating system and cloud host will support them – and they give you a great way to hide your tokens (and anything else that’s sensitive). By using environment variables, you can lock your sensitive data away in a place where only your admins can see them.

And if you want to emulate this in your development environment, you can check out a module called dotEnv.

 

So what’s next?

You can officially call yourself a bot developer. And that’s a massive achievement.

But there’s still more work to do. You’ve learned how to code an application that can send a message – but we haven’t yet looked at how we’re going to receive messages from our users.

Next time, we’ll be taking a deeper look at how our application can receive data – by using webhooks and GET requests.

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