Just Chris


Easier Facebook bots using pipelines

I recently experimented with Fb bots, which was actually quite fun.

They have made the effort of creating bots very accessible to the average developer, with a somewhat straight-forward process of publishing.

In the simplest terms, what you need to know is:

You need a server that processes the messages that people type into FB Messenger

Then you just send those messages back to Fb that sends it to the user.

In HTTP terms, every time a user sends a message, Fb POSTs that to your server, then you POST the response back to Fb, who forwards it to the user.

This request/response pattern is very well handled by pipelines — famously used by Express, using app.use(function). Let’s compose a bot that will simplify our message processing with a .use() function.

Here, we’ll use a module fbmbot, that will hide all the express server details, and expose functions to process messages from Fb. It gives you these functions to use, and hides the Express server and HTTP communication.

var bot = require('fbmbot')();

bot.onmessagetext = (user, txt, body) => {
bot.sendText(user.id, 'Hi') // (fbid, txt, [wait seconds, metadata]
bot.onpostback = (user, postback) => {

bot.setupGetStartedButton() one-time
bot.sendQuickReply(user.id, [])
bot.queryUser(user.id, callback)
bot.sendMessage(user.id, {})
bot.users // [users since bot was restarted]
bot.app // express app

I’ll use the excellent Gomix @gomixme playground to make the bot.
We can simply use this module to handle requests, and our bot is created like this:

Fb has the concept of “postback” which is when someone clicks a button. This will run when a user starts a new conversation.

onmessage text will process incoming messages after that initial message.

Now, let’s introduce a processing pipeline, ala Express .use()

Here, we create our own “user manager”, which will query a user information by their id, and save it in users={}. We may save this off somewhere if it needs to be saved on server restarts. Instant user manager!

Keep in mind that these process in reverse order. The first bot.use() checks and sees if we have user info. Then it sends the response back with the user name.

These piplelines allow a composable way of making your bots.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

More by Just Chris

Topics of interest

More Related Stories