Closed eladcandroid closed 1 month ago
is it okay if we add this to the library?
Great idea! I'll add it to the roadmap
i tried to add a function, but not sure what "file" they expect, this does not work
const postImage = async (file, type) => {
return new Promise((resolve, reject) => {
var bodyFormData = new FormData();
bodyFormData.append('file', fs.createReadStream(file));
bodyFormData.append('type', type);
bodyFormData.append('messaging_product', 'whatsapp');
axios({
method: "post",
url: https://graph.facebook.com/v15.0/${from}/media
,
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data", 'Authorization': 'Bearer ' + token },
})
.then(function (response) {
console.log(response);
resolve(response.id);
})
.catch(function (error) {
console.log(error);
reject(error);
});
});
}
I use the following function to get the media Id of the local file:
async function getMediaID(filePath) {
try {
let data = new FormData();
data.append('messaging_product', 'whatsapp');
data.append('file', fs.createReadStream(filePath));
const config = {
method: 'post',
url: `https://graph.facebook.com/v15.0/${Meta_WA_SenderPhoneNumberId}/media`,
headers: {
'Authorization': 'Bearer ' + Meta_WA_AccessToken,
'Content-Type': 'multipart/form-data',
...data.getHeaders()
},
data : data
};
const response = await axios(config);
return response.data.id;
} catch (err) {
console.error(err);
}
}
where filePath would be relative to your project, example: './localfolder/testfile.xlsx'
Closing - please read more here.
See this for information on how to upload a file: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#get-media-id
Once uploaded, you can use
bot.sendDocument()
with the media id.