Making a Facebook Messenger Bot Using Flask

For this tutorial we will be building a messenger bot using Python, more specifically the Flask framework.
This is the third post in our bot series,
The previous one’s being

Chatboot Facebook

Requirements for this tutorial

1. Python
2. Facebook Page
3. Flask

To install Flask, follow the instructions here.

Creating Webhooks

WebhooksPicture Credits: Mailchimp

A webhook is an URL to which a ping is sent if any activity occurs in the host server.
In our case, when your facebook page recieves a message, Facebook sends a notification to your server URL which you provided. It’s kinda like guests arriving at your house. You don’t open the door, unless someone rings the doorbell.
Here Guests refer to the messages, and the doorbell to the callback URL which you have provided to facebook.
To create your own callback URL you are free to use ngrock, in this tutorrial we will be using heroku.

TDLR;
1. Create a heroku account if not done already.
2. Create a new app on heroku
3. Go to my github link and fork this repository. reach2ashish/fb-messenger-bot
4. Once forked you can straight away deploy it to heroku-
5. Go to settings enter: PAGE_ACCESS_TOKEN and VERIFY_TOKEN
6. Go to your facebook app page and create a webhook with the settings you've selected.

Let us do this step by step

  • Fork this github repository
  • Go to heroku -> deploy -> and connect your github account
  • Go down and deploy the main branch.
  1. Head on to developer.facebook.com
  2. Create a new app
  • Select messenger from the list
  • Select the page on which you wish to run your app.
  • Copy and keep te page access token.You will need it in a while.
  1. Click on set up webhooks
  • If the verify and save process is not working at the moment, do not worry, we’ll fix that in a bit.
  1. head back to your heroku app settings and click on reveal config vars
  2. Set your PAGE_ACCESS_TOKEN and your VERIFY_TOKEN
  • Everything is set and now your echo facebook bot should work.

Code

Let us dive into the code.

Verify:

This function basically tells facebook that you are the authentic sender for the the message. The verify token which you set basically acts as a password for your application and your facebook page.

Recieve Message:

When your facebook page recieves a message, the following code is used to extract the vital information from the message.

Sending a message:

Using the information we extracted earlier, we use the following function to send a message back to the user, using his facebook ID.

And that’s all, implement your own functions and message handlers to this code.
Happy coding!

Leave a reply:

Your email address will not be published.

Site Footer

Sliding Sidebar

About Me

About Me

Hey, I am Thomas Ashish Cherian. What I cannot create, I do not understand.

Social Profiles