Send image message(path) with whatsapp-web.js
To send an image using the WhatsApp Web API and Node.js, you need to first convert the image file into a base64-encoded string. You can do this using the Node.js built-in fs module and the readFileSync() function to read the file contents, and the encoding function to convert it to a base64:
const fs = require('fs'); const path = require('path'); const filePath = '/path/to/image.jpg'; const image = fs.readFileSync(filePath, { encoding: 'base64' });
Once you have the image encoded as a base64 string, you can use the sendImage method of the Client object in whatsapp-web.js to send it to a contact or group:
const {Client , MessageMedia} = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); const client = new Client(); async function sendFileFromPath(chatId, filePath, message) { const fileData = fs.readFileSync(filePath, { encoding: 'base64' }); const chat = await client.getChatById(chatId); chat.sendMessage(new MessageMedia('image/jpg', fileData, 'image.jpg'), { caption: message }).then(() => { console.log('Media sent successfully'); }).catch((err) => { console.error('Error sending media:', err); }); } client.on('qr', qr => { qrcode.generate(qr, {small: true}); }); client.on('ready', () => { const chatId = '62123456789@c.us'; const message = 'This is an image file'; const filePath = 'D:/foto.jpg'; sendFileFromPath(chatId, filePath, message); }); client.initialize(); app.listen(3000, () => { console.log('SERVICE IS RUNNING'); });
Komentar
Posting Komentar