Is there a Python port for the new FB Messenger webhook?

时间:2016-04-15 15:00:46

标签: facebook webhooks facebook-messenger

Couldn't find anything in python for FB Messenger webhook quickstart page. (https://developers.facebook.com/docs/messenger-platform/quickstart)

3 个答案:

答案 0 :(得分:3)

I went ahead and ported it myself. Figured I should share the riches. This snippet response to every message with " to you!":

import json
import requests
from django.views.decorators.csrf import csrf_exempt

FB_MESSENGER_ACCESS_TOKEN = "<Your Access 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)

#this allows the requst to come in without requiring CSRF token
@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.')

And here is the FB Messenger Chatbot port on Gist

答案 1 :(得分:1)

我为Facebook Messenger平台编写了一个Python客户端:messengerbot

答案 2 :(得分:1)

这是使用fbmq library的python示例,对我有用:

echo示例:

from flask import Flask, request
from fbmq import Page

page = fbmq.Page(PAGE_ACCESS_TOKEN)

@app.route('/webhook', methods=['POST'])
def webhook():
  page.handle_webhook(request.get_data(as_text=True))
  return "ok"

@page.handle_message
def message_handler(event):
  page.send(event.sender_id, event.message_text)