Facebook now has the Messenger Platform which permits us to manufacture bots which can acknowledge messages from clients and react to them.
Facebook now has the Messenger Platform which permits us to manufacture bots which can acknowledge messages from clients and react to them. In this instructional exercise, we should perceive how we can assemble a bot and add it to one of our pages so that the clients can interface with the bot by sending messages to the page.
To begin, we have three necessities to satisfy:
I am accepting you as of now have a Facebook Page. In the event that you don’t, simply ahead and make one. It’s extremely basic.
.
Next, snap the “Webhooks” area.
Install Flask from PyPi using pip:
pip install Flask
Facebook will send a GET solicitation to the callback URL we give. The solicitation will contain a custom mystery we can include (while setting up the webhook) and a test code from Facebook. They anticipate that us will yield the test code to check ourselves. To do as such, we compose a speedy GET handler utilizing Flask.
## Filename: server.pyfrom flask import Flask, request
app = Flask(name)
@app.route(‘/’, methods=[‘GET’])
def handle_verification():
return request.args[‘hub.challenge’]if name == ‘main’:
app.run(debug=True)
We run the nearby server utilizing python server.py. The application will dispatch at port 5000 of course. Next we utilize ngrok to open the server to the web. ngrok is an awesome device and you ought to truly try it out for running and troubleshooting webhooks/callback urls on your nearby machine.
ngrok http 5000
With that order, we will get a location like https://ac433506.ngrok.io. Duplicate that url and glue it in the Webhook setup popup. Checkmark the occasions we’re occupied with. I check every one of them. At that point we include a mystery, which our code couldn’t care less about much. So simply include anything you like. The popup now seems as though this:
Click “Verify and Save”. If the verification succeeds, the popup will close and you will be back to the previous screen.
Select a Page again and click “Subscribe”. Presently our application ought to be added to the page we chose. If it’s not too much trouble note, on the off chance that we haven’t created an entrance token for that page in the prior stride, the membership will fall flat. So ensure we have an entrance token produced for that page.
Presently every time somebody makes an impression on the “Masnun” page, Facebook will make a POST solicitation to our callback url. So we have to compose a POST handler for that url. We additionally require react back to the client utilizing the Graph API. For that we would need to utilize the marvelous requests module.
pip install requests
Here’s the code for tolerating approaching messages and sending them an answer:
from flask import Flask, request
import requestsapp = Flask(name)
ACCESS_TOKEN = “EAAP9MMaGh1cBAHS7jZCnuQgm2GWx5grLraIElFlWlIw2r3Afb34m2c2rP0xdkkkKEeiBOykGINAP0tScwmL5NNBJQN9ayPCuq13syvWocmbYZA7BXL86FsZCyZBxTmkgYYp8MDulLc1Tx70FGdU5ebQZAJV28nMkZD”
def reply(user_id, msg):
data = {
“recipient”: {“id”: user_id},
“message”: {“text”: msg}
}
resp = requests.post(“https://graph.facebook.com/v2.6/me/messages?access_token=” + ACCESS_TOKEN, json=data)
print(resp.content)@app.route(‘/’, methods=[‘POST’])
def handle_incoming_messages():
data = request.json
sender = data[‘entry’][0][‘messaging’][0][‘sender’][‘id’]
message = data[‘entry’][0][‘messaging’][0][‘message’][‘text’]
reply(sender, message[::-1])return "ok"
if name == ‘main’:
app.run(debug=True)
The code here acknowledges a message, recovers the client id and the message content. It switches the message and sends back to the client. For this we utilize the ACCESS_TOKEN we produced before hand. The approaching solicitation must be reacted with a status code 200 to recognize the message. Generally Facebook will attempt the message a couple of more times and after that cripple the webhook. So sending a http status code 200 is essential. We simply yield “alright” to do as such.
You can now make an impression on your page and check whether it reacts accurately. Look at Flask’s and ngrok’s logs to troubleshoot any issues you may confront.
You can download the specimen code from here: https://github.com/masnun/fb-bot
#python #facebook