FB Bot coding on Cloud9



  • Referenced from - https://codingislove.com/build-facebook-chat-bot-javascript/

    I can't get my bot to respond.

    I also get this error below when I added the last handleMessage function

    Result:

    1269477626479023
    b
    ReferenceError: request is not defined
        at sendHelp (/home/ubuntu/workspace/server.js:60:3)
        at handleMessage (/home/ubuntu/workspace/server.js:35:17)
        at callbacks (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:161:37)
        at param (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:135:11)
        at pass (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:142:5)
        at Router._dispatch (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:170:5)
        at Object.router (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:33:10)
        at next (/home/ubuntu/workspace/node_modules/express/node_modules/connect/lib/proto.js:190:15)
        at multipart (/home/ubuntu/workspace/node_modules/express/node_modules/connect/lib/middleware/multipart.js:60:27)
        at /home/ubuntu/workspace/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:57:9
    

    Code:

    var express = require('express'); //express handles routes
    var http = require('http'); //need http module to create a server
    var app = express(); //starting express
    
    app.set('port', process.env.PORT || 3000); //set port to cloud9 specific port or 3000
    app.use(express.bodyParser()); //body parser used to parse request data
    app.use(app.router);
    app.get('/', verificationHandler);
    function verificationHandler(req, res) {
      console.log(req);
      if (req.query['hub.verify_token'] === 'verifycode') {
        res.send(req.query['hub.challenge']);
      }
      res.send('Error, wrong validation token!');
    }
    http.createServer(app).listen(app.get('port'), function() {
      console.log('Express server listening on port ' + app.get('port'));
    });
    
    app.post('/',handleMessage);
    
    function handleMessage(req, res) {
        var messaging_events = req.body.entry[0].messaging;
        for (i = 0; i < messaging_events.length; i++) {
            event = req.body.entry[0].messaging[i];
            var sender = event.sender.id;
            console.log(sender);
            if (event.message && event.message.text) {
                var text = event.message.text.toLowerCase().trim();
                console.log(text);
                if (text.toLowerCase().substr(0,4) == 'wiki') {
                    wikibot(text.replace("wiki ", ""),sender)
                }
                else {
                    sendHelp(sender);
                }
            }
            else if(event.postback && event.postback.payload){
               sendMessage(sender,event.postback.payload) ;
            }
        }
        res.end('replied!');
    }
    
    
    var url = "https://graph.facebook.com/v2.6/me/messages?access_token=EAAXCoDXitiYBAJjgLnsIZAfZAyCrQ0gCQTbNdB9cHyvlDoZA3KOunEX08UcutrQDXxEQhnyYZB4ZBpLd7KvzG0JBahOrZBo36yNvdZCEYB9lZBNCfdzKt5VuJnOFekZCpeCkfaEcAw8NHYsVuq6lkNVbWOUiVbiMDwUuY75EbKkiOTQZDZD" //replace with your page token
    function sendHelp(id) {
    var options = {
        uri: url,
        method: 'POST',
        json: {
          "recipient": {
            "id": id
          },
          "message": {
            "text": "Send wiki space 'Your query' to search wikipedia"
          }
        }
      }
      request(options, function(error, response, body) {
        if (error) {
          console.log(error.message);
        }
      });
    };
    
    function wikibot(query, userid) {
      var queryUrl = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts&exintro&explaintext&exsentences=5&exlimit=max&gsrsearch=" + query;
      var myTemplate = {
        recipient: {
          id: userid
        },
        message: {
          attachment: {
            type: "template",
            payload: {
              template_type: "generic",
              elements: []
            }
          }
        }
      };
      var options = {
        url: url,
        method: 'POST',
        body: myTemplate,
        json: true
      }
      request(queryUrl, function(error, response, body) {
        if (error) {
          console.log(error);
        }
        try {
          body = JSON.parse(body);
          var pages = body.query.pages;
          for (var i = 0 in pages) {
            var myelement = {
              title: "",
              subtitle: "",
              buttons: [{
                type: "postback",
                title: "Read more",
                payload: "Nothing here, Please view in browser"
              }, {
                type: "web_url",
                url: "",
                title: "View in browser"
              }]
            };
            myelement.title = pages[i].title;
            myelement.subtitle = pages[i].extract.substr(0, 80).trim();
            myelement.buttons[1].url = "https://en.wikipedia.org/?curid=" + pages[i].pageid;
            if (pages[i].extract != "") {
            myelement.buttons[0].payload = pages[i].extract.substr(0, 1000).trim();
            }
            myTemplate.message.attachment.payload.elements.push(myelement);
          }
          options.body = myTemplate;
        }
        catch (err) {
          console.log("error : " + err.message);
          options = {
            uri: url,
            method: 'POST',
            json: {
              "recipient": {
                "id": userid
              },
              "message": {
                "text": "Something went wrong, please try again."
              }
            }
          }
        }
        request(options, function(error, response, body) {
          if (error) {
            console.log(error.message);
          }
          console.log(body);
        });
      })
    };
    
    function formatmsg(msg){
        msg = msg.substr(0,320);
        if(msg.lastIndexOf(".") == -1) {
            return msg;
        }
        return msg.substr(0,msg.lastIndexOf(".")+1);
    }
    

    Here is the code that doesn't give the error, I can see messages sent via messenger on Cloud9 server.js tab, but the bot doesn't respond.

    Result:

    Important: use process.env.PORT as the port and process.env.IP as the host in your scripts!
    
    Debugger listening on port 15454
    Express server listening on port 8080
    b
    test message
    

    Code:

    var express = require('express'); //express handles routes
    var http = require('http'); //need http module to create a server
    var app = express(); //starting express
    
    app.set('port', process.env.PORT || 3000); //set port to cloud9 specific port or 3000
    app.use(express.bodyParser()); //body parser used to parse request data
    app.use(app.router);
    app.get('/', verificationHandler);
    function verificationHandler(req, res) {
      console.log(req);
      if (req.query['hub.verify_token'] === 'verifycode') {
        res.send(req.query['hub.challenge']);
      }
      res.send('Error, wrong validation token!');
    }
    http.createServer(app).listen(app.get('port'), function() {
      console.log('Express server listening on port ' + app.get('port'));
    });
    
    app.post('/',handleMessage);
    
    function handleMessage(req, res) {
      messaging_events = req.body.entry[0].messaging;
      for (i = 0; i < messaging_events.length; i++) {
        event = req.body.entry[0].messaging[i];
        sender = event.sender.id;
        if (event.message && event.message.text) {
          text = event.message.text;
          console.log(text);
        }
      }
      res.end('received!');
    }
    
    
    var url = "https://graph.facebook.com/v2.6/me/messages?access_token=EAAXCoDXitiYBAJjgLnsIZAfZAyCrQ0gCQTbNdB9cHyvlDoZA3KOunEX08UcutrQDXxEQhnyYZB4ZBpLd7KvzG0JBahOrZBo36yNvdZCEYB9lZBNCfdzKt5VuJnOFekZCpeCkfaEcAw8NHYsVuq6lkNVbWOUiVbiMDwUuY75EbKkiOTQZDZD" //replace with your page token
    function sendHelp(id) {
    var options = {
        uri: url,
        method: 'POST',
        json: {
          "recipient": {
            "id": id
          },
          "message": {
            "text": "Send wiki space 'Your query' to search wikipedia"
          }
        }
      }
      request(options, function(error, response, body) {
        if (error) {
          console.log(error.message);
        }
      });
    };
    
    function wikibot(query, userid) {
      var queryUrl = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts&exintro&explaintext&exsentences=5&exlimit=max&gsrsearch=" + query;
      var myTemplate = {
        recipient: {
          id: userid
        },
        message: {
          attachment: {
            type: "template",
            payload: {
              template_type: "generic",
              elements: []
            }
          }
        }
      };
      var options = {
        url: url,
        method: 'POST',
        body: myTemplate,
        json: true
      }
      request(queryUrl, function(error, response, body) {
        if (error) {
          console.log(error);
        }
        try {
          body = JSON.parse(body);
          var pages = body.query.pages;
          for (var i = 0 in pages) {
            var myelement = {
              title: "",
              subtitle: "",
              buttons: [{
                type: "postback",
                title: "Read more",
                payload: "Nothing here, Please view in browser"
              }, {
                type: "web_url",
                url: "",
                title: "View in browser"
              }]
            };
            myelement.title = pages[i].title;
            myelement.subtitle = pages[i].extract.substr(0, 80).trim();
            myelement.buttons[1].url = "https://en.wikipedia.org/?curid=" + pages[i].pageid;
            if (pages[i].extract != "") {
            myelement.buttons[0].payload = pages[i].extract.substr(0, 1000).trim();
            }
            myTemplate.message.attachment.payload.elements.push(myelement);
          }
          options.body = myTemplate;
        }
        catch (err) {
          console.log("error : " + err.message);
          options = {
            uri: url,
            method: 'POST',
            json: {
              "recipient": {
                "id": userid
              },
              "message": {
                "text": "Something went wrong, please try again."
              }
            }
          }
        }
        request(options, function(error, response, body) {
          if (error) {
            console.log(error.message);
          }
          console.log(body);
        });
      })
    };
    
    function formatmsg(msg){
        msg = msg.substr(0,320);
        if(msg.lastIndexOf(".") == -1) {
            return msg;
        }
        return msg.substr(0,msg.lastIndexOf(".")+1);
    }
    

  • administrators

    You haven't installed request module. Install it using npm install request --save

    Follow all the steps specified in the tutorial.



  • I did install request, problem still persists


  • administrators

    Then you forgot to require request module. Add this at the top of your server.js

    var request = require('request');
    

    I did not mention this in tutorial because I thought its quite obvious. I'll add it now.



  • That did it! I appreciate your help and I'm sorry I'm quite new to coding, I wasn't sure how to define request. Thank you so much again!!


Log in to reply
 

Looks like your connection to Codingislove Forum was lost, please wait while we try to reconnect.