與瓶

2016-05-05 26 views
1

我試圖讓FB信使API使用Python的瓶,調整下面的說明工作的Facebook Messenger的:https://developers.facebook.com/docs/messenger-platform/quickstart與瓶

到目前爲止,事情已經做得較好。我驗證了我的回調,並且能夠接收我在我的頁面上使用Messenger發送的消息,就像在我的heroku服務器中的日誌中指出我的服務器正在接收相應的數據包。現在,我正在努力向客戶端發送迴應消息,以傳遞我的應用程序。特別是,我不知道如何從教程瓶執行以下部分:

var token = "<page_access_token>"; 

function sendTextMessage(sender, text) { 
    messageData = { 
    text:text 
} 
request({ 
    url: 'https://graph.facebook.com/v2.6/me/messages', 
    qs: {access_token:token}, 
    method: 'POST', 
    json: { 
    recipient: {id:sender}, 
    message: messageData, 
    } 
}, function(error, response, body) { 
    if (error) { 
    console.log('Error sending message: ', error); 
    } else if (response.body.error) { 
    console.log('Error: ', response.body.error); 
    } 
}); 
} 

到目前爲止,我在我的服務器端瓶模塊該位:

@app.route('/', methods=["GET", "POST"]) 
def chatbot_response(): 
    data = json.loads(req_data) 
    sender_id = data["entry"][0]["messaging"][0]["sender"]["id"] 
    url = "https://graph.facebook.com/v2.6/me/messages" 
    qs_value = {"access_token": TOKEN_OMITTED} 
    json_response = {"recipient": {"id": sender_id}, "message": "this is a test response message"} 
    response = ("my response text", 200, {"url": url, "qs": qs_value, "method": "POST", "json": json_response}) 
    return response 

然而,運行這個,我發現雖然我可以處理有人發送我的頁面,但它不會發送回應(即沒有在信使聊天框中顯示)。我是Flask的新手,所以任何幫助都可以通過與Flask上面的Javascript代碼相同的方式得到很大的讚賞。

謝謝!

回答

-1

在Flask中進行響應時,必須小心。簡單地做一個return語句不會返回任何東西給請求者。您可能需要查看jsonify()。它將採用Python字典並將其作爲JSON對象返回給瀏覽器。

from flask import jsonify 
return jsonify({"url": url, "qs": qs_value, "method": "POST", "json": json_response}) 

如果你想在迴應更多的控制,如設置代碼,看看make_response()

+0

「簡單地做一個return語句不會返回任何東西給請求者」這是不正確的。 Flask將函數的返回值自動轉換爲Response對象。 http://flask.pocoo.org/docs/0.10/quickstart/#about-responses –

0

在你的教程,場景,Node.js的應用程序發送一個HTTP POST請求回到Facebook的服務器,然後將內容轉發給客戶端。

到目前爲止,聽起來像你的瓶應用僅接收(AKA 服務)的HTTP請求。原因在於這就是Flask圖書館的全部內容,也是Flask唯一的作用。

若要發送一個HTTP請求回Facebook,您可以使用任何你喜歡的Python HTTP客戶端庫。標準庫中有一個名爲urllib,但使用起來有點笨拙......試試Requests庫。

由於您的請求處理程序正在委託傳出的HTTP調用,您還需要查看對此子請求的響應,以確保一切按計劃進行。

你的處理程序最終可能看起來像

import json 
import os 
from flask import app, request 
# confusingly similar name, keep these straight in your head 
import requests 

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

# good practice: don't keep secrets in files, one day you'll accidentally 
# commit it and push it to github and then you'll be sad. in bash: 
# $ export FB_ACCESS_TOKEN=my-secret-fb-token 
FB_TOKEN = os.environ['FB_ACCESS_TOKEN'] 


@app.route('/', method="POST") 
def chatbot_response(): 
    data = request.json() # flasks's request object 
    sender_id = data["entry"][0]["messaging"][0]["sender"]["id"] 
    send_back_to_fb = { 
     "recipient": { 
      "id": sender_id, 
     }, 
     "message": "this is a test response message" 
    } 

    # the big change: use another library to send an HTTP request back to FB 
    fb_response = requests.post(FB_MESSAGES_ENDPOINT, 
           params={"access_token": FB_TOKEN}, 
           data=json.dumps(send_back_to_fb)) 

    # 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) 

    # always return 200 to Facebook's original POST request so they know you 
    # handled their request 
    return "OK", 200 
+0

感謝您的幫助!我嘗試運行你的例子,並從FB中得到以下響應:「jeepers。400:{」error「:{」message「:」(#100)param recipient must be non-empty。「,」type「:」OAuthException「 ,「code」:100,「fbtrace_id」:「」}「。我也試着用(「recipient」:sender_id)鍵/值對修改上面的post請求的params參數,但是我仍然得到相同的錯誤。因爲sender_id絕對是一個實際的數值,所以很奇怪。有什麼想法嗎? – MEric

+0

有兩個途徑可以實現:首先,在調用過程中使用'print sender_id'或'print send_back_to_fb'進行調試,仔細檢查實際發送的值是否合理 - 做一個真正的愚蠢的完整性檢查總是一個好主意。第二,也許FB需要你的請求中正確的「application/json」頭文件來理解你發送的內容,試着在'json' kwarg中傳遞數據(非序列化):'requests.post(FB_MESSAGES_ENDPOINT,params = { 「access_token」:FB_TOKEN},json = send_back_to_fb)' –

+0

針對Facebook的另一個方便的調試工具特別好,因爲它們的文檔有時會混淆或過時:請嘗試https://developers.facebook.com/上的圖形瀏覽器工具。工具/資源管理器/ ...你可以很容易地重建和玩你嘗試的POST請求,同時消除了一些複雜的大型雙向交互。 –

0

這是對我的作品的代碼:

data = json.loads(request.data)['entry'][0]['messaging'] 
for m in data: 
    resp_id = m['sender']['id'] 
    resp_mess = { 
    'recipient': { 
     'id': resp_id, 
    }, 
    'message': { 
     'text': m['message']['text'], 
    } 
    } 
    fb_response = requests.post(FB_MESSAGES_ENDPOINT, 
           params={"access_token": FB_TOKEN}, 
           data=json.dumps(resp_mess), 
           headers = {'content-type': 'application/json'}) 

主要區別:

message需要爲實際一個text關鍵響應消息,並且您需要添加application/jsoncontent-type標題。

沒有content-type頭你得到The parameter recipient is required錯誤響應,沒有messagetext鍵你得到param message must be non-empty錯誤響應。

1

這是使用fbmq library的瓶的例子,對我的作品:

回聲例如:

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)