Add example for downloading message media

This commit is contained in:
Nur Muhammad
2021-08-02 15:43:45 +08:00
parent 4bfd9118fc
commit 2b7756b764
4 changed files with 51 additions and 4 deletions

40
app.js
View File

@@ -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();