How to use RiveScript in Node.js to reply with a Facebook Messenger bot

126 Views Asked by At

Currently, I keep receiving Promise, and the error User localuser was in an empty topic named 'random'.

My code is structured like this

const bot = new RiveScript();
bot.loadDirectory("./brain");
bot.sortReplies();

Below is in a function

// blah  
if (text === 'blah') {
    return {
        attachment: blah()
    };
}

// No command is correct
return {
    text: getReply(text)
};
function getReply(msg) {
    const reply = bot.reply("localuser", msg);
    return reply;
}

I've been trying everything, but I still need help getting a result where the text goes into the function and returns a reply from the RiveScript. I also ran debug, so the RiveScript files are definitely being read. I also tried using async functions and await for getReply but it doesn't work either.

1

There are 1 best solutions below

0
On

I'm not overly familiar with RiveScript, however checking their GitHub, loadDirectory is an asynchronous function which would show as Promise<Pending> until the Promise has resolved (or is rejected).

You need to wait for the Promise to resolve before moving on in your code. Read up on asynchronous javascript or node, because there is a lot to learn! https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous is a good start!

To start you off with your example:

const bot = new RiveScript();
bot.loadDirectory("./brain").then((response) => {
   //Once loadDirectory is complete then do this...
   bot.sortReplies();
});

then() will wait until the Promise has resolved before executing bot.sortReplies().

Note that .reply() also returns a Promise according to the ReadMe (https://github.com/aichaos/rivescript-js). So:

//bot.reply is asynchronous to you need to await the Promise to resolve before returning.
async function getReply(msg) {
   return await bot.reply("localuser", msg);
}

Hopefully this gives you something to play with!