mirror of
https://github.com/cheveguerra/whatsapp-api-tutorial.git
synced 2026-04-17 19:36:59 +00:00
Add example for downloading message media
This commit is contained in:
40
app.js
40
app.js
@@ -8,6 +8,9 @@ const fs = require('fs');
|
||||
const { phoneNumberFormatter } = require('./helpers/formatter');
|
||||
const fileUpload = require('express-fileupload');
|
||||
const axios = require('axios');
|
||||
const mime = require('mime-types');
|
||||
const { Z_ERRNO } = require('zlib');
|
||||
|
||||
const port = process.env.PORT || 8000;
|
||||
|
||||
const app = express();
|
||||
@@ -73,6 +76,43 @@ client.on('message', msg => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Downloading media
|
||||
if (msg.hasMedia) {
|
||||
msg.downloadMedia().then(media => {
|
||||
// To better understanding
|
||||
// Please look at the console what data we get
|
||||
console.log(media);
|
||||
|
||||
if (media) {
|
||||
// The folder to store: change as you want!
|
||||
// Create if not exists
|
||||
const mediaPath = './downloaded-media/';
|
||||
|
||||
if (!fs.existsSync(mediaPath)) {
|
||||
fs.mkdirSync(mediaPath);
|
||||
}
|
||||
|
||||
// Get the file extension by mime-type
|
||||
const extension = mime.extension(media.mimetype);
|
||||
|
||||
// Filename: change as you want!
|
||||
// I will use the time for this example
|
||||
// Why not use media.filename? Because the value is not certain exists
|
||||
const filename = new Date().getTime();
|
||||
|
||||
const fullFilename = mediaPath + filename + '.' + extension;
|
||||
|
||||
// Save to file
|
||||
try {
|
||||
fs.writeFileSync(fullFilename, media.data, { encoding: 'base64' });
|
||||
console.log('File downloaded successfully!', fullFilename);
|
||||
} catch (err) {
|
||||
console.log('Failed to save the file:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
client.initialize();
|
||||
|
||||
Reference in New Issue
Block a user