Skip to main content

Deploy your Facebook Messenger Bot with Python

A step-by-step guide to easily deploying a Facebook Messenger chatbot with Python, using Flask, requests and ngrok.
Feb 2018  · 7 min read

When done right, interacting with a computer through human language is incredibly powerful and also quite fun. Messaging and Voice-Controlled devices are the next big platforms, and conversational computing has a big role to play in creating engaging augmented and virtual reality experiences. There are a number of unique challenges to building these kinds of programs, such as: how can I make my chatbot available to the outside world?

In this tutorial, you'll go through the steps required to deploy a chatbot on Facebook Messenger, which has over 1 Billion active users. You can reach an enormous audience with just a few lines of code.

There are 3 main steps to get this done. You need to:

  • create a server which listens to messages from Facebook (using flask)
  • define a function for sending messages back to users (using requests)
  • forward a https connection to your local machine (using ngrok)

If you want to know more on how to turn human language into machine instructions, check out the Building Chatbots in Python DataCamp course.

Note that what you won't cover in this post is how to your bot can understand what people are saying and respond appropriately. To learn more about that you should have a look at Rasa NLU, Rasa Core, and the DataCamp course that was just mentioned.

Python chatbot

Wrap your Chatbot in a http Server

The first step is to create a http server which listens to messages sent by Facebook, gets a response to that message, and eventually sends the response back to the user on Facebook. We will use flask to create this server. The basic idea is the following:

  • Create a flask app that listens for messages sent to localhost:5000/webhook. When messages are sent on Facebook they will arrive as http requests to this URL.
  • The listen() function handles these http requests and checks that they contain a valid Facebook message
  • If the message is valid, the get_bot_response() function is called and the response is sent back to Facebook Messenger

In addition, you will create a function called verify_webhook() that handles the initial authentication between Facebook and your app.

The final script looks like this (save it under

from flask import Flask, request

app = Flask(__name__)

VERIFY_TOKEN = ''# <paste your verify token here>
PAGE_ACCESS_TOKEN = ''# paste your page access token here>"

def get_bot_response(message):
    """This is just a dummy function, returning a variation of what
    the user said. Replace this function with one connected to chatbot."""
    return "This is a dummy response to '{}'".format(message)

def verify_webhook(req):
    if req.args.get("hub.verify_token") == VERIFY_TOKEN:
        return req.args.get("hub.challenge")
        return "incorrect"

def respond(sender, message):
    """Formulate a response to the user and
    pass it on to a function that sends it."""
    response = get_bot_response(message)
    send_message(sender, response)

def is_user_message(message):
    """Check if the message is a message from the user"""
    return (message.get('message') and
            message['message'].get('text') and
            not message['message'].get("is_echo"))

def listen():
    """This is the main function flask uses to 
    listen at the `/webhook` endpoint"""
    if request.method == 'GET':
        return verify_webhook(request)

    if request.method == 'POST':
        payload = request.json
        event = payload['entry'][0]['messaging']
        for x in event:
            if is_user_message(x):
                text = x['message']['text']
                sender_id = x['sender']['id']
                respond(sender_id, text)

        return "ok"

In the above script the VERIFY_TOKEN and PAGE_ACCESS_TOKEN variables aren't defined yet - so you will have to set these. The VERIFY_TOKEN can be any string, it is used as a kind of password to let facebook know that this server wants to receive messages. It is a good idea to use a long random string. You can do this quickly by running openssl rand -base64 32 in your terminal.

Don't worry about the PAGE_ACCESS_TOKEN just yet - you will see how to get it below!

Send Messages Back to Users

Next, you will write a function that that sends a response back to Facebook Messenger using a python library called requests. In particular, you use the post() method, which creates a HTTP POST request. A POST request is the typical way to send information to a server.

Your function should look like this:

import requests

def send_message(recipient_id, text):
    """Send a response to Facebook"""
    payload = {
        'message': {
            'text': text
        'recipient': {
            'id': recipient_id
        'notification_type': 'regular'

    auth = {
        'access_token': PAGE_ACCESS_TOKEN

    response =

    return response.json()

Expose a https Endpoint and Connect a Facebook Page

The url localhost:5000 only works for requests created on the same computer as the running server. So you need to let facebook know how to reach your flask server. To do this, first install ngrok.

Go to this page and install the version for your operating system. If you're on Mac and have homebrew, the quickest way to install ngrok is with brew cask install ngrok.

Start the ngrok server in your terminal with ngrok http 5000. This will set up a https endpoint to get forwarded to your machine on port 5000, for example

Note that if you quit ngrok and restart, this URL will change.

Create a Facebook App and Page

The next step is to create an app and a page on Facebook. There is good documentation available from Facebook but you'll walk through the main steps here.

To create the app go here and

  • click on My Apps -> Add a New App and enter a name
  • you will be redirected to the dashboard for the app
  • under Products, find Add a Product and click on Messenger -> Set Up

To create the page, you have to:

  • go the settings for Messenger, scroll down to Token Generation and click on the link to create a new page for your app

Once you have created a page, go back to the Token Generation settings and select this page from the drop-down menu. Copy the Page Access Token into the placeholder for PAGE_ACCESS_TOKEN in above.

Start your bot server

Now that you have everything set up, it's time to start your chatbot server! In a separate terminal tab, run flask run

Set up the webhook

Finally, you need to register your webhook on the Facebook developers page.

  • Go to the Messenger tab in Products again and scroll down to Webhooks, click on Setup Webhooks
  • Under the Callback URL enter in your ngrok URL, for example, It is important that your flask app is running at this point, because the verify_token() will be called on the next step
  • In the Verify Token field, you put the value you specified in your file
  • In Subscription Fields make sure messages and messaging_postbacks are ticked Click Verify and Save to perform the authentication

Important: Go back to Products -> Messenger, and under Select a page to subscribe your webhook to the page events select your page and click Subscribe.

You're done!

Your bot is now ready to send and receive messages via Facebook Messenger. Right now, your get_bot_response() function is still pretty simple, and doesn't feel like a real chatbot yet! To learn all about building chatbots, check out the Building Chatbots in Python DataCamp course and Building a Chatbot using Chatterbot in Python tutorial, as well as the Rasa NLU and Rasa Core python libraries. 

Introduction to Python

4 hours
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course

Intermediate Python

4 hours
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

Python Data Science Toolbox (Part 2)

4 hours
Continue to build your modern Data Science skills by learning about iterators and list comprehensions.
See all coursesRight Arrow
Data Science Concept Vector Image

How to Become a Data Scientist in 8 Steps

Find out everything you need to know about becoming a data scientist, and find out whether it’s the right career for you!
Jose Jorge Rodriguez Salgado's photo

Jose Jorge Rodriguez Salgado

12 min

DC Data in Soccer Infographic.png

How Data Science is Changing Soccer

With the Fifa 2022 World Cup upon us, learn about the most widely used data science use-cases in soccer.
Richie Cotton's photo

Richie Cotton

The 23 Top Python Interview Questions & Answers

Essential Python interview questions with examples for job seekers, final-year students, and data professionals.
Abid Ali Awan's photo

Abid Ali Awan

22 min

Plotly Express Cheat Sheet

Plotly is one of the most widely used data visualization packages in Python. Learn more about it in this cheat sheet.
DataCamp Team's photo

DataCamp Team

0 min

Getting started with Python cheat sheet

Python is the most popular programming language in data science. Use this cheat sheet to jumpstart your Python learning journey.
DataCamp Team's photo

DataCamp Team

8 min

Python pandas tutorial: The ultimate guide for beginners

Are you ready to begin your pandas journey? Here’s a step-by-step guide on how to get started. [Updated November 2022]
Vidhi Chugh's photo

Vidhi Chugh

15 min

See MoreSee More