tawn33y / whatsapp-cloud-api

A Node.js library for creating bots and sending/receiving messages using the Whatsapp Cloud API.
https://www.npmjs.com/package/whatsapp-cloud-api
GNU General Public License v3.0
186 stars 51 forks source link

How can we send local files? #48

Closed eladcandroid closed 1 month ago

tawn33y commented 1 year ago

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.

yauluntang commented 1 year ago

is it okay if we add this to the library?

tawn33y commented 1 year ago

Great idea! I'll add it to the roadmap

yauluntang commented 1 year ago

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); }); }); }

tommygarces commented 1 year ago

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'

tawn33y commented 1 month ago

Closing - please read more here.