How to send an image to Whatsapp in Python using the Cloud API?
As far as I understood, the process is:
Sources: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#upload-media https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages https://developers.facebook.com/docs/whatsapp/cloud-api/messages/image-messages/
Thus, code to UPLOAD the image (seems ok):
url = f"https://graph.facebook.com/v15.0/{config_WA['PHONE_NUMBER_ID']}/media"
headers = {'Authorization': 'Bearer ' + config_WA['ACCESS_TOKEN']}
files = {
'file': ('filename.jpeg', open('filename.jpeg', 'rb'), 'image/jpeg', {'Expires': '0'}),
}
data = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
}
upload_media = requests.post(
url,
data={
'messaging_product' : 'whatsapp',
'type': 'image/png',
},
files=files,
headers=headers
)
Code to retrieve the image, showing it is indeed there (seems ok):
# Open image uploaded
url = f'https://graph.facebook.com/v20.0/{id}/'
#-H 'Authorization: Bearer <ACCESS_TOKEN>'
image = requests.post(
url,
headers=headers
)
response = requests.get(image.url, headers=headers) # get the file binary
# save the received file
print(response.content)
And then, code to SEND the image:
url = "https://graph.facebook.com/v17.0/"+config_WA['PHONE_NUMBER_ID']+"/messages"
# Headers
headers = {
"Content-type": "application/json",
'Authorization': 'Bearer '+config_WA['ACCESS_TOKEN']
}
data = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": "+5521972832146",
"type": "image",
"image": {
"id" : id,
"caption": "The best succulent ever?"
}
}
send_media = requests.post(
url,
data= data,
headers=headers
)
It runs but I get a "Response [400]"
, and send_media.text
returns:
{"error":{"message":"(#100) Param image must be a JSON object.","type":"OAuthException","code":100,"fbtrace_id":"A64oeOdpaY7e7WjoPChkcfz"}}
You can send a JSON object like that:
send_media = requests.post(
url,
json=data,
headers=headers
)