Tuesday, 18 April 2017

watson conversation issue with twitter & facebook

I am having an issue when integrating watson conversation with twitter and facebook. I have set conversation_start variable to null in convesation dialog workspace because no matter what user input is, the first response is always the value in conversation_start variable .So i had to set it to null. Now a new problem has emerged as user has to input twice to get response (only at the start). PLease help me resolve it. I will be very grateful.Below is my code for twitter integration

     const Botmaster = require('botmaster');
      const TwitterBot = require('botmaster-twitter-dm');
      const express = require('express');
      const cfenv = require('cfenv');
      const _ = require('lodash');
      const Twit = require('twit');
      var bodyParser = require('body-parser'); // parser for post requests
      var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
      var request = require('request');
      var tt=require('twitter-text');

      // create a new express server
      var app = express();
      // get the app environment from Cloud Foundry
      var appEnv = cfenv.getAppEnv();
      // start server on the specified port and binding host
      app.listen(appEnv.port, '0.0.0.0', function() {
        // print a message when the server starts listening
        console.log("server starting on " + appEnv.url);
      });

      var conversation_context,conversation_id;
      const botmaster = new Botmaster();

      const twitterSettings = {
        credentials: {
          consumerKey: 'key',
          consumerSecret: 'secret',
          accessToken: 'token',
          accessTokenSecret: 'ats',
        }
      }

      var conversation = new Conversation({
        // If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
        // After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
        username: 'username',
        password: 'pass',
        url: 'https://gateway.watsonplatform.net/conversation/api',
        version_date: '2016-10-21',
        version: 'v1'
      });

      const bot = new TwitterBot(twitterSettings);
      botmaster.addBot(bot);



      myIncomingMiddlewareController = (bot, update) => {

                    //console.log("Twitter Conversation start");
                    //console.log("Messsage "+update.message.text);
                    var params = {
                        input: update.message.text,
                        context: conversation_context /*|| {"conversation_id": conversation_id}*/

                    };



                    var payload = {
                      // Put your workspace id of your conversation service here.
                      workspace_id: process.env.WORKSPACE_ID || 'workspaceid',
                 // conversation_start:true
                    };

                    if (params) {
                      if (params.input) {
                        params.input = params.input.replace("\n","");
                        payload.input = { "text": params.input };
                      }
                      if (params.context) {
                        payload.context = params.context;
                      }
                    }

                    //console.log("payload generaated");

                    //console.log("calling watson");

                 callWatson(payload, update, bot);

      };


      botmaster.use({
        type: 'incoming',
        name: 'My incoming middleware',
        controller: myIncomingMiddlewareController,
      });


      //talking to watson

      function callWatson(payload, sender, bot) {
        //console.log("gonna talk to watson");
        conversation.message(payload, function (err, convResults) {
          if (err) {
            return responseToRequest.send("Erro.");
          }

          if(convResults.context !== null){
            conversation_id = convResults.context.conversation_id;
            conversation_context = convResults.context;

          }
          if(convResults !== null && convResults.output !== null){
             console.log(convResults);
            //console.log(convResults.output);
            var i = 0;
            while(i < convResults.output.text.length){
              if(convResults.output.text[i].search("knowmax_request") != -1)
              {
                  sendGenericMessage(sender,convResults.entities[0].value,bot)
              }
              else{
                console.log("watson result: "+convResults.output.text[i]);
                    sendMessage(sender, convResults.output.text[i], bot);
                }
              i++;
            }
          }


        });
      }

      //simple msg

      function sendMessage(sender, text, bot) {
        return bot.reply(sender, text);
      }

      //generic msg

      function sendGenericMessage(sender,entities,bot) {

      request({
              url: 'http://knowledge-base.com/ChatAssistService/Search.svc/getservicedata_v1/'+entities+'/6',
              method: 'GET'
          }, function (error, response, body) {
              if (error) {
                  return console.error('Error :', error);
              } 
                data = JSON.parse(body);
                if(data.length != 0){
                    url = data[0].url;
                    title = data[0].text;
                    dt = title+" "+url;

               return bot.reply(sender,dt);
              }
          } );

      }



via Malkit Singh

No comments:

Post a Comment