Thumbnail
WhatsApp Business API | Integration for IBM Watson

Are you looking to integrate your IBM Watson based assistant with whatsapp? We are going to explain how this integration looks like.

logo_ibm_watson_ct2x

Introduction

Are you looking to integrate your IBM Watson based assistant with whatsapp? We are going to explain how this integration looks like.

We are going to cover:

  1. Creation and training the assistant in IBM Watson.
  2. Integrating watson with our node project.
  3. Integrating watson with whatsapp business api provided by Tyntec.

Prerequisites

  • IBM cloud account.
  • Tyntec’s whatsapp business api.

Setup

1. Create and Train the assistant under IBM Watson

  • Login into your IBM cloud account and then go to watson assistant page.
  • Now, if you click on the create assistant button you will see the below screen.

Fill all the details and click on create assistant.

  • Now you can see our Tyntec Bot in the assistants page, select tyntec Bot. you will see the screen like below.
  • Click on ‘add dialog skill’ and you will see the below screen.

Enter all the necessary details and click on Create.

  • After creating the dialog it will reflect in the dashboard, click on the dialog that you created just now and you will see the below screen.

Now you can create intents and entities. Click on Create intent

  • Enter the intent name, description and training phases as shown in the below image.
  • Now let's come back to the skills page and go to the dialog section.
  • The Dialog section helps in deciding the flow of the chatbot and here we will feed the responses that have to be sent to users.
  • By default we have two nodes welcome and Anything else (Fallback).
  • Lets create a new node by clicking on the add node button.
  • Fill all the details like node name, when to trigger and responses. Once done close the modal.
  • Now click on Try it out from the top right corner, you will see the below screen.
  • You can notice in the above image - when i sent ‘hi’, the intent #introduction was triggered.
  • This is how we will train the assistant in watson. You can train as per your requirement.

Let’s move forward and see how to integrate our Watson assistant with the node js application.

2. Integrating watson in our node project

  • First visit https://cloud.ibm.com/resources and under the services section, you can find your assistant. Click on it and it will take you to the assistant management page. Now go to service credentials and find the credentials - api key, url and service id.
  • Store the configuration details of watson and tyntec in an environment file.
  • Now let's create a node application by running the command npm init.
  • After that now create a few files in the project directory with the given code.

app.js

Here we have the route “/message”, which we need to provide to tyntec support and ask them to configure it with your tyntec account. So that when a new message comes on whatsapp, it will trigger our backend.

const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: true}))
const watsonHandler = require('./watsonHandler')
const tyntecHandler = require('./tyntecHandler')
 
app.post('/message',  async(req,res)=>{
 
   let result =  await watsonHandler.sendTextToWatson(req.body.message)
   console.log(result)
   tyntecHandler.sendMessageToWhatsapp('req.body.from.jid', result.watsonRes)
   res.status(200).send('success')
})
 
app.get('/session', async(req,res)=>{
   let sessionID = await watsonHandler.createSession()
   res.send(sessionID)
})
 
app.listen('3000', ()=>{
   console.log('server started on port 3000')
})

watsonHandle.js

This file is responsible for sending the message to watson assistant and getting the response back.

'use strict'
 
const dotenv = require('dotenv')
dotenv.config()
const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');
 
const assistant = new AssistantV2({
 version: '2020-02-05',
 authenticator: new IamAuthenticator({
   apikey: process.env.API_KEY,
 }),
 url: process.env.URL,
 disableSslVerification: true,
 
});
 
//we should create a session and use the session id while sending the text to watson assistant
function createSession() {
 assistant.createSession({
   assistantId: process.env.ASSISTANT_ID
 })
   .then(res => {
     console.log(res.result.session_id);
     return res.result.session_id;
   })
   .catch(err=>{
       console.log(err)
   })
}
 
// This function is responsible for sending the text to watson and getting response
function sendTextToWatson(text){
 return new Promise((resolve, reject)=>{
   assistant.message({
     assistantId: process.env.ASSISTANT_ID,
     sessionId: process.env.SESSION_ID,
     input: {
       'message_type': 'text',
       'text': text
       }
     })
     .then(res => {
       console.log(JSON.stringify(res.result, null, 2));
       let watsonRes = res.result.output.generic[0].text
       let watsonIntent = res.result.output.intents[0].intent
       resolve({watsonRes,  watsonIntent});
     })
     .catch(err => {
       console.log(err);
       reject(err)
     });
 })
}
 
module.exports= {
 createSession,
sendTextToWatson
}

tyntecHandler.js

This will help to send a message back to whatsapp with the response that we received from watson.

'use strict'
const Request = require('request')
 
exports.sendMessageToWhatsapp = (to, text) => {
   return new Promise((resolve, reject) => {
       console.log("sendMessageToWhatsapp---to",to,"text---",text)
       var url = "https://api.eazy.im/2.0/message"
       var options = {
           url: url,
           headers: {
               'content-type': 'application/json',
               'Authorization': process.env.apiKeyWhatsApp
           },
           json: true,
           body: {
               "message": {
                   "body": text,
                   "type": "text"
               },
               "to": to
           }
 
       };
 
       function callback(error, response, body) {
           console.log("statusCode", response.statusCode)
           console.log("error",error)
           if (!error && response.statusCode) {
 
               if (response) {
                   resolve(body)
               } else {
                   reject(error)
               }
           } else {
               reject(error)
           }
 
       }
       Request.post(options, callback);
   })
}

Your setup is complete!

Train your assistant further and handle customer’s queries efficiently through your assistant.