Giter VIP home page Giter VIP logo

botalize's Introduction

Create and setup your Facebook Messenger Bot with API.AI, Node.js and Mongo.db

The purpose of this repo is to provide instructions for how to setup a Facebook Messenger Chatbot using API.AI, Node.js and Mongo.db. If you have any question or suggestions, feel free to create an issue.

Overview

In this tutorial the API.AI is used as your NLP (Natural Language Processor) and Node.js for backend operations that can't be done with API.AI. If you don't have any backend operation, just ignore the Node.js/Mongo.db sections.

The following picture shows an architectural overview of how the full example will operate. The API.AI interacts directly with the Facebook Messenger Platform, while the Node.js server will only interact directly to the Messenger Platform if notification messages are required.

alt text

Setup the Facebook App

  1. Create your Facebook App at https://developers.facebook.com/apps

    alt text

  2. Go to the Messenger tab and select your Facebook Page to generate an Page Access Token. Make sure to save it somewhere, as it will be used in your Node.js sever.

    alt text

  3. After you have an Page Access Token, you have to configure your API.AI webhook to explore the messenger platform. Head over to API.AI and follow the steps at Section Setup API.AI for how to setup the Facebook messenger One-click integration.

  4. Setup the webhook with the Callback URL and Verify Token from the Facebook messenger One-click integration at your API.AI agent. Make sure to check the Subscription Fields required for your bot interaction (check messages and messaging_postbacks at least).

    alt text

  5. Select a page to subscribe your webhook to the page events

    alt text

Setup API.AI

  1. Create an account at API.AI, and create your first Agent. For more info about API.AI, check their documentation.

    alt text

  2. Go to Integrations tab and setup the Facebook messenger One-click integration. The Verify Token can be any string, and the Page Access Token is the token generated at your Facebook App.

    alt text

  3. Go to Fulfillment tab and setup the Webhook with your Heroku app url endpoint. After this setup, your can now enable the Webhook option at your intentions.

    alt text

Setup Node.js server

If you don't want to follow this whole section, you can download this repo and update the environment variables and Heroku informations.

  1. First things first. We will use Heroku platform for deployment. As so, you will need a Heroku account and Heroku toolbelt installed locally. You will also need MongoDB to run the server locally.

  2. Install Node. If you already have it installed, update npm to the latest version.

    sudo npm install npm -g
    
  3. Create your project folder and init a Node project.

    npm init
    
  4. Install the extra dependencies. Express for the server, Request for easy html requests, Body-Parser for message processing, and Mongoose for data storage.

    npm install express request body-parser mongoose --save
    
  5. Create an index.js file and copy the following code:

    'use strict'
    
    var express  = require('express');
    var app      = express();
    var port     = process.env.PORT || 5000;
    
    var mongoose    = require('mongoose');
    var database    = require('./configs/database');
    
    // Pull information from HTML POST (express4)
    var bodyParser     = require('body-parser');
    
    // Mongoose connection
    mongoose.connect(database[process.env.NODE_ENV].url);
    
    // Parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({'extended':'true'}));
    
    // Parse application/json            
    app.use(bodyParser.json());       
    
    // Parse application/vnd.api+json as json
    app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
    
    // Routes
    require('./routes/api-ai.js')(app);
    
    // Listen (start app with node index.js)
    app.listen(port);
  6. Create an database.js file with the following code inside the directory /configs. This file uses environment variables to provide the url for the database.

    module.exports = {
      development: {
        url: process.env.MONGODB_URI
      },
      staging: {
        url: process.env.MONGODB_URI
      },
      production: {
        url: process.env.MONGODB_URI
      }
    }
  7. Create an api-ai.js file with the following code inside the directory /routes. This file contains the webhook endpoint for API.AI, and the index endpoint.

    module.exports = function(app) {
      // Index route
      app.get('/', function (req, res) {
        res.send('Welcome to the Index Route');
      });
      // API.AI webhook route
      app.post('/webhook/apiai/', function(req, res) {
        // Your code for different actions sent by API.AI
        res.status(200).json('Sucessfull');
      });
    }
  8. Create an Procfile to tell Heroku where the server is.

    web: node index.js
    
  9. Setup your local environment variables(MongoDB, Node.js and Facebook Page Access Token) to test the server locally.

    export MONGODB_URI = mongodb://localhost/your-bot-database
    export NODE_ENV = development
    export FB_PAGE_ACCESS_TOKEN = YOUR-FACEBOOK-PAGE-ACCESS-TOKEN
    
  10. Commit all code, install mLab MongoDB, and deploy to Heroku:

    git init
    git add .
    git commit --message "first commit"
    heroku create app-name
    heroku addons:create mongolab:sandbox
    heroku config:set FB_PAGE_ACCESS_TOKEN=YOUR-FACEBOOK-PAGE-ACCESS-TOKEN
    git push heroku master
    

Using MongoDB

  1. Install MongoDB on your local environment using your favorite installer: https://docs.mongodb.com/manual/administration/install-community/

  2. Install mLab MongoDB on your Heroku app, if you haven't done it before:

    heroku -a app-name addons:create mongolab:sandbox
    
  3. Configure your MONGODB_URI on your local environment you haven't done it before:

    export MONGODB_URI = mongodb://localhost/your-bot-database
    
  4. In this project we are using Mongoose, as so, we need to define the model's that we will persist. For simple demonstration we will persist the Facebook User data of every user that interacts with our Chatbot. Create an user.js file inside /models with the following code:

    // Load mongoose since we need it to define a model
    const mongoose = require('mongoose');
    
    module.exports = mongoose.model('User', {
      facebookId: { type: String, required: true },
      firstName: String,
      lastName: String
    });
  5. Create an user.service.js file inside /services with the following code:

    const User = require('../models/user');
    const request = require('request');
    
    module.exports = {
      getFacebookData: getFacebookData,
      saveUser: saveUser
    }
    
    // Get user data Messenger Platform User Profile API and save it on the MongoDB
    function saveUser(facebookId, firstName, lastName) {
    
      getFacebookData(facebookId, function(err, userData){
        let user = {
          facebookId: facebookId,
          firstName: firstName || userData.first_name,
          lastName: lastName || userData.last_name
        };
    
        User.collection.findOneAndUpdate({facebookId : facebookId}, user, {upsert:true}, function(err, user){
          if (err) console.log(err);
          else console.log('user saved');
        });
      });
    }
    
    // Get User data from Messenger Platform User Profile API **NOT GRAPH API**
    function getFacebookData(facebookId, callback) {
    
      request({
        method: 'GET',
        url: 'https://graph.facebook.com/v2.8/' + facebookId,
        qs: {
          access_token: process.env.FB_PAGE_ACCESS_TOKEN
        }
      },
    
      function(err, response, body) {
    
        let userData = null
        if (err) console.log(err);
        else userData = JSON.parse(response.body);
    
        callback(err, userData);
      });
    }
  6. Update your api-ai.js file with the following code to to call the saveUser function from user.service and save every user that interacts with the Chatbot:

    const userService = require('../services/user.service');
    
    module.exports = function(app) {
      // Index route
      app.get('/', function (req, res) {
        res.send('Welcome to the Index Route');
      });
      // API.AI webhook route
      app.post('/webhook/apiai/', function(req, res) {
    
        // Your code for different actions sent by API.AI
        res.status(200).json('Sucessfull');
    
        // Save User to MongoDB
        userService.saveUser(req.body.originalRequest.data.sender.id);
      });
    }

botalize's People

Contributors

levinomoises avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.