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.
-
- 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
- Double-click the function node and set Outputs to 2. Name it
Look for Messages
. Then, click Done.
- In your Node-RED flow editor, drag and drop the following nodes onto the canvas:
-
- 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.
- 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 itMessenger Chat Listener
. Then, click Done.
- Wire the nodes together:
-
- 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]);
}
}
}
}
}
- Click Done.
- Double-click the second debug node (msg.payload). In the Output field, enter
msg.messagingEvent
, name it something likeMessengingEvent
from Messenger and then click Done.
- Double-click the function node, name it
-
- Deploy your application.
Your flow should now look like this:
- Deploy your application.
-
- Go back to your Facebook page.
-
- Click Message and enter some text to test the application.
-
- Go back to the Node-RED flow editor.
Look at the Debug tab. Your node-RED app is now listening to Facebook Messenger chats
- Go back to the Node-RED flow editor.