How-tos

Building a Bot for Facebook Messenger using IBM Bluemix

Share this post:

Weather Chat Bot This example shows how a basic weather bot can be built for Facebook Messenger using the IBM Bluemix cloud platform. Although this example is very simple, it shows all the steps needed to build a real-life cognitive messaging bot.

If you want more background on this example and some practical tips, please see my prior post Messaging Bots are the next big wave in Mobile.

Introduction to the sample weather bot

The sample extends Facebook Messenger so the user can ask weather-related questions in natural language format. The bot responds by determining if the user asked about the weather condition or the temperature. Assuming the bot recognizes the desired location, it answers the user appropriately.

The solution is composed of the following modules:

Main Modules for Bots

  • The Broker is responsible for the connectivity with the Messaging Platform. In this example, it is connected only with Facebook Messenger, but you may extend it to connect with other Messaging Platforms.
  • The Weather App is called by the dispatcher in order to interpret the text and generate a reply. Again, weather is just an example. Your solution may include multiple apps, each one specialized in a specific domain (banking, dining, shopping, etc.)
  • The Weather App utilizes a few standard services that are available in the Bluemix catalog.

Below are some reasons Bluemix is well suited for this solution:

  • Quality of Interaction – Thanks to IBM Watson, the app offers superb natural language and dialog capabilities. Since these services are available through IBM Bluemix cloud platform, you can make these capabilities part of your bot.
  • Messaging Platform Independence – Building your bot decoupled from a specific Messaging Platform simplifies making it available on other Messaging Platforms and connecting it with multiple chat accounts. Avoid ‘walled gardens’ as this domain is very dynamic!
  • Backend Connectivity & Services – It’s easy to imagine allowing your user to successfully complete an action by connecting your bot with other cloud services or with your legacy IT. IBM Bluemix cloud platform facilitates the necessary capabilities and in a flexible and scalable way.

Setup Instructions

To build this solution, follow the steps below.

Prerequisites

  • A Bluemix account
  • A Facebook account for your Bot

Configure Facebook Page and Application

  • From your Facebook homepage, select ‘Create a New Page’ from the menu.
  • Select ‘Cause or Community’, fill-out a name and click ‘Get Started’. You make skip the following stages of the wizard.
  • From your Facebook for Developers homepage, select My Apps / Create a New App and click ‘basic setup’
  • Fill-in the necessary information and click ‘Create App ID’

Create the Broker App in Bluemix

  • From your Bluemix dashboard, under ‘Cloud Foundry App’ click ‘Create App’
  • Select ‘Web’ and then select ‘SDK for Node.JS’,
  • Click ‘Continue’ and enter a name for your app.
  • Click ‘Download Starter Code’ and choose a download location.
  • Open the app.js file and replace the default sample code with the Broker sample code available at this Gist on GitHub.
  • Open the package.json file, and under dependencies apply the following changes:
    “body-parser”: “^1.15,0”,
    “express”: “^4.13.4”,
    “request”: “2.72.0”
    </li>
    	<li>To push the Broker App to Bluemix, use the following CF CLI command: <code>‘cf push using manifest file path/manifest.yml</code>, replacing <code>path</code> with the path to your file.</li>
    </ul>
    <h3>Connect your Facebook App Application to your Broker App</h3>
    <ul>
    	<li>In your Facebook Developer homepage, under ‘Webhooks’, click New Subscription / Page</li>
    	<li>Under ‘Callback URL’, fill out the Broker App URL; you can find it in Bluemix just under the name of the app’
    <img src="/blogs/bluemix/wp-content/uploads/2016/05/Broker_app_URL.png" alt="Broker app URL" /></li>
    	<li>Under ‘Verify Token’ fill out the token you’ve defined in the Broker App (in our example, we’ve used ‘mySecretAccessToken’. You may of course have your own).</li>
    	<li>Under ‘Subscription Fields’, select messages, message_deliveries, messaging_options and messaging_postbacks.</li>
    	<li>To get the Facebook access token, Click ‘Messenger’ and then ‘Get Started’. Select the page you’ve created earlier, click ‘okay’ and copy the Page Access Token than has been generated.</li>
    	<li>To subscribe your app to the page, use the Terminal to run the following command: <code>curl -ik -X POST “Facebook_access_token_goes_here”</code></li>
    	<li>Open again the <code>app.js</code> file and use Facebook token to the <code>token</code> var defined at the last section of the code.</li>
    	<li>Push the Broker App to Bluemix as described previously.</li>
    </ul>
    <h3>Create the Weather App in Bluemix</h3>
    <ul>
    	<li>Create a Bluemix app with AlchemyAPI, Insights for Weather, and Natural Language Classifier services bound to it.</li>
    	<li>We've trained a basic Watson Natural Language Classifier that identifies whether a question is about weather conditions or temperature. <a href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/nl-classifier/get_start.shtml">Getting started with the Natural Language Classifier service</a> explains how to train your own classifier.</li>
    	<li>After you train your own classifier, you should obtain a classifier id.</li>
    	<li>Similar to the previous section for the Broker app, download the starter code for your Node.js app.</li>
    	<li>Open the <code>app.js</code> file and replace the default sample code with the Weather sample code available at <a href="https://gist.github.com/eyal-he/a97e0bc70687dd0c579fab63b5727e91">this Gist</a> on GitHub.</li>
    	<li>Replace with the classifier id you obtained.</li>
    	<li>Open the <code>package.json</code> file, and under <code>dependencies</code>, apply the following edits:
    "JSON": "^1.0.0",
    "body-parser": "^1.15.0",
    "cfenv": "^1.0.3",
    "express": "^4.13.4",
    "node-geocoder": "^3.9.1",
    "request": "^2.71.0",
    "watson-developer-cloud": "^1.4.1"
    
  • Push the Weather App to Bluemix as described previously.

Connect the Broker App with the Weather App

  • Open the app.js file of the Broker app
  • Locate the following code:
    request("https://whatistheweather.mybluemix.net/getWeather?text=" + text, function (error, response, body)
  • Change the address to the URL of your Weather app
  • Push the app to Bluemix.

Did it work? If you encounter problems with the instructions above or have questions, please let me know in the comments below.

Add Comment
27 Comments

Leave a Reply

Your email address will not be published.Required fields are marked *


Dmitry

Looks great!
What messaging platforms are supported except FB Bots?

Reply

    Eyal Herman

    FB is just an example. You can connect with any chat platform that has the necessary API. WeChat, Telegram, Kik, Line and Kakao are good examples.

    Reply

    Eyal Herman

    That was the ‘tokenName’ string on line 11 of the Gist. I’ve now updated the Gist to ‘mySecretAccessToken’ so now it fits the instructions. Thanks for raising our attention to this mismatch!

    Reply

Wanderley

Hi, maybe I’ve missed some part but how to define the token for the Broker App? (The one we need to fill in the ‘Verify Token’ of the Facebook’s webhook configuration)
Thanks in advance

Reply

Adam

Please could you explain in more detail how to register the Facebook app to the broker app? Should the curl command include a URL? From which terminal should this be run? What exactly is the access token, is this the Facebook App’s “App Token”? Thanks.

Reply

    EyalHerman

    Please use the Curl command in the following way:
    curl -X POST “https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=
    Don’t forget to place your access token (the one you obtained in the previous step).
    We’ve been using the terminal on a Mac, I guess Windows have something similar (sorry, i’m not that familiar with Win…).

    Reply

Harjeet Singh

Hey i tried to follow the instructions but for broker facebook do not accept the callback address. It says invalid domain and they ask for secure address. Is there any way i can solve this problem?

Reply

    EyalHerman

    I think the broker has to be on https but I’m not sure that’s the case for you.

    Reply

      Dibin

      Bluemix doesn’t provide you a domain with https.. It provides only http.
      How to change that? Or whats the alternative?

      Reply

      Dibin

      You can change it by following this tutorial:
      http://www.tonyerwin.com/2014/09/redirecting-http-to-https-with-nodejs.html

      Now it work with https too..

      But there is a new error for CallBack URL
      The URL couldn’t be validated. Response does not match challenge, expected value = ‘111883464’, received=’ <h…

      Any idea how to solve it?

      Reply

        Paul McL

        Hi Eyal & Dibin,
        This tutorial is helpful at 5’50”
        https://youtu.be/y4XPudpy-vo?t=5m40s
        The solution there (and they’re using PHP) is for the server to return the hub.challenge part of FB’s message (nb: they do in PHP as hub_challenge).
        The hub.challenge text is a random string sent from FB’s server, part of the API.
        Hope that helps.
        I found the material above most useful, so thanks to everyone for your input.

        Reply

EyalHerman

Not sure, maybe the token you provided in this line:
req.query[‘hub.verify_token’] === ‘mySecretAccessToken’
does not match the one you put in Facebook? That’s the only idea I have…

Reply

    Patricio Julian

    Mmmm, I just re-direct HTTP to HTTPS by express, but it is still not working. Did you use your own server? I can´t find out the problem with this. I followed everything step by step.

    Reply

PatricioJulian

Eyal, I just have the same problem as Harjeet Singh, callback url does not working. Double checked, the token is the right one.

Reply

Chris

Any updates on the https issue using Facebook?

Reply

    PatricioJulian

    Nope, couldnt solve it yet.

    Reply

      Chris

      Thanks PatricioJulian, in the same boat it seems stuck on that step 🙁

      Reply

Abderrazak Landoulsi

Hi guys, I made the same project using java liberty profile. It works fine with admin’s page. My app can send a response msg only if the sender is the admin. How can i change it to be able to response all facebook users?

Reply

    Abderrazak Landoulsi

    I know why :)) I can’t !!
    When the app is in development mode, it can only be used by app admins, developers and testers.

    Reply

viky

Hi Eyal Herman, Is this possible to use ibm bluemix services without broker ?

Reply

RodrigoMendoza

I had same problem with facebook requesting secure https address. Make sure to set callback URL to: “https://yourappname.mybluemix.net/webhook”

Reply

Varun

Hi Eyal, thanks for the instructions.

Everything works fine up until I try to push the weather app to Bluemix. It uploads fine, has all the services connected, but can’t seem to start for some reason. Any idea how to resolve this?

Reply

Parth

Hello
Can you help me resolve the https error? I am not really able to solve it. Thanks.

Reply

Marc Kruger

When I try and create the link between the message broker and the facebook app I get the following error; “The URL couldn’t be validated. Callback verification failed with the following errors: HTTP Status Code = 404; HTTP Message = Not Found”

I have already deployed the message broker app successfully. When I follow the URL of my broker app it gives the simple text of ‘Cannot GET /’
I dont know if that is an issue or if Chrome simply cannot render the broker app

Reply

sd120

ERR url : vcap.natural_language_classifier[0].credentials.url,
2017-04-06T02:48:48.64-0500 [APP/0] ERR ^
2017-04-06T02:48:48.64-0500 [APP/0] ERR TypeError: Cannot read property ‘0’ of undefined

I got this error when i try to push weather app.Help me plz.

Reply

Chris

I have made the chatbot on Bluemix already using IBM Watson. Now I want to test it out on my facebook page using messenger. Could you let me know on how to do this?

Reply

RYAN W TYLER

are we supposed to add the markup to the package.json? seems like the format of that part of the instructions is messed up.


To push the Broker App to Bluemix, use the following CF CLI command: …”

Reply
More Mobile Stories

Home automation powered by Cloud Functions, Raspberry Pi, Twilio and Watson

Over the past few years, we’ve seen a significant rise in popularity for intelligent personal assistants, such as Apple’s Siri, Amazon Alexa, and Google Assistant. Though they initially appeared to be little more than a novelty, they’ve evolved to become rather useful as a convenient interface to interact with service APIs and IoT connected devices.

Continue reading

Interpreting Spring Social Twitter Data with Watson Tone Analyzer

In this post, I'll show you how to build a basic Spring app with Twitter login using Spring Social. Then we'll use Watson Tone Analyzer to determine the dominant emotion from each of the tweets on the time of the logged-in user. The project we will create will be similar to the Accessing Twitter Data Spring guide, but with a few modifications.

Continue reading

Arria brings Natural Language Generation to IBM Cloud

The Arria Natural Language Generation APIs service is an addition to the Finance category on the IBM Cloud platform. This blog post shows you how to get started with Arria’s Natural Language Generation APIs service on the IBM Cloud platform.

Continue reading