aichaos / rivescript-js

A RiveScript interpreter for JavaScript. RiveScript is a scripting language for chatterbots.
https://www.rivescript.com/
MIT License
377 stars 144 forks source link

Slack-bot example, returns undefined #302

Closed geoapi closed 5 years ago

geoapi commented 5 years ago

Trying a simple HTTP request within javascript rive file to test the slack-bot with the below macro, it does print the output on console correctly, but I get undefined on Slack , tried changing the current reply to an async await function just in case and same problem still there, any help please?

+ test
- <call> test</call>
> object test javascript
const request = require('request');
request('http://jsonplaceholder.typicode.com/todos', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
  console.log(body[0].title)  // some text title
  return(body[0].title); //this is just a simple title which returned as undefined!
});
< object
kirsle commented 5 years ago

Hi, try it like this:

+ test
- <call> test</call>
> object test javascript
const request = require('request');
return new Promise(function(resolve, reject) {
  request('http://jsonplaceholder.typicode.com/todos', { json: true }, (err, res, body) => {
    if (err) { reject(err); }
      console.log(body[0].title)  // some text title
    resolve(body[0].title);
  });
});
< object

It was returning "undefined" before because the object macro function wasn't returning anything at all! You were firing off an asynchronous request() function and handling the response in a separate function, but by the time that happened, RiveScript has long since already called the macro and gotten the "undefined" return value and ran with that.

The macro should instead return a Promise that you can resolve later in your request() callback function. Promise return types get waited on by RiveScript before it returns the final reply to the user.

geoapi commented 5 years ago

That solved the problem, thank you very much for your help