简体   繁体   中英

IBM watson Integration with twilio

I am trying to integrate IBM Watson bot with twilio, whatsapp using IBM cloud functions using Nodejs. I followed the following blog to come up with this code

https://www.codechain.com.br/2019/02/20/ibm-cloud-alem-do-watson-whatsapp-gateway-100-serverless/

Please find below code for reference:

var AssistantV2 = require( 'ibm-watson/assistant/v2' )

var twilio = require ( 'twilio' ) ;
async function main ( parameters ) { 
   try {
       var assistant = new AssistantV2({
       version: '2019-02-28',
       iam_apikey: '',
       url: ''
       });
      // printing values ​​received by twilio (message sent by the user)
      console.log ( 'parameters received from twilio:' , parameters ) ;
      console.log ( 'AccountSid:' + parameters.AccountSid ) ;
      console.log ( 'Body:'+ parameters.Body ) ;
      console.log ( 'From:'+ parameters.From ) ;
      console.log ( 'NumMedia:' + parameters.NumMedia ) ;
      console.log ( 'MediaContentType0:' + parameters.MediaContentType0 ) ;
      console.log ( 'MediaUrl0:' + parameters.MediaUrl0 ) ;
      // inform the user who received your message
      // this line is only for testing, in a real scenario a chatbot integration should be called
      parameters.message = assistant.message({
                            assistantId: '',
                            sessionId: parameters.sid,
                        input: {
                                'message_type': 'text',
                                'text': parameters.Body
                                }
                       })

  .then(res => {
    console.log(JSON.stringify(res, null, 2));
  })
  .catch(err => {
    console.log(err);
  });
     await callTwilio ( parameters ) ;
     console.log ( 'whatsapp call ended' ) ;
     return {
        statusCode: 200 ,
        headers: { 'Content-Type' : 'application / json' } ,  
        body: { Body: 'success' } , 
     } ;
   } catch ( err ) {   
      console.log ( err )
     return Promise. reject ( {
        statusCode: 500 ,
        headers: { 'Content-Type' : 'application / json' } ,  
        body: { message: err.message } ,
     } ) ;
   }
}
async function callTwilio ( parameters ) {
   console.log ( 'joined twilio' ) ;
   var client = new twilio ( parameters.AccountSid, parameters.authToken ) ;
   await client.messages. create ( {
      body: parameters.message,
      to: parameters.From,
      from: 'whatsapp:+' + parameters.telephoneOrigin
   } )
   . then ( ( message ) => console. log ( message.sid ) ) ;
   console.log ( 'left twilio' ) ;

}

But I am getting the following error response:

Results:
{
  "error": {
    "body": {
      "message": "username is required"
    },
    "headers": {
      "Content-Type": "application / json"
    },
    "statusCode": 500
  }
}

The code that you have looks correct for older 4.x versions of the npm module ibm-watson. The code that @Andrei has shows is partially correct for 5.x versions. I am guessing that you have cloned a repo that has a package.json dependancy for a 4.x version.

If this is the case you need to modify the dependancy in package.json . Current version is 5.3.1

Then run a npm install to pull the updated version of the ibm-watson package.

Your authentication should then be based on the API docs - https://cloud.ibm.com/apidocs/assistant/assistant-v2?code=node

const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');

const assistant = new AssistantV2({
  version: '{version}',
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  url: 'https://api.jp-tok.assistant.watson.cloud.ibm.com',
});

but then you need to create a session.


let sessionID = null;

assistant.createSession({
  assistantId: '{assistant_id}'
})
  .then(res => {
    if (res && res.session_id) {
      sessionID = res.session_id;
    }}
  })
  .catch(err => {
    console.log(err);
  });

You can then send messages to the Assistant service.

By the way, because you have shared your APIKey, endpoint url and assistant id in your answer, it is very easy for anyone to use it. You will need to revoke your key, and create a new one, because your existing one is now compromised.

Looks like the authentication is not done correctly for IBM Watson

in the NPM docs here's the following https://www.npmjs.com/package/ibm-watson

const AssistantV2 = require('ibm-watson/assistant/v2');
const { IamAuthenticator } = require('ibm-watson/auth');

const assistant = new AssistantV2({
  authenticator: new IamAuthenticator({ apikey: '<apikey>' }), // need to use this
  url: 'https://gateway.watsonplatform.net/assistant/api/',
  version: '2018-09-19'
});

assistant.message(
  {
    input: { text: "What's the weather?" },
    assistantId: '<assistant id>',
    sessionId: '<session id>',
  })
  .then(response => {
    console.log(JSON.stringify(response.result, null, 2));
  })
  .catch(err => {
    console.log(err);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM