Facebook Messenger Chatbot to Make Your Life Easier. Built in Node-Red With Ngrok.

by b00t3r in Circuits > Software

813 Views, 1 Favorites, 0 Comments

Facebook Messenger Chatbot to Make Your Life Easier. Built in Node-Red With Ngrok.

message.png

Today I'm going to teach you on how to make a Facebook Messenger bot that lives on a local server, without writing a line of code.. Well, you will copy/paste some, but that's all!

Have a look at step 9 for ideas on why you should build one!

And BTW, I use quotations marks like a lot.. So if you see them around a text you should input somewher, remove them, ok?

Supplies

  • Connection to the interwebz
  • A Facebook account
  • An ngrok account (It's free and great!)

Some kind of computer that can host Node-Red.

Install Node-Red

nodered.png

There is literally a ton of guides online on how to install Node-Red, just Google what type of device you want't to install it on and follow the guide.

Me personally run it on a Raspberry Pi, since I need it to always be on.

To open your Node-Red dashboard simply open a browser and:

Visit localhost:1880 if you installed it on the computer you are sitting at right now.

  • Visit the IP-adress to the computer where you installed Node-Red, e.g. 192.168.1.8007:1880.

When Node-Red is installed, make sure to protect it!


Create an Ngrok Account

ng.png
auth.PNG

First off, what is ngrok and why should I use it?

Well, it's a service that, in our case, allows Facebook API to "talk" to the Node-Red Messenger bot without you having to expose your private network to the rest of the world.

Of course, if you know how, you could skip the ngrok part and and let Facebook API "talk" to Node-Red some other way.

When you have created your ngrok account, click on "Your Authtokens" and save the token somewhere, we are going to use it in the next step.

Connect Ngrok to Node-Red

ngrok.PNG

Open a browser and type in the address to your Node-Red installation.

Click the hamburger menu, the three horizontal lines, in the top right and press "Manage Palette".

Now click on the tab "Install" and search for ngrok, you should see "node-red-contrib-ngrok". If that's the case, press on "Install" and then "Install" again to confirm.

After a short while ngrok will be installed and placed in the node list to the right, find it, drag it out to the workspace and double click on it.

Press the pencil to the right of authtoken to get to the screen where you paste in the authtoken you generated in the previous step.

Save it, change the Region to where you are and press "Done".

I would recommend to drag a debug node from the node list and place it to the right of the ngrok node, drag a line between them, press on the "Deploy" button in the top right, and then press on the ngrok button to start ngrok.

Under the "Deploy" button there is a small tab that looks like a bug, it will show you the output from the debug node you just placed on your workspace, here you will see the URL that ngrok generated, copy it and save it somewhere.

Create a Facebook Page

fb.jpeg

First off, why Facebook?

For me it was convenience. Me and my wife both have Facebook and Facebook Messenger, unfortunately, is great at pushing notifications with little to now delay. And the bot I'm building will give us both important information that needs to get trough always. Like if the bus or train is delayed, updated from pre school, weather information and so on.

So let's create a Facebook page!

Follow the step-by-step instructions and give Facebook as much or little information you want. When the page is ready, go to "Settings" and the "General" to make sure that the page is unpublished.

Even if your bot is intended to be used by the public I would recommend to have it unpublished util everything is set up properly.

Become A Facebook Developer 

It might sound like a big step, but it's really not.

Just visit Facebook Developer and register your Facebook account as a developer.

Click on "My apps" and then "Create App". Chose an app type, I choose "None", and click "Next".

Now, give the app a name, something cool, like "AwesomeBot 1.0", type in your contact email and press "Create App".

Facebook will ask for your password, just give it to them..

Generate an Access Token

at.PNG

You are now on the "Add a product" page, scroll down until you see the "Messenger" window and click on "Set up".

On the next page scroll down a little until you see "Add or remove pages", click on that and choose the page you crated in step 4.

Make sure that "Manage and access Page conversations in Messenger" are turned to "HELL YEAH" and press on "DONE" followed by "OK".

Your page should now be in the list under "Access Tokens", click on "Generate Token", check the "I Understand" box, after you have read the text of course, and then copy the access token and save it somewhere.

Make Node-Red "Listen"

fb-node-debug.PNG
deploy.PNG

Now, go back to your Node-Red dashboard and drag a "http in" node to your workspace, dubble click it and make sure that method is GET and type in something like "/awesome" after URL, click "Done" to save.

Next drag a "function" node to your workspace and double click it. Delete everything inside and paste in this code:

var mode = "";

var vtoken = "";

var challenge = "";

if (msg.payload["hub.mode"])
{
mode = msg.payload["hub.mode"];
}

if (msg.payload["hub.verify_token"])
{
vtoken = msg.payload["hub.verify_token"];
}

if (msg.payload["hub.challenge"])
{
challenge = msg.payload["hub.challenge"];
}

if ('subscribe' == mode &&
"SUPER_SECRET_PASSWORD!" == vtoken) {
msg.payload = challenge;
}

return msg;

As you can see on the 5th row from the bottom there is a SUPER_SECRET_PASSWORD! - Change it to whatever floats your boat and write it down somewhere.

Drag a "debug" node from the list and connect it to the "http in" node, it will come in handy on step 8.

Lastly, drag a "http response" from the list to your workspace, double click it and type "200" after "Status code" and press "Done" and then press "Deploy" on the top right.

Add a Callback URL

callback.PNG

Go back to your Facebook Developer screen and scroll down a imsy whimsy bit and click on "Add Callback URL", if you left the page for some reason, you can find it again under "Messenger", "Settings", this will send the SUPER_SECRET_PASSWORD! to your Node-Red to make sure that you are who you say you are, basically.

So, in the Callback URL field paste in the URL that was created by ngrok in step 3 followed by the URL you put in the "http in" node in the previous step, it could look like this 

https://super-secret-ngrok-url.eu.ngrok.io/awesome

And in the "Verify Token" type in the SUPER_SECRET_PASSWORD! from earlier, press on "Verify and save" and if everything went fine the popup you where typing in just disappears, highly anticlimactic, but it is what it is..

Send a Message to and From the Bot

IMG_3392.PNG
debug.PNG

Now, go back to your Facebook Page and edit the "Call to action" button so you can press it to send a message to the bot. After you done that try out the button to send a message as your self to the bot.

Go back into Node-Red and have a look at the debug screen on the right, you should see a new message, looking like:

{ object: "page", ..

Click the "copy value" and paste it some where, you are looking for the line:

"sender":{"id":"13378007"}

That's you! Copy the value somewhere.


Now, if you have a look at Facebooks Messaging documentation you will find examples on how to send plain text messages, messages with pictures, buttons and even phone numbers.

But for now, let's make the bot say that you are awesome!

So, go back to Node-Red, drag an "inject", "function" and "http-request" node to your workspace and connect them, "inject" > "function" > "http-request".

Double click the "function node", delete everything in it and paste this code:

msg.headers = {};
msg.headers["content-type"] = "application/json"

msg.payload = {
 "recipient":{
  "id":"YOUR-SUPER-SECRET-ID"
 },
 "message":{
  "attachment":{
   "type":"template",
   "payload":{
    "template_type":"button",
    "text":"Hey, you are truly awesome!",
    "buttons":[
      {
      "type": "web_url",
      "url":"https://giphy.com/explore/youre-awesome",
      "title": "Click to confirm!",
     }
    ]
   }
  }
 }
}

return msg

Change the SUPER-SECRET-ID to your ID from above and press on "Done".

Now double click on the "http request" node and type in 

https://graph.facebook.com/v2.6/me/messages?access_token=

 + the "Access Tokens" you created on step 6, so it looks like this, kinda..

https://graph.facebook.com/v2.6/me/messages?access_token=woohoo-im-a-frickin-access-token

Press "Done" followed by "Deploy" in the top right corner.

And now.. the fun part!

Press on the inject button and you will get a Facebook message from your bot, isn't that just fantastic? 

Ok, Now What?

I choose Node-Red because it's really easy to "program" in, and can be really powerful

Here is some ideas of things you can have your bot to do:

  • Send weather forecast if a temperature wind speed gets to high or low.
  • See if the next train or bus is on time.
  • Tell your bot to turn on or off the lights
  • Notify you when your favourite Youtuber posts a new video.
  • If your IR sensor detects motion on the drive way.
  • If there is any new listings on the marketplace you like.
  • Whats todays special is at that restaurant.
  • Play your favourite song on Spotify.
  • Collect RSS feeds.
  • If your investment in Crypto is going to the moon.
  • Control the heating.
  • And so on and so forth..

If you get stuck on a step, or are in need of more pictures, just write a comment and I'll get back to you ASAP!