我想使用我的烧瓶应用程序向Facebook页面发送消息,但我一直收到400错误的请求错误,请问我在哪里做错了或有更好的方法来做到这一点。这是代码
import requests
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res = processRequest(req)
print(res)
url = 'https://graph.facebook.com/v2.6/me/messages'
payload = res
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r)
return r
def processRequest(req):
request = req.get("originalRequest")
first_data = request.get("data")
sender = first_data.get("sender")
user_id = sender.get("id")
speech = "hello"
print("Response:")
print(speech)
token ="my_access_token"
return {
"recipient": {
"id": user_id
},
"message": speech,
'access_token': token
}
if __name__ == "__main__":
port = int(os.getenv('PORT', 5000))
print("Starting app on port %d" % port)
app.run(debug=False, port=port, host='0.0.0.0')
请任何帮助表示赞赏。提前致谢
答案 0 :(得分:0)
您是否通过了有效的" access_token"在请求中?如果没有,服务器端将返回400错误请求错误。使用正确的" access_token"值,请求如下所示:
curl -X POST -H "Content-Type: application/json" -d '{
"recipient": {
"id": "USER_ID"
},
"message": {
"text": "hello, world!"
}
}' "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"
请阅读here的官方Facebook API参考资料,了解更多详情。