ibm-cloudwatson-conversationbotkitwatson-assistantibm-cloud-functions

How can I use Botkit Middleware with Watson Assistant dialog server actions?


I followed this tutorial to deploy a Slackbot with Watson Assistant. The tutorial uses server actions in the dialog to directly interface with a database. To connect Slack with Watson Assistant the tutorial uses the Conversation connector. That works fine, but I am interested in how to do the same with Botkit and the Botkit Middleware provided by Watson Developer Cloud.

How can I use the serverless actions, how do I obtain and pass the necessary API key?


Solution

  • There is actually code that demonstrates how to configure the API key for IBM Cloud Functions and pass it as context variable to Watson Assistant. It makes use of the before method to add the API key to the context variable. The value is configured in a separate file together with the other app-related credentials. The code tests whether the context variable and the key exist, else it is added:

    middleware.before = function(message, conversationPayload, callback) {
      // Code here gets executed before making the call to Conversation.
    
      // retrieve API Key from environment and split it into user / password
      var arr=process.env.ICF_KEY.split(":");
      // check if context exists
      if (typeof(conversationPayload.context) === 'undefined') {
          var context={context: {}}
          Object.assign(conversationPayload, context);
      }
      // if credentials already exists, we don't have to add them
      // else add credentials under private element in context
      if (typeof(conversationPayload.context.icfcreds) === 'undefined') {
         var privcontext = {"private": {icfcreds: {user: arr[0], password: arr[1]}}};
         Object.assign(conversationPayload.context, privcontext);
      }
    
      // log the payload structure for debugging
      // console.log(conversationPayload)
      callback(null, conversationPayload);
    }