我想发送音频文件给用户在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的: '快译通'对象没有属性'编码'
https://stackoverflow.com/questions/25491090(非常感谢我的同事!)/how-to-use-python-to-execute-a-curl-command – luschn
https://stackoverflow.com/questions/2667509/curl-alternative-in-python – luschn
只是google上的第2个结果;) – luschn