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
Requirements for this tutorial
1. Python 2. Facebook Page 3. Flask
To install Flask, follow the instructions here.
Picture 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.
- Head on to developer.facebook.com
- 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.
- 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.
- head back to your heroku app settings and click on reveal config vars
- Set your PAGE_ACCESS_TOKEN and your VERIFY_TOKEN
- Everything is set and now your echo facebook bot should work.
Let us dive into the code.
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.
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.