Create the Node-RED Messenger listener

You’ve created the Node-RED webhooks for Facebook Messenger. Next, you’ll create the flow that will listen to message texts.

    1. In your Node-RED flow editor, drag and drop the following nodes onto the canvas:
      • Input http input node
      • Output http response node
      • Function node
      • Two output debug nodes
    2. Double-click the function node and set Outputs to 2. Name it Look for Messages. Then, click Done.

    1. Wire the nodes together:

      Wire the input http node to the first debug node (msg.payload). Also, wire the input http node to the function node. Then, wire the functionnode to both the debug node (msg.payload) and the output http response node.

    2. Double-click the input http node and specify the method as POST and the URL as /mybot or the URL that you registered as your webhook. Name it Messenger Chat Listener. Then, click Done.

      1. Double-click the function node, name it Look for messages, and enter the following code.
        This function loops though the submitted entries and for each message that is detected, sends a message signal to the first output. It ends by sending a message (msg) object to the second output.

        The first output is used to process each message event that comes in, and the events can be bundled into one HTTP POST. The second output is the signal that comes as an HTTP response back to Facebook Messenger that the POST has been received. If this is not sent, Facebook Messenger will keep resending the same message.

        if (msg.payload.object && ‘page’ == msg.payload.object) {

        if (msg.payload.entry){

        var entry = msg.payload.entry;

        for (var i = 0; i < entry.length; i++) {

        var pageID = entry[i].id;

        var timeOfEvent = entry[i].time;

        var messaging = entry[i].messaging

        for (var j =0; j < messaging.length; j++) {

        if (messaging[j].message) {

        msg.messagingEvent = messaging[j];

        node.send([msg,null]);

        }

        }

        }

        }

        }

      2. Click Done.
      3. Double-click the second debug node (msg.payload). In the Output field, enter msg.messagingEvent, name it something like MessengingEventfrom Messenger and then click Done.

        1. Deploy your application.
          Your flow should now look like this:

          1. Go back to your Facebook page.

            1. Click Message and enter some text to test the application.

              1. Go back to the Node-RED flow editor.

                Look at the Debug tab. Your node-RED app is now listening to Facebook Messenger chats