Issue
I'm trying to send audio file to user in Facebook messenger bot using file upload. Official documentation says you can do it through curl command in terminal. This command works:
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"
where ACCESS_TOKEN is my page's token, "mymp3.mp3" is the file I want to send.
Question - how do I do the same in python using requests library?
I tried this:
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
I get this error:
{"error":{"message":"(#100) Message cannot be empty, must provide valid attachment or text","type":"OAuthException","code":100,"error_subcode":2018034,"fbtrace_id":"E5d95+ILnf5"}}
Also, tried this:
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
I got this error: AttributeError: 'dict' object has no attribute 'encode'
Solution
OK, I got it (big thanks to my colleague!)
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)
Answered By - Alikhan Amandyk