Code Monkey home page Code Monkey logo

messenger-chatbot's Introduction

messenger-chatbot

A simple Facebook Messenger chat bot using Heroku + Firebase

Q: Why not just use one or the other?

A: Hosting Messenger chatbot using Firebase Functions would require external invocations - which is currently only available on Paid Plan. See Functions > Outbound Networking. Also, I want to demonstrate Firebase Realtime Database using javascript.

Try Magic X Ball Messenger Bot now.

Setup

  1. Install Heroku CLI. Create an account on Heroku if you don't have one.

  2. Install nodejs. Open your terminal and make sure that you have the updated version. If you're having issues with your npm version, you may use nvm and follow this guide here

    sudo npm install -g npm 
    npm -v       // Check npm version
    
  3. Create a folder for your project and create a initialize a new Node project.

    npm init
    
  4. Install additional Node dependencies. Express is for the server, request is for sending out messages, and body-parser is to process messages.

    npm install express request body-parser --save
    
  5. Follow steps on Facebook docs for the setup of your Messenger chatbot and getting the required API Keys.

  6. You may use the index.js on this project as a base and fill the required API Keys for your app to work.

    const token = "FB_PAGE_ACCESS_TOKEN"

    Get the Page Access Token by following the Step 3 of the docs.

  7. This app mimics a Magic 8 Ball. The bot will only accept answers when called as 'magic ball' or 'magicball'. An answer will be detected if the message from the user has a '?' at the end of the sentence.

    var engaged = false;  // set as false by default
    if (messageText) {
      // If we receive a text message, check to see if it matches a keyword
      // and send back an answer. Otherwise, ask the question again.
      if (messageText.toLowerCase().replace(/\s+/g, '')includes("magicball")){
        engaged = true; // Start accepting questions
        sendTextMessage(senderID, "Yes?");
      } else if (engaged && messageText.toLowerCase().includes("?")) {
        engaged = false;  // Once question is answered - set to false again
        sendAnswer(senderID);
      } else if (engaged){
        sendTextMessage(senderID, "Could you repeat your question again?");
      }
    } else if (messageAttachments) {
      sendTextMessage(senderID, "Message with attachment received");
    }
  8. For Firebase, currently, we'll only be using Realtime Database to fetch data. Create an account on Firebase if you don't have one.

  9. For Realtime Datbase, you may follow the quickstart guide here. You can find your Realtime Database URL in the Database tab in the Firebase console. It will be in the form of https://.firebaseio.com.

    /** Firebase **/
    var firebase = require("firebase");
    // Set the configuration for your app
    var firebaseConfig = {
      apiKey: "FIREBASE_API_KEY",  // Firebase Console > Project > Settings > Web API Key
      authDomain: "<APP_CODE>.firebaseapp.com",
      databaseURL: "https://<APP_CODE>.firebaseio.com",	// This chatbot only utilizes Firebase RTDB
      storageBucket: "<APP_CODE>.appspot.com"
    };
    firebase.initializeApp(firebaseConfig);
    // Get a reference to the database service
    var database = firebase.database();
  10. Reading from Firebase Realtime Database. You may read the docs here.

    function sendAnswer(senderID){
      let listAnswers = [];
      database.ref('xball/answers').once('value').then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          var answer = {};	// initialize new object
          // key
          answer['answerType'] = childSnapshot.key;
          // childData
          answer['answerText'] = childSnapshot.val();
          listAnswers.push(answer);
          console.log("sendAnswer " + answer.answerType + " " + answer.answerText);
        });
        let min = Math.ceil(0), max = Math.floor(Object.keys(listAnswers).length);
        // Generate random num
        let randNum = Math.floor(Math.random() * (max - min + 1)) + min;
        console.log("sendAnswer [" + randNum + "] ");
        sendTextMessage(senderID, listAnswers[randNum].answerText);
      });
    }

    The data is based from the list of possible answers of a Magic 8 Ball

  11. Create a file named Procfile and copy the line below. This is so Heroku can know what file to run.

    web: node index.js
    
  12. Commit all the code with Git then create a new Heroku instance and push the code to the cloud.

    git init
    git add .
    git commit --message "Initial commit"
    heroku create  // This will create a new project on Heroku, do this if you don't have a project for your chatbot yet.
    git push heroku master
    
  13. Test your bot

  14. Make your bot public! Try this bot now - Magic X Ball

    • You may share your bot by sharing its link https://m.me/<PAGE_USERNAME>
    • If you haven't published your bot yet, it can only respond to registered Developers/Testers on your Facebook App
    • Publish your Facebook App (Messenger Bot) by following their guide here.

Sources

This won't be possible without the sources from:

  • Facebook Messenger Platform guide link
  • Firebase docs link
  • jw84/messenger-bot-tutorial link

messenger-chatbot's People

Contributors

jofftiquez avatar omatt avatar

Stargazers

 avatar  avatar  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.