Send image URL using whatsapp-web.js

To send an image with a URL using whatsapp-web.js, you can use the Client.sendImage method with the url parameter. Here is an example code:

const fs = require('fs');
const path = require('path');
const axios = require('axios');
const qrcode = require('qrcode-terminal');
const { Client , MessageMedia } = require('whatsapp-web.js');

const client = new Client();
const folderPath = 'D:/xampp/htdocs/api-whatsapp/downloads';

function sendFileFromUrl(chatId, message, fileUrl) {
    const filename = path.basename(fileUrl);
    const filePath = path.join(folderPath, filename);

    axios({
      url: fileUrl,
      responseType: 'stream'
    }).then(response => {
      response.data.pipe(fs.createWriteStream(filePath));
      response.data.on('error', err => {
        console.error(err);
      });
      response.data.on('end', () => {
        console.log('File downloaded successfully!');
        const media = MessageMedia.fromFilePath(filePath);
        client.sendMessage(chatId, media, message).then(() => {
            console.log('sent successfully!');
            fs.unlinkSync(filePath);
        }).catch((err) => {
            console.error('Error sending: ', err);
            fs.unlinkSync(filePath);
        });
      });
    }).catch(err => {
      console.error(err);
    });  
}

client.on('qr', (qr) => {
    qrcode.generate(qr, {small: true});
});

client.on('ready', () => {
    console.log('Client is ready!');

    const chatId = '62123456789@c.us';
    const message = 'This is file';
    const fileUrl = 'https://pmb.uii.ac.id/wp-content/uploads/2020/04/Panduan-Merubah-Dokumen-ke-Format-PDF-Secara-Online.pdf';
    sendFileFromUrl(chatId, message, fileUrl);
});

client.initialize();

Komentar

Postingan populer dari blog ini

Node.js Telegram Bot API send an image with text

Node.js Telegram BOT retrieve data from API

WhatsApp Web login QR code in an HTML page using whatsapp-web.js