In this article we will setup facebook messenger customer chat plugin in a django site so that vistors can directly communicate with you.
Prequesites
A facebook page is required.
Django site should be https.
Setup Django Logic
Create a django app
python manage.py startapp chatbot
Create a file bot_logic.py
inside your app chatbot and paste the code below.
# bot_logic.py
LOGIC_RESPONSES = {
'account': [
"You can find your account information here"
],
'human': [
'A real person will get back to you shortly!'
]
}
Now run the following in a python shell:
import os, binascii
webhook_endpoint = (binascii.b2a_hex(os.urandom(30))).decode("utf-8")
VERIFY_TOKEN = (binascii.b2a_hex(os.urandom(25))).decode("utf-8")
print("webhook_endpoint",webhook_endpoint)
print("VERIFY_TOKEN",VERIFY_TOKEN)
Now, save the webhook_endpoint & VERIFYTOKEN printed string somewhere, we will use them soon.
Now, Open your app chatbot views.py and paste the following
# views.py
import json
import requests, random, re
from django.http import HttpResponse, JsonResponse
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from .bot_logic import LOGIC_RESPONSES
# change this to generated above
VERIFY_TOKEN = "asdac715abcfa28ace91507da2d28d907a2d2db3c7c6639b0"
"""
FB_ENDPOINT & PAGE_ACCESS_TOKEN
Come from the next step.
"""
FB_ENDPOINT = 'https://graph.facebook.com/v4.0/'
PAGE_ACCESS_TOKEN = "LwRraIBAB6wNqmxZC2K2bA55GURfPNWDEFSfQNSUiRa3I49oVgZCxcuun6zTrsw0s4ZCUhXQ33kPb7zN3NSmGZAoJYZBw0ZB762DDnAp3TD9eqVN3yUwcrpyOsBldoFWZAxCmELsSUza8teXsZAYr07VodZAlFWlMttmqWv1"
def parse_and_send_fb_message(fbid, recevied_message):
# Remove all punctuations, lower case the text and split it based on space
tokens = re.sub(r"[^a-zA-Z0-9\s]",' ',recevied_message).lower().split()
msg = None
for token in tokens:
if token in LOGIC_RESPONSES:
msg = random.choice(LOGIC_RESPONSES[token])
break
if msg is not None:
endpoint = "{FB_ENDPOINT}/me/messages?access_token={PAGE_ACCESS_TOKEN}"
response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":msg}})
status = requests.post(
endpoint,
headers={"Content-Type": "application/json"},
data=response_msg)
print(status.json())
return stats.json()
return None
class FacebookWebhookView(View):
@method_decorator(csrf_exempt) # required
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs) #python3.6+ syntax
'''
hub.mode
hub.verify_token
hub.challenge
Are all from facebook. We'll discuss soon.
'''
def get(self, request, *args, **kwargs):
hub_mode = request.GET.get('hub.mode')
hub_token = request.GET.get('hub.verify_token')
hub_challenge = request.GET.get('hub.challenge')
if hub_token != VERIFY_TOKEN:
return HttpResponse('Error, invalid token', status=403)
return HttpResponse(hub_challenge)
def post(self, request, *args, **kwargs):
incoming_message = json.loads(request.body.decode('utf-8'))
for entry in incoming_message['entry']:
for message in entry['messaging']:
if 'message' in message:
fb_user_id = message['sender']['id'] # sweet!
fb_user_txt = message['message'].get('text')
if fb_user_txt:
parse_and_send_fb_message(fb_user_id, fb_user_txt)
return HttpResponse("Success", status=200)
Now, open up your app urls.py and paste the following
# urls.py
from django.urls import re_path
from django.contrib import admin
from .views import (
FacebookWebhookView,
)
app_name ='chatbot'
urlpatterns = [
# replace <string_endpoint> with the one you created above
re_path(r'^<webhook_endpoint>/$', FacebookWebhookView.as_view(), name='webhook'),
]
After replacing your pattern would look something like this:
re_path(r'^d33300c2f7df8016b9f49f53179f9cae51/$', FacebookWebhookView.as_view(), name='webhook'),
Setup Facebook
Go to https://developers.facebook.com/apps/ (create account if needed)
Create a new app
Select to setup a Messenger App
Go to Token Generation for an API Testing token. Select a page or create a new one, generate the token, copy the token. Add this to the code above as PAGE_ACCESS_TOKEN.
In your app, go to Settings > Advanced and look for the numbers in Upgrade API Version. Mine say** v4.0**. That's where the FB_ENDPOINT came from.
Now is the time to bring your Django project, with the new webhook, live.
Setup django webooks
https://www.yourdomain.com/chatbot/<webhook_endpoint>/
should now exist for realIn your app, go to messenger > settings > webhooks > setup webhooks
Add in your entire url endpoint for the webhook such as
https://www.yourdomain.com/webhook/<webhook_endpoint>/
Add in the VERIFY_TOKEN created set above.
You can select all Subscription Fields or the ones you want. We chose to catch all.
Setup Facebook Page
Go to facebook page > settings > messenger platform > customer chat plugin
click on set up.
Follow instruction and it will ask your for your domain name, put your domain name.
At last it will give you a code snippet.
Now, copy the code snippet above and paste it in your django base template at the begining of body tag.
If it does work, add facebook sdk snippet too.