2017-10-05 96 views
-2

我想发送音频文件给用户在Facebook messenger使用文件上传。 官方文档说你可以通过curl命令在终端中完成。 此命令的工作:发送音频给用户在Facebook messenger bot

curl \ 
    -F 'recipient={"id":user_id}' \ 
    -F 'message={"attachment":{"type":"audio", "payload":{}}}' \ 
    -F '[email protected];type=audio/mp3' \ 
    "https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN" 

其中ACCESS_TOKEN我的网页标记,“mymp3.mp3”是我要发送的文件。

问题 - 如何在使用请求库的python中执行相同的操作?

我尝试这样做:

with open("mymp3.mp3", "rb") as o: 
    payload = { 
     'recipient': "{id: 1336677726453307}", 
     'message': {'attachment': {'type': 'audio', 'payload':{}}}, 
     'filedata':o, 'type':'audio/mp3' 
    } 
    files = {'recipient': {'id': '1336677726453307'},'filedata':o} 
    headers = {'Content-Type': 'audio/mp3'} 
    r = requests.post(fb_url, data=payload) 
print r.text 

我得到这个错误:

{"error":{"message":"(#100) Message cannot be empty, must provide valid attachment or text","type":"OAuthException","code":100,"error_subcode":2018034,"fbtrace_id":"E5d95+ILnf5"}} 

此外,尝试这样做:

import requests 
from requests_toolbelt import MultipartEncoder 

m = MultipartEncoder(
    fields={ 
     'recipient': {'id': '1336677726453307'}, 
     'message': {'attachment': {'type': 'audio', 'payload':{}}}, 
     'filedata':(open("mymp3.mp3", "rb"), 'audio/mp3') 
    } 
) 
headers = {'Content-Type': m.content_type} 
r = requests.post(fb_url, data=m, headers=headers) 
print r.text 

我得到这个错误: AttributeError的: '快译通'对象没有属性'编码'

+0

https://stackoverflow.com/questions/25491090(非常感谢我的同事!)/how-to-use-python-to-execute-a-curl-command – luschn

+0

https://stackoverflow.com/questions/2667509/curl-alternative-in-python – luschn

+0

只是google上的第2个结果;) – luschn

回答

0

OK,我知道了

fb_url = 'https://graph.facebook.com/v2.6/me/messages' 
data = { 
    'recipient': '{"id":1336677726453307}', 
    'message': '{"attachment":{"type":"audio", "payload":{}}}' 
} 
files = { 
    'filedata': ('mymp3.mp3', open("mymp3.mp3", "rb"), 'audio/mp3')} 
params = {'access_token': ACCESS_TOKEN} 
resp = requests.post(fb_url, params=params, data=data, files=files) 
0

我认为你的第一次尝试就是靠近目标,但你似乎很难与文件上传。 您首先需要了解curl的功能; curl documentation is here。然后对请求做同样的事情;文档是here

据我了解,你可以试试:

with open("mymp3.mp3", "rb") as finput: 
    data = { 
     'recipient': "{id: 1336677726453307}", 
     'message': {'attachment': {'type': 'audio', 'payload':{}}}, 
    } 
    # 
    files = {'filedata': ('mymp3.mp3', finput, 'audio/mp3')} 
    # BTW you can remove the ACCESS_TOKEN from fb_url and pass it as params instead 
    params = {'access_token': 'ACCESS_TOKEN'} 
    resp = requests.post(fb_url, params=params, data=data, files=files) 

print r.text 
+0

我收到此错误: {“error”:{“message”:“(#100)消息不能为空,必须提供有效的附件或文本”,“type”: “OAuthException”, “代码”:100, “error_subcode”:2018034, “fbtrace_id”: “HTjHVPM0grB”}} –