FB Messenger无法接收消息

时间:2016-05-10 19:53:18

标签: python facebook facebook-graph-api flask python-requests

我正在尝试使用新发布的信使平台api设置信使聊天机器人。我在Heroku上设置了一个Python Flask服务器,并且一直在调整这些指令,试图让我的页面接收我服务器发送的消息:https://developers.facebook.com/docs/messenger-platform/quickstart

到目前为止,我已经验证了一个回调网址,并且当我在FB上发布到我的页面时能够接收消息(即,当我在FB上发送链接到我的应用的页面时,我的heroku日志显示了POST请求正在收到)。但是,当我尝试从我的服务器向我的应用程序发送消息时,我收到以下JSON错误响应:

400: {"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"B3cni+LAmYU"}}

我正在使用请求库向页面发送请求。下面是我用来处理POST请求的代码:

import json
import os
import requests

from flask import Flask, request

app = Flask(__name__)

FB_MESSAGES_ENDPOINT = "https://graph.facebook.com/v2.6/me/messages"
FB_TOKEN = "EAADKWAcVj...AZDZD"

@app.route('/', methods=["POST"])
def chatbot_response():
    req_data = request.data

    data = json.loads(req_data)
    print "Data: ", data
    sender_id = data["entry"][0]["messaging"][0]["sender"]["id"]
    print "Sender id: ", sender_id
    send_back_to_fb = {
    "entry": [{"messaging": [{"recipient": {"id": str(sender_id)}}]}],
        "recipient": {
             "id": str(sender_id)},
        "message": "this is a test response message",
        "recipient": str(sender_id), "access_token": FB_TOKEN
    }

    params_input = {"access_token": FB_TOKEN, "recipient": sender_id}
    fb_response = requests.post(FB_MESSAGES_ENDPOINT,
                                params={"access_token": FB_TOKEN, "recipient":  {"id": str(sender_id)}, "json": "recipient": {"id": str(sender_id)}},
                                data=json.dumps(send_back_to_fb)) 



    print "Json of response: ", fb_response.json()

    # handle the response to the subrequest you made
    if not fb_response.ok:
        # log some useful info for yourself, for debugging
        print 'jeepers. %s: %s' % (fb_response.status_code, fb_response.text)


    return "OK", 200


if __name__ == '__main__':
    app.run(host="0.0.0.0")

我已尝试过无数种不同类型的“收件人”键/值编码。将元素转换为json但FB图形服务似乎无法理解它们。如何编码我的请求,以便FB知道'收件人' param是?

谢谢!

编辑:

事实证明我必须在POST请求的标头中手动设置编码类型。添加以下行使我可以向FB发送可解释的文本响应:

headers = {'content-type':  'application/json'}

2 个答案:

答案 0 :(得分:2)

你可以试试这些,两者都应该有用

headers = {'Content-type': 'application/json'}
response = requests.post(url, data=json.dumps(send_back_to_fb), headers=headers)

OR

response = requests.post(url, json=send_back_to_fb)

答案 1 :(得分:0)

使用facebook messenger平台的python库怎么样?

https://github.com/conbus/fbmq

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, "HI!!!")