npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

messenger-botkit-starter

v0.1.3

Published

A Facebook Messenger Bot Starter with Botkit

Downloads

4

Readme

Create, Develop and Deploy your FB Messenger chatbot

Chatbot Architecture

Chatbots are programs that live in messaging applications. I believe, when talking about bots, we invoke three main parts :

  • Messaging app or channel : Where the bot lives which is the frontend
  • Bot Backend : Bot application which can be caded from scratch, coded using a framework or built with a chatbot platform
  • Server were bot backend is deployed to : local or remote server

This illustration shows how these parts are connected :

Facebook uses Webhooks. Webhook endpoints are URLs defined by users to which Facebook sends events. A single event may be sent to many webhook endpoints. Webhooks refers to the overall concept of sending notifications to webhook endpoints.

Code your chatbot with : Botkit

Bot Framework : Botkit

Botkit is designed to ease the process of designing and running useful, creative bots that live inside messaging platforms. Bots are applications that can send and receive messages, and in many cases, appear alongside their human counterparts as users.

Some bots talk like people, others silently work in the background, while others present interfaces much like modern mobile applications. Botkit gives developers the necessary tools for building bots of any kind! It provides an easy-to-understand interface for sending and receiving messages so that developers can focus on creating novel applications and experiences instead of dealing with API endpoints. - Botkit

About Botkit

Botkit is a product of Howdy. For support, check out the Developer Community and find our team in the #Botkit channel.

Prerequisites

Before getting started with Botkit, dvelopers should have a basic understandng of Javascript and Node.js. Node.js is a Javascript-based framework/plaform built on Google Chrome's Javascript V8 Engine. Start preparing your dev environment by dwonloading and installing Node.js from the official web site.

If you're using Linux and have sudo privelges :

for Node.js v6

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -

Then install the Node.js package.

sudo apt-get install -y nodejs

P.S.: curl package must be installed on server for these code lines.

Make sure everything is well done :

node --version

We'll also need Node Package Manager : NPM

sudo apt-get install npm

Verify with :

npm --version

Get Started with Botkit

Botkit is available in many messagging applications. In this article, we will be interested in Facebook Messenger. Clone Botkit :

    git clone https://github.com/howdyai/botkit.git
    cd botkit
    npm install

or directly download the project.

If you want to start directly with the bot I made for this article, clone the project from my Github

    git clone https://github.com/Raniazy/messenger-bot.git
    cd messenger-bot
    npm install

Now that you have set up your dev environment and installed required libraries and packages. Let's take a look at the project's entry point : facebook_bot.js

This file is refactored and written in News Papers Style to ease comprehension to developers. First thing is creating the bot using Botkit for Facebook :

    let controller = createBotkitController();
    
    function createBotkitController() {
       return Botkit.facebookbot({
            debug: true,
            receive_via_postback: true,
            verify_token: process.env.verify_token,
            access_token: process.env.page_token,
        });
    }

access_token and verify_token are key parameters to connect your bot application to Facebook Messenger. I'll be back to them later.

Botkit is based on an express server :

    let expressWebServer = require(__dirname + '/components/express_webserver.js');
    expressWebServer(controller);

When botkit receives a message, controller instance has many listeners that are constantly hearing incomming messages. For example, when a user sends "Hello" to the bot on Messenger, controller uses the function hears to receive the message and response with a proper answer :

    controller.hears(['^hello', '^hi'], 'message_received, facebook_postback', function (bot, message) {
        bot.reply(message, "Hi there Human. I'm a Gif Bot");
    });

You will notice that I have changed the code comparing to the official repository of Botkit. I've added a new directory and named it : bot_skills. It should contain js files with hears tasks. This refactoring is benificial for understanding the logic of bots. Botkit has plenty functionnalities which encapsulate most of calls to Messenger API. Don't hesitate looking at the official repository.

Now that you have you bot code set up. It is ready to be deployed.

Deploy your bot

In this section, I will show you how to deploy your bot to three servers localy and to remote. Please note that you only need one of these three possibilities to connect your chatbot to Facebook.

Deploy your bot to a local server and publish it using Ngrok

Before deployment, your should set your environment variables we talked about earlier.

access_token : Is the page token given by facebook verify_token : is a verification token that only your bot and your Facebook application know.

    export page_token=PAGE_ACCESS_TOKEN
    verify_token=MY_VERIFY_TOKEN

Run your bot localy with :

node facebook_bot.js

Botkit is running on port:3000. If you access to http://localhost:3000/ you will get this page :


Because it calls : ../public/index.html http://localhost:3000/facebook/receive : should be your Facebook Webhook URL. But Facebook only accepts public URLs.

To expose our localhost, we will use Ngrok to create a secure tunnel.

  • Download Ngrok from : https://ngrok.com/download

    unzip /path/to/ngrok.zip
  • run ngrok to create an HTTP tunnel to port 3000, you can also define your sub domain. Otherwise, Ngrok attributes a random hexadecimal names to tunnels :
  ./ngrok http -subdomain=messenger-bot 3000


Keep this URL, we will need it in the next section to configure Facebook application.

Deploy your bot to Heroku ❤

Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.

Heroku runs your apps inside dynos — smart containers on a reliable, fully managed runtime environment. Developers deploy their code written in Node, Ruby, Java, PHP, Python, Go, Scala, or Clojure to a build system which produces an app that's ready for execution. The system and language stacks are monitored, patched, and upgraded, so it's always ready and up-to-date. The runtime keeps apps running without any manual intervention.

These are steps you need for your deployment :

  • Create a new app

  • Go to Settings and define your env variables (just like in local)

  • Go to Deploy : Heroku has three deployment methods. I will use Github because I want to directly connect my repos to the Heoku app. With this option, I can keep my versionning control in Github and deploy at anytime, any branch, with one button.

Congrats, you've just deployed your bot to Heroku. Click on open app :

Again, keep that URL. You will need it.

Deploy your bot to AWS Elastic Beanstalk

I will base this section on @mlabouardy's blog article on : Deploying Node.js Application on AWS Elastic Beanstalk.

AWS Elastic Beanstalk is an easy to use service for deploying and sizing web applications and services developed with Java, .NET, PHP, Node.js, Python, Ruby, Go and Docker on familiar servers like Apache, Nginx, Passenger and IIS.

All you need to do is load your code, and Elastic Beanstalk automatically performs the deployment steps of capacity sizing, load balancing, automatic sizing, and application status monitoring. By doing so, you maintain total control of the AWS resources that power your application and can access the underlying resources at any time. For more, visit : https://aws.amazon.com/fr/elasticbeanstalk/

These are the steps you need to go through to deploy your bot :

  • Use AWS Console to create your Elastic Beanstalk Instance :

Visit : AWS Management Console. Login with an account, username and password. You will see a list of AWS Services.

Choose Elastic Beanstalk :


  • Create your Beanstalk application :

You will be redirected to the welcome page ith a briefing about Elastic Beanstalk.

Click on "Create new application" on the right.

Give your application a significant name and a description. Then hit "Create".

Your new Elastic Beanstalk application is fresh but empty. We need to set up its environment.

  • Create your environment

To do so, click on "Create one now". I mean, NOW, It's now or never.

Since we are trying to deploy a web application, we will go for : "Web server environment" then hit "Create" :


You'll have to fill a pretty cool form. I'll help you with that : In Platform, choose : Node.js as your preconfigured platform 😇 . Then just click on "Create environment".


A couple minutes are need for Elastic Beanstalk to create instances and launch your app. Wait please.


Finally, your App Health is OK. Everything is coul, until now :< .


Try to call the given URL in your browser. If You see the next figure, then, Congrats mate, you've just deployed a Node.js application in Elastic Beanstalk !


But wait. You need to deploy your app not this app --' .

  • Deploy your bot

I will deploy the current application : Messenger bot for Gifs, but you can use your very own, it's totally fine.

You should have a zip file of your app. Just download it.


Then, go to your EB app, and click on "upload and Deploy". Select the zip file and name the version of your app.


Wait again for the app to be uploaded and deployed to EB. If your app health is OK, still. Call the URL in your browser. If your using the app I mentionned, then you should see this :


Otherwise, you'll have your own app running.

You're done, son !

You've just deployed your Node.js app in EB.

If you like EB, check this.

PS : keep Ze URL.

Create a Facebook Application for Messenger

In Facebook Messenger, the identity of a chatbot is a Page. Users can intercat with your bot via this Facebook Page. But still, behind this Page, there should be a Facebook App to which your Page will subscribed.

Setup your Facebook Page

Create a Facebook Page (if you don't have one and would like to use it). I wil choose : App Page as a category.


Setup your Facebook App

Go to : Facebook Devolopers and Create a New App ID :


Add a Messenger Product :


Facebook uses Webhooks to notify your Bot App. Many events are available in FB Messenger :

  • messages : Subscribes to Message Received events
  • message_deliveries : Subscribes to Message Delivered events
  • message_reads : Subscribes to Message Read events
  • message_echoes : Subscribes to Message Echo events
  • messaging_postbacks : Subscribes to Postback Received events
  • messaging_optins : Subscribes to Plugin Opt-in events
  • messaging_referrals : Subscribes to Referral events
  • messaging_checkout_updates (BETA) : Subscribes to Checkout Update events
  • messaging_payments (BETA) : Subscribes to Payment events
  • messaging_account_linking : Subscribes to Account Linking events
  • messaging_policy_enforcement : Subscribes to Policy Enforcement events

Webhook configuration

Remember the URLs I asked you to keep. You now will need them. Click on "Setup webhooks".

Webhook URL is Ze URL/facebook/receive (https) Verify Token is a string that Facebook uses to verify that this token matches the one you have in your Bot App.


Link your Facebook App to your Page

All you need to do now is subsribe this application to your FB Page.


Test your bot

Congratulations 🎉 🙌 👌 !

gif -----------

You've just created a Facebook chatbot.

Now, visit your page, and talk to your bot.

---- gif

Tip : Messenger Codes

Messenger Codes are pictos that can be scanned to instantly link the user to your bot, no typing needed. ~Facebook Messenger Platform

They're great for sticking on fliers, ads, or anywhere in the real world where you want people to try your bot.

Use the API to get your code :

Calling this API requires an access token for the page :

curl -X POST -H "Content-Type: application/json" -d '{
  "type": "standard",
  "image_size": 1000
}' "https://graph.facebook.com/v2.6/me/messenger_codes?access_token=<ACCESS_TOKEN>" 

Response :

"uri": "<YOUR_CODE_URL_HERE>"

To scan someone's code:

  1. From Home, tap your profile picture in the top left corner
  2. Tap your picture at the top of the page
  3. Tap My Code to let someone scan your code, or tap Scan Code to scan someone else's

You will be directly redirect to start the conversation.

Here's my page's code. Try it 😊 .