Last active
January 7, 2019 04:11
-
-
Save sshadmand/304a77371c9e207a5fa42a6b874017d5 to your computer and use it in GitHub Desktop.
FB Messenger Webhook Ported to Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
from django.views.decorators.csrf import csrf_exempt | |
FB_MESSENGER_ACCESS_TOKEN = "[TOKEN]" | |
def respond_FB(sender_id, text): | |
json_data = { | |
"recipient": {"id": sender_id}, | |
"message": {"text": text + " to you!"} | |
} | |
params = { | |
"access_token": FB_MESSENGER_ACCESS_TOKEN | |
} | |
r = requests.post('https://graph.facebook.com/v2.6/me/messages', json=json_data, params=params) | |
print(r, r.status_code, r.text) | |
@csrf_exempt | |
def fb_webhook(request): | |
if request.method == "GET": | |
if (request.GET.get('hub.verify_token') == 'this_is_a_verify_token_created_by_sean'): | |
return HttpResponse(request.GET.get('hub.challenge')) | |
return HttpResponse('Error, wrong validation token') | |
if request.method == "POST": | |
body = request.body | |
print("BODY", body) | |
messaging_events = json.loads(body.decode("utf-8")) | |
print("JSON BODY", body) | |
sender_id = messaging_events["entry"][0]["messaging"][0]["sender"]["id"] | |
message = messaging_events["entry"][0]["messaging"][0]["message"]["text"] | |
respond_FB(sender_id, message) | |
return HttpResponse('Received.') |
Hey, I'm sorry for the following noob question. How would I set up the url to access this file? What is the webhook URL you would provide at the Facebook Messenger Dashboard to connect this endpoint? Please bear with my ignorance, I don't have any experience with web based python applications.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @sshadmand! Thanks for the port. What would be the equivalent of
requests.post('https://graph.facebook.com/v2.6/me/messages', json=json_data, params=params)
if I were to useurllib
/urllib2
?