remixz / messenger-bot

A Node client for the Facebook Messenger Platform
MIT License
1.09k stars 213 forks source link

built-in NLP support? #79

Open sgkhode opened 6 years ago

sgkhode commented 6 years ago

I would like to know if built-in NLP support is added in this library, as described here: https://developers.facebook.com/docs/messenger-platform/built-in-nlp

When would it be available?

slidenerd commented 5 years ago

I double this, I am guessing you will have to modify the handleMessage method to add some callback for handling built in NLP calls

slidenerd commented 5 years ago

I found how to do that. If you enable built in NLP with the default English language model, the structure of your payload inside bot.on("message") looks as follows

{"sender":{"id":"1264345230309999"},"recipient":{"id":"1796187950609999"},"timestamp":1560751759389,"message":{"mid":"p_lqjiuSBZxsOx13swH47cG5zAB69T8EBhssJlJt9TQ6dHAyn6pQV_ljt-xkjjRJvMZhDV5Y_Trbqlz5ln9999","seq":0,"text":"hey there","nlp":{"entities":{"sentiment":[{"confidence":0.8168874995786,"value":"neutral"}],"greetings":[{"confidence":0.99825531242256,"value":"true"}]},"detected_locales":[{"locale":"en_XX","confidence":0.9997}]}}}

As you can see, you just need to check for the existence of NLP property which contains an ibject of entities

Here is how it works


bot.on('message', (payload, reply, actions) => {
    try {
        console.log(JSON.stringify(payload));
        handleMessage(payload, reply);
    } catch (error) {
        console.log(error);
    }
});

function firstEntity(nlp, name) {
    return nlp && nlp.entities && nlp.entities[name] && nlp.entities[name][0];
}

function handleMessage(payload, reply) {
    // check greeting is here and is confident
    const greeting = firstEntity(payload.message.nlp, 'greetings');

    if (greeting && greeting.confidence > 0.8) {
        reply({ text: `Hi There!` }, (err, info) => { });
    } else {
        // default logic
        reply({ text: `You said ${payload.message.text}` }, (err, info) => { });
    }
}