Skip to content

PHILIA Recipe engine is a Facebook messenger bot that provide over 2 million recipes and meal recommendations for special diets.This bot allows customers to search by diet, health labels and many .

License

Notifications You must be signed in to change notification settings

philodi-dev/philia-bot-messenger

Repository files navigation

PHILIA RECIPE ENGINE

Build a Facebook Messenger Bot with Node.js and a RESTFUL API In Just 5 minutes

Chatbots are computer programs that mimic conversation with people through the use of artificial intelligence. In a nutshell, when someone types in a message, the bot responds with the right reply. Out of the thousands of chatbots that exist today, most are messenger apps designed to communicate with customers. They work with Natural Processing Language (NLP) systems which translate everyday language into a form that the bot can understand and learn new interactions from.

Through the help of that technology, bots now hold endless possibilities. You can use them to read everyday news, get the weather, transfer money, buy your favorite items, schedule a meeting, or even get service assistance. And all from the convenience of your favorite messenger app.

People are now spending more mobile screen time on messaging than on social media. A lot of companies have noticed the trend and are taking advantage of chatbots as a new channel to talk to us. Turns out that a whopping 60% of online adults in the US use online messaging, voice or video chat services.

Today, I’m going to show you how to build your own Facebook Messenger bot node.js in just 5 minutes

A step-by-step guide to building the chatbot

What it does?

PHILIA Recipe Engine was originally an Alexa conversation skill, which provides more than 2 million indexed, standardized, and complete nutritional information recipes; so I decided to create a facebook-messenger bot for this project as well. The bot allows searches by amount of nutrients, 40 diets and health labels, as well as keyword searches by type of cuisine (Chinese, Italian, Indian, French, ...), by type of meal (lunch, dinner, breakfast, snack) or by type of dish (soup, salad, pizza, sandwich, ...).

Prerequisites

In order to start writing this bot application, there are a few requirements:

So, assuming we have all the above covered — Let’s get started!

Step 1: Creating a github repository

First we need to create a github repository. If you don't know how to do this, then look here.

Step 2: Writing webhook server with Restify

First of all, we need to know that a webhook (also called a web callback or HTTP push API) is a way for an app to provide other applications with real-time information. It delivers data to other applications as it happens, meaning you get data immediately, unlike typical APIs where you would need to poll for data very frequently in order to get it in real-time. In order to get started, you will have to clone the github repository that we created into the local machine. Once, you it is done , go to your terminal, access this directory and initialize your Node.js app with:

npm init

After filling out all the needed info (if you don’t know how to fill package.json, take a look here ), your next step will be to install the required dependencies to setup our webhook server. So, in your terminal type:

npm install restify request --save

Once the installation is complete, go to your directory and create a file called index.js and start Restify server listening to the port 8001 (you can take any you want).

const Restify = require('restify')
let PORT = process.env.PORT || 8001;

const app = Restify.createServer({
    name: 'philia recipe engine'
})
app.use(Restify.plugins.bodyParser({ limit: '50mb' }))
app.use(Restify.plugins.jsonp())

app.listen(PORT, () =>
    console.log('Server listening on:' + PORT)
);

Save it and let’s check if it’s working. Run this command in your terminal:

node index.js

Great, our server is listening! Now we are going to create two endpoints:

  1. One will be for Facebook initial verification. The reason why we need to do this is because when you’re connecting a Facebook page with the webhook server you will also need have a token. Facebook will make a request and match this token to that one webhook response to be sure that you’re not connecting your page with a random webhook server.
  2. The second one will be responsible for the other messages from Facebook Messenger.

The first verification endpoint goes to index.js like this:

const Restify = require('restify')
let PORT = process.env.PORT || 8001;

const token = 'abc12345'
const app = Restify.createServer({
    name: 'philia recipe engine'
})
app.use(Restify.plugins.bodyParser({ limit: '50mb' }))
app.use(Restify.plugins.jsonp())

app.get('/', (req, res, next) => {
    if (req.query['hub.mode'] == 'subscribe' && req.query['hub.verify_token'] == token) {
        res.end(req.query['hub.challenge'])
    } else {
        next()
    }
})

app.listen(PORT, () =>
    console.log('Server listening on:' + PORT)
);

Here you can see a token string value “abc12345” . You can change it and choose any word or text string value that you prefer. Make sure to make a note of it as you will need it later when setting up your Facebook app.

Before dealing with our second final point, we will have to create a file named methods.js to implement all the http post methods for our bot, like this :

const request = require('./requestPromise')

module.exports = class methods {
    constructor(access_token) {
        this.ACCESS_TOKEN = access_token
    }

    async sendText(text, id) {
        const json = {
            recipient: { id },
            message: { text }
        }

        const res = await request({
            url: 'https://graph.facebook.com/v8.0/me/messages',
            qs: {
                access_token: this.ACCESS_TOKEN
            },
            json,
            method: 'POST'
        })
        console.log('Facebook says: ', res)
    }

    async sendImageAttachment(image, id) {
        const json = {
            recipient: { id },
            message: { 
                attachment:{
                    type:'image',
                    payload:{
                        url:image, 
                        is_reusable:true
                    }
                }
             }
        }

        const res = await request({
            url: 'https://graph.facebook.com/v8.0/me/messages',
            qs: {
                access_token: this.ACCESS_TOKEN
            },
            json,
            method: 'POST'
        })

        console.log('Facebook says: ', res)
    }

    getMessageObject(json) {
        const message = json.entry[0].messaging[0].message.text
        const id = json.entry[0].messaging[0].sender.id
        return {message, id}
    }
}

For this to work we need to create a requestPromise.js file to handle all the promised responses from our client's facebook messenger.

const request = require('request')
module.exports = function(obj) {
    return new Promise((resolve, reject) => {
        request(obj, (error, response, body) => {
            if(!error) {
                resolve(body)
            } else {
                reject(error)
            }
        })
    })
}

Now it is time to add our second endpoint in our webhook server for handling all the Facebook bot messages and by providing our Facebook page token, we will see how to create this.

const Restify = require('restify')
const methods = require('./methods')

let PORT = process.env.PORT || 8001;

const app = Restify.createServer({
    name: 'philia recipe engine'
})

const token = 'abc12345'
const bot = new methods('EAANz0eBh2w8BANf1PMdNdruoYmHScelZCDkpDCFMoZAdcvgaa7pHeOKsxLDEIN9vDaDoEZAHfK9GcsQdjFe2GTG32z1oCw7FxWZA9AFW34H2LQp1Opx9b7fQZBC3cyntPfriqDUmEYBm1VG2i60tZBHtBZABN6Wl5RTuw7TGlm7p33Gv20W5zCKwLsBYW9ljysZD')

app.use(Restify.plugins.bodyParser({ limit: '50mb' }))
app.use(Restify.plugins.jsonp())

app.get('/', (req, res, next) => {
    if (req.query['hub.mode'] == 'subscribe' && req.query['hub.verify_token'] == token) {
        res.end(req.query['hub.challenge'])
    } else {
        next()
    }
})

app.post('/', (req, res, next) => {
    const response = req.body
    const index = Math.floor(Math.random() * (3 - 1) + 1)
    const index2 = Math.floor(Math.random() * (6 - 1) + 1)
    const mealMessage = ['Baked Chicken', 'Drunken Chicken Recipe', 'Chicken Satay','Chicken Feet Stock', 'Catalan Chicken', 'Creamed Chicken recipes']
    const welcomeMessage = ['Welcome to philia, your personal food recommendation assistant. you can search for a special diet meal planning by saying, Can I get a high-protein  meal, please ?  or just say , Can you search for a burger recipe ? or ask for help','Hello dear customer, I am philia, your personal assistant for dietary recommendations. you can ask for help or search for a special diet meal planning by saying, Do you have balanced meal ? or Can I get a pizza recipe ?','Hello, my name is philia, your personal assistant to find you meals that match your diet and taste. search for a special diet meal planning by saying; Do you have low-sodium meal ? or just say ; Can I get a chicken recipe ? or just ask for help']
    const image = ['https://www.edamam.com/web-img/01c/01cacb70890274fb7b7cebb975a93231.jpg','https://www.edamam.com/web-img/921/9216913515dc95ba687e2ae85d6ef3e0.jpg', 'https://www.edamam.com/web-img/ba6/ba6f66d885e4d62a98055b088a5a85a3.jpg', 'https://www.edamam.com/web-img/ae9/ae96650072cc599967d945c5e9961bb7.JPG', 'https://www.edamam.com/web-img/4d9/4d9084cbc170789caa9e997108b595de.jpg', 'https://www.edamam.com/web-img/67d/67dfcb646ef76499afc7b89640868099']
    if (response.object === "page") {
        const messageObj = bot.getMessageObject(response)
        if(messageObj.message.includes('meal') || messageObj.message.includes('recipe') || messageObj.message.includes('do you have') || messageObj.message.includes('may I have') || messageObj.message.includes('do you have') || messageObj.message.includes('can I order')){
            bot.sendText(`In that case , I recommend that you take ${mealMessage[index2]}`, messageObj.id)
            bot.sendImageAttachment(`${image[index2]}`, messageObj.id)
        }else if (messageObj.message.includes('thank')){
            bot.sendText(`It is still my pleasure to help you out`, messageObj.id)
        }else if (messageObj.message.includes('bye')){
            bot.sendText(`Good bye, see you soon`, messageObj.id)
        }
        else{
            bot.sendText(`${welcomeMessage[index]}`, messageObj.id)
        }
    }
    res.send(200)
})

app.listen(PORT, () =>
    console.log('Server listening on:' + PORT)
);

Step 4 : Setting up Facebook Application

Before continuing to send requests to Facebook, let’s create our Facebook app. To create a Facebook Messenger bot, we need the two things:

  • Facebook public page, that you’ll connect with your bot.
  • Facebook Developer application, which will be connected to your webhook server and your public page, and work as a middleware between them.

First you need to create a Facebook page. Go to https://web.facebook.com/pages/create?. Choose a Page name, Category, Description and click create Page.

After that you’ll need to login in your Facebook developer account and create an app. Go to https://developers.facebook.com/apps/, click the “Create App” button, select “Manage Business Integrations” then click “Continue”. In the next popup modal, write in the name of app, select your App purpose (eg. Clients) and then click again “Create App”.

After creating the App, you have to select a product. Click the“Messenger” icon and then click on the “Set Up” button. This will redirect you to the Messenger Platform.

Once you’re there, you must locate the “Access Tokens” section. click on “Add or Remove Pages” button to select the page you already created by following the step it ask and you will click on the “Generate Token” button located in the right side of your selected page. It will give you a Page Access Token that we will replace in our node js webhook server by copying it.

Below this section is the Webhooks section. Click on “Add Callback URL” and it will show you a popup window, where you’ll need to fill out the following:

  • Callback URL: With your heroku app url , in my case it is https://philodi-recipe-engine.herokuapp.com/. (change this with yours).
  • Verify Token: The token string value for validation that you already chose from your index.js file.

After doing that , you will need to add a Subscription Fields. Click on "Add Subscriptions" button located in the right side of your selected page in the Webhooks session, choose "messages" and click " save " button. If you want to know more about webhooks events read this information.

Now, all that’s left is to test our bot. If all is well with your bot, you should get replies from the bot for some simple questions like “Hello ?”, " thank you", " can I order a balanced meal ?", " do you have italian food ?", etc…

Summary

Congratulations on making it through this project with me! I had a lot of fun and hope you did as well. I built a basic Facebook Messenger bot with node.js and tested it on Facebook Messenger app.

If you’d like to see a full-working version of this, you can check it out here on GitHub. If you want to make this better, I encourage you to open a pull request! You can ask questions there in an issue or open an issue if you find a bug. All contributions are welcome!

Next Steps

If you’d like to continue hacking on this project further, here are a few ideas:

  • Send a message to the user along with the username of the person who interacted with the bot
  • Interact with the bot with a voice interface
  • Integrate Natural languange experiences to the bot (for example wit.ai)
  • Send a Request for reviews to get your app live and published for production

Let me know if you do this or something similar. We’d love to see what you build.

Resources for Learning More on Facebook Messenger bot

Looking for more ways to develop your Facebook Messenger bot skills? Here are a few recommendations for continuing your learning :

Thanks for reading. Happy coding!

Special thanks to the Facebook Developer Circles for the tutorial examples which made writing this tutorial possible.

To learn more about Facebook Open Source, visit Facebook open source website, subscribe on Facebook open source Youtube, or follow Facebook open source products on Facebook.

About

PHILIA Recipe engine is a Facebook messenger bot that provide over 2 million recipes and meal recommendations for special diets.This bot allows customers to search by diet, health labels and many .

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published