Facebook Messenger API 无法发送附件
Facebook Messenger API can't send attachments
我正在尝试使用 Python 请求通过 Facebook API 发送附件,但我不断收到以下错误:
"message":"(#100) The parameter recipient is required"
我的代码是:
import requests
url = "https://graph.facebook.com/v6.0/me/messages?access_token=<API_TOKEN>"
headers = {
'Content-Type': 'multipart/form-data;'
}
payload = {
'recipient': {"id": user_id},
'message': {
"attachment": {
"type": "image",
"payload": {}
}
},
}
files = {
'filedata': open('C:/Users/user-pc/Downloads/duck.jpg', 'rb')
}
response = requests.post(url, headers=headers, data=payload, files=files)
我的代码基于以下两个链接:
https://developers.facebook.com/docs/messenger-platform/send-messages/#file
https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api/
注意:我确实设法使用 CURL 并通过 Postman 进行了发送。
次要说明,是否可以仅使用附件的字节字符串发送附件?那不是需要文件的实际路径,我将如何在服务器环境中执行此操作?
使用 https://webhook.site/ 我正在检查我发送到 Facebook 的内容,我发现它实际上并没有正确处理我字典中的 Key-Value 对。所以通过一些实验,我发现你需要使用元组,不完全确定为什么,如果有人能解释一下,我将不胜感激。
import requests
url = "https://graph.facebook.com/v6.0/me/messages?access_token=<API_Key>"
payload = {
'recipient': (None, {"id": user_id}),
'message': (None, {"attachment": {"type": "image", "payload": {}}}),
}
files = {
'filedata': ('duck', open('C:/Users/user-pc/Downloads/duck.jpg', 'rb'), 'image/jpg')
}
response = requests.post(url, data=payload, files=files)
print(response.text.encode('utf8'))
headers 似乎也不是真正必要的,因为 Requests 库似乎会自动处理它。
正如@CBroe 所提到的,路径并不重要,因为它无论如何都会读取二进制数据。
我正在尝试使用 Python 请求通过 Facebook API 发送附件,但我不断收到以下错误:
"message":"(#100) The parameter recipient is required"
我的代码是:
import requests
url = "https://graph.facebook.com/v6.0/me/messages?access_token=<API_TOKEN>"
headers = {
'Content-Type': 'multipart/form-data;'
}
payload = {
'recipient': {"id": user_id},
'message': {
"attachment": {
"type": "image",
"payload": {}
}
},
}
files = {
'filedata': open('C:/Users/user-pc/Downloads/duck.jpg', 'rb')
}
response = requests.post(url, headers=headers, data=payload, files=files)
我的代码基于以下两个链接:
https://developers.facebook.com/docs/messenger-platform/send-messages/#file
https://developers.facebook.com/docs/messenger-platform/reference/attachment-upload-api/
注意:我确实设法使用 CURL 并通过 Postman 进行了发送。
次要说明,是否可以仅使用附件的字节字符串发送附件?那不是需要文件的实际路径,我将如何在服务器环境中执行此操作?
使用 https://webhook.site/ 我正在检查我发送到 Facebook 的内容,我发现它实际上并没有正确处理我字典中的 Key-Value 对。所以通过一些实验,我发现你需要使用元组,不完全确定为什么,如果有人能解释一下,我将不胜感激。
import requests
url = "https://graph.facebook.com/v6.0/me/messages?access_token=<API_Key>"
payload = {
'recipient': (None, {"id": user_id}),
'message': (None, {"attachment": {"type": "image", "payload": {}}}),
}
files = {
'filedata': ('duck', open('C:/Users/user-pc/Downloads/duck.jpg', 'rb'), 'image/jpg')
}
response = requests.post(url, data=payload, files=files)
print(response.text.encode('utf8'))
headers 似乎也不是真正必要的,因为 Requests 库似乎会自动处理它。
正如@CBroe 所提到的,路径并不重要,因为它无论如何都会读取二进制数据。