What is a chatbot?

A chatbot is an automated or semi-automated service, powered by a set of rules and sometimes artificial intelligence, that you can interact with a chat interface. This chat interface can be anywhere, It can be on social media platforms like facebook messenger, telegram, slack or it can be your own chat interface. It can employ technologies like natural language processing, natural language understanding, machine learning to provide a better conversational interface and user experience.

How fb messenger bot works?

how-chatbot-works When a user sends a message to a Facebook page that has bot feature setup, it is sent to the chatbot server by using webhooks. The chatbot server receives the message and may do operations like natural language processing, access information from the database or get information from third-party services and constructs the response and sends reply back to the facebook messenger API.

Let’s build our first bot, an echo bot. Echo bot is like the hello world program for chatbots. It basically confirms that the rest endpoints are functioning properly and the ability to reply back to the chat server.

To get started, we need a facebook application setup and a chatbot application running as a web service. Let’s create the facebook application first.

Create Facebook application

You will need,

  • a Facebook account
  • a Facebook page with admin privileges

If you do not have a facebook page create a page here https://www.facebook.com/pages/create

  • Log into the Facebook Developer Console
  • Click on My Apps in the upper right hand corner.
  • Click on Add a New App and enter a name and contact email address

create fb app

  • Click Create App ID.

On the next page, click on the Setup button under messenger section. Under the Token Generation section, choose the Facebook page you want to add your chatbot to. This will generate a Page Access Token. Keep this token handy, as you’ll need to enter it in the next step.

Create Flask application

We will be using flask web framework and fbmessenger, a python wrapper for messenger platform api. we will be using zappa for deployment to AWS Lambda.

If you’re not sure of the zappa deployment for flask application, follow this tutorial on deploying serverless flask application to aws lambda

Put the page access token you have generated in the facebook developer console to the environment variables as FB_PAGE_TOKEN and then FB_VERIFY_TOKEN, this is your own secret access code, which the facebook messenger use to verify your application.


    "dev": {
        "app_function": "main.app",
        "aws_region": "<aws_region>",
        "profile_name": "<aws_profile>", // profile config at ~/.aws/credentials
        "project_name": "serverless-bot",
        "runtime": "python3.6",
        "s3_bucket": "serverless-bot"
        "environment_variables": {
            "FB_PAGE_TOKEN": "<YOUR FB PAGE TOKEN>",


import os
from flask import Flask, request
from fbmessenger import BaseMessenger

class Messenger(BaseMessenger):
    def __init__(self, page_access_token):
        self.page_access_token = page_access_token
        super(Messenger, self).__init__(self.page_access_token)

    def message(self, message):
        res = self.send({'text': str(message['message']['text'])})
        app.logger.debug('Response: {}'.format(res))

    def delivery(self, message):

    def read(self, message):

    def account_linking(self, message):

    def postback(self, message):

    def optin(self, message):

app = Flask(__name__)
app.debug = True
messenger = Messenger(os.environ.get('FB_PAGE_TOKEN'))

@app.route('/webhook', methods=['GET', 'POST'])
def webhook():
    if request.method == 'GET':
        if request.args.get('hub.verify_token') == os.environ.get('FB_VERIFY_TOKEN'):
            return request.args.get('hub.challenge')
        raise ValueError('FB_VERIFY_TOKEN does not match.')
    elif request.method == 'POST':
    return ''

if __name__ == '__main__':



Deploy to AWS Lambda

zappa deploy dev

Deploy the application to aws lambda, your will get the web url for your lambda function. Keep this url handy, you will need it the next step.

Setup Webhook on Facebook Developer Console

Now goto your facebook developer Console and choose your application, Click on Setup Webhook under Webhooks section Click the Setup Webhooks button under the Webhooks section and enter the following information:

  • Callback URL - Your lambda function URL followed by /webhook Ex: https://xxxxxxxxxxxxxxx.amazonaws.com/dev/webhook
  • Verify Token - Your FB VERIFY TOKEN
  • Check the messages and messaging_postbacks options under Subscription Fields
  • Click the Verify and Save button.

Next, In the same section, Choose your page and click “subscribe”. This will subscribe to webhook notifications to the lambda function.

Submit your application for review

By default your chatbot is available only to you and developers, testers who are part of the facebook application can access it. In order to make your chatbot available for everyone on the facebook, you’ll need to make your app public and submit your application for review.

Basically your application’s “pages_messaging”( Send/Receive API ) permission must be approved by facebook.

Click on “Add to Submission” for “pages_messaging”

Then under “Current Submission” section, click on add details and provide details about how chatbot will work so that facebook dev team will test and approve it. You must complete all the items mentioned under this tab.

Thats all for now, In the next article we will be developing a weather bot. stay tuned. subscribe to our pages to get alerts on next articles.